text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\section{Introduction} \label{sec:Introduction} \input{intro} \section{ML Model under DP} \label{sec:formulation} \input{formulation} \section{DP Forward-Propagation (DP-FP)} \label{sec:dpfp} \input{dp-fp} \section{Experiments} \label{sec:Experiments} \input{exps} \section{Related Work} \label{sec:RelatedWork} \input{related} \section{Discussion} It is instructive to compare the types of information that DP-SGD and DP-FP protect under DP. As illustrated in Eq.~(\ref{eqn:clipping-dpsgd}), in the DP-SGD, the label information is embedded in the gradient, thus the data record under DP protection is each pair of training data samples and their labels. While in the DP-FP, as illustrated in Eq.~(\ref{eqn:clipping-dpfp}), because the DP operation is performed in the forward stage, the data record under DP protection is simply the training data sample without labels. But, it is interesting to note that for the majority of classification tasks, one only needs to protect the privacy of the data sample, as the labels themselves are finite and not constitute privacy information as long as they cannot be connected to the training data sample. Consider the SST-2 sentence classification task as an illustration, which contains 67,500 sentences that require protection under DP. Additionally, each sentence is labeled with ``positive'' or ``negative''. Because DP-FP ensures that the adversary almost never recovers any sentence using the fine-tuned model, labels cannot be associated with the training sentences. However, in DP-FP for the generation task, protecting the label information is required and difficult, and further model architecture design is required. We plan to investigate it as part of our future work. \section{Conclusion} In this paper, we have introduced the differentially private forward propagation (DP-FP) method for applying differential privacy to large pretrained models on classification tasks. The key design of DP-FP exploits differential privacy's post-processing property, ensuring privacy by protecting the latent representation in the forward stage rather than the conventional wisdom of DP Stochastic Gradient Descent (DP-SGD), which protects the gradient in the backward stage. DP-FP has the same memory cost as an off-the-shelf SGD-based optimizer, an unbiased gradient, and significantly lower noise power that scales only with the latent representation dimension, as opposed to DP-SGD, which has a large memory cost, a biased gradient, and total noise power that scales with the huge model size. We have also created micro-batches that are unique to DP-FP in order to reduce the noise power for each coordinate. As a result, on a large model like RoBERTa-large, DP-FP achieves an average accuracy of 91.34\% on four downstream tasks with $\epsilon$ less than 3, which is only within 0.9\% lower than the non-private baseline and 3.81\% better than the state-of-the-art DP-SGD method. \subsection{Forward Propagation under DP} Let $X$ denote the entire training dataset and $\text S(X)$ be the subsampling scheme used to build a batch for each step of model update, such as shuffling and sampling with/without replacement, Poisson sampling. The latent representation is then denoted in a composition form of $h\circ \text S(X)$ with $h(\cdot)$ being the ML model for latent representation computation, e.g., the hidden state or pooler output of \texttt{[CLS]}\footnote{In this paper, we simply use the pooler output of \texttt{[CLS]} as our choice of $h(\cdot)$, since it is straightforward to integrate our DP at the outside of encoders for classification tasks, without changing any code inside encoders. Furthermore, it is much smaller in size than the transformer layers preceding the pooler.}. Note that subsampling schemes provide DP amplifications~\cite{wang2019subsampled,dong2021gaussian}, which reduce the amount of noise required under the same privacy budget. To achieve the forward propagation under DP, we first stabilize the latent representation. Because training data is random, the output of $h\circ \text S(X)$ can vary significantly, implying that the model will vary significantly if different data records are used for training. As a result, data privacy is at risk of being compromised by a membership attack. Thus, we constrain $h$'s output range by clipping the representation that corresponds to each data record, such as a sentence in a language model. We clip the output of $h(\cdot)$, which shrinks the latent representation whenever its $\ell_2$ norm exceeds a certain threshold $C$, similarly to DP-SGD. More formally, the clipped latent representation is given by \begin{equation} \label{eqn:clipping-dpfp} \mathrm{Clip}\left(h(\cdot), C\right) \triangleq h\cdot\min\left(1, \frac{C}{\|h(\cdot)\|_2}\right). \end{equation} The clipping operation also implies that the greatest variation output for a pair of neighboring datasets in terms of the $\ell_2$-norm is given by \begin{align*} C = \underset{ X \sim X^{\prime} }{\max}||h\circ \text S(X)-h\circ\text S(X^{\prime})||_2. \end{align*} Following clipping, Gaussian noise is added to ensure DP, with details on noise power $\sigma^2$ calibration provided later in this subsection. Before the downstream classification layer, the latent representation is computed as follows: \begin{equation} \label{eqn:dp-fp} \mathcal M(X)\triangleq \mathrm{Clip}\left(h\circ \text S(X), C\right) + \mathcal{N}\left(0, \sigma^2I_{k}\right). \end{equation} Since the input data is under DP according to Eq.~(\ref{eqn:dp-fp}), the model updated based on the result of Eq.~(\ref{eqn:dp-fp}) still follows the same DP assurance according to the post-processing property of DP~\cite[Proposition~2.1]{dwork2014algorithmic}. As a result, after Eq. (\ref{eqn:dp-fp}), a conventional SGD-based optimizer, such as Adam, can be used and the privacy of $X$ is still guaranteed. Until now, we identify the advantages of DP-FP over DP-SGD in the following propositions: \noindent \begin{proposition} \label{prop:noise-dim} \textbf{Small noise dimension in DP-FP}: It is worth noting that $I_k$ represents a $k$-dimension identity matrix, and therefore the noise vector dimension $k$ in DP-FP is much smaller than $d$, which is the noise vector dimension in Eq.~(\ref{eq:dpsgd}) that equals to the model dimension in DP-SGD. Take BERT for example, $d\approx$ 110M, whereas $k$ is only 768 if using the hidden state of \texttt{[CLS]} for downstream task. Thus, DP-FP saves significant total noise power than that for DP-SGD due to a significant noise dimension reduction. \end{proposition} \begin{proposition} \label{prop:unbiased-g} \textbf{ Unbiased gradient in DP-FP}: The results of Eq.~(\ref{eqn:dp-fp}) are then fed to the classifier, which predicts label distribution, computes the loss further, and then performs standard backpropagation via an off-the-shelf optimizer such as Adam for model update. As a result, the DP-FP backpropation inherits all of the advantages of the non-DP optimizer and produces an unbiased estimate of the true gradient. \end{proposition} \subsection{Micro-batch for DP Amplification\footnote{The micro-batch construction in our DP-FP is used to achieve DP amplification in order to reduce calibrated noise variance without sacrificing privacy, which is distinct from the micro-batch functionality used in Tensorflow Privacy to reduce the memory cost of the DP-SGD implementation.} in DP-FP} Intuitively, privacy amplification by subsampling is caused by the fact that individual data record has complete privacy if it is not included in the subsample. Based on this intuition, DP-SGD benefits from batch subsampling for DP amplification \citep{li2021large, yu2021large}, which reduces the calibrated noise power for each coordinate significantly. In contrast to DP-SGD, we show that additional DP amplification can be achieved by subsampling out $M$ micro-batches that comprise a batch, resulting in lower noise power for each coordinate of the $k$-dimension noise vector in Eq.~(\ref{eqn:dp-fp}). Because of the unique structure for DP operations in forward propagation, this DP amplification is unique to DP-FP and does not exist in DP-SGD, as discussed further below. More concretely, an independent Bernoulli trial for all data records, i.e., sentences in a dataset, is performed to construct each micro-batch with subsampling probability $p$. Clipping is applied to each latent representation corresponding to the input data record, i.e., clip the hidden state of \texttt{[CLS]} in the BERT model. In the following, we evaluate the privacy cost using the Gaussian DP (GDP) framework~\citep{dong2021gaussian}, which measures the privacy profile $(\epsilon, \delta)$ in terms of $\mu = C/\sigma$ using Eq.~(\ref{eqn:compute_eps}) and (\ref{eqn:mu}). To make our paper self-contained, we include a preliminary of GDP calculation in Appendix~\ref{app:GDP}, as well as a more detailed procedure for privacy accounting described below. \begin{table*} \centering \scalebox{0.9}{ \begin{tabular}{c|c c c c } \hline & DP-SGD & DP-FP & RGP & SGD \\ \hline Memory cost & $\mathcal O(md)$ & $\mathcal O(d)$ & $\mathcal O(m r w)$ & $\mathcal O(d)$ \\ Computational cost & $\mathcal O(md)$ & $\mathcal O(md)$ & $ \mathcal{O}\left(m d+K r d+K r^{2}w\right) $ & $\mathcal O(md)$ \\ Coordinates \# to add noise & $\mathcal O(d)$ & $\mathcal O(k)$ & $\mathcal O(w)$ & -- \\ Noise power at each coordinate & $\sigma^2$ & $\frac{1}{M}\sigma^2$ &$\sigma^2$ &-- \\ \hline \end{tabular}} \caption{For all methods, $m$ is the batch size, and $d$ is the model size. In our DP-FP, $k$ and $M$ are the latent representation dimension used for downstream tasks and micro-batch number, respectively. Note that $k\ll d$, e.g. in the experiment $k=768$ while $d=3$ Million for BERT model. Specifically for RGP in~\citet{yu2021large}, $w$ is the model width, $r$ is the reparametrization rank, and $K$ is the number of power iterations.\protect\footnotemark{}} \label{table:cmp} \end{table*} According to the subsampling DP amplification in the Gaussian DP framework~\citep{bu2020deep}, the privacy cost corresponding to each micro-batch is given by \begin{equation} p\cdot G_{\mu}+(1-p) \text { Id }, \end{equation} where $ G_{\mu}$ is a function of $\mathcal{N}(0,1)$ and $\mathcal{N}(\mu, 1)$ with $\mu = C/\sigma$ and $\text { Id }(\alpha)=1-\alpha$. The details of function $ G_{\mu}(\alpha)$ is given in the appendix. In each step, the training stage executes $M$ micro-batches and updates $T$ steps based on the training dataset. Even if each micro-step is DP protected with a privacy cost of $(\epsilon, \delta)$, the question is whether all $T\times M$ micro-batches are private when combined, and if so, how privacy degrades as the number of steps increases, a process known as DP composition. We have the total privacy cost according to the central limit theorem for $T\cdot M$ rounds Gaussian DP composition given by \begin{equation} \label{eqn:gdp-clt-dpfp} \mu_{\text{tot}} = p\cdot \sqrt{T\cdot M \left(\mathrm{e}^{(C/\sigma)^2}-1\right)}, \end{equation} with details provided in the appendix. It is evident that the smaller $p$ is, the smaller the total privacy cost denoted by $\mu_{\text{tot}}$. Similarly in DP-SGD~\cite{li2021large} with subsampling probability $\widetilde p$ to construct the mini-batch, the total privacy cost is given by \begin{equation} \label{eqn:gdp-clt-dpsgd} \widetilde \mu_{\text{tot}} = \widetilde p\cdot \sqrt{T \left(\mathrm{e}^{\widetilde \mu^2}-1\right)}, \end{equation} where $\widetilde \mu = C/\widetilde \sigma$. To make a fair comparison, DP-FC is set to have the same batch size in expectation as DP-SGD by setting $\widetilde p=p \cdot M$. In the strong DP regime, $\mu$ and $\widetilde \mu$ are very small positive values close to zero. Thus, by taking the Taylor series expansion of the exponential function in (\ref{eqn:gdp-clt-dpfp}) and (\ref{eqn:gdp-clt-dpsgd}), respectively and taking into account the fact that $ \mu_{\text{tot}} = \widetilde \mu_{\text{tot}} $ for the same privacy budget, we obtain $$ \frac{\sigma^2}{\widetilde\sigma^{2}}= \frac{1}{{M}}.$$ As a result, we have the third advantage of DP-FP over DP-SGD: \begin{proposition} \label{prop:noise-power}\textbf{ As with DP-SGD, DP-FP requires less than $1/M$ noise power per coordinate.} Note that the comparison is under the same batch-size, privacy budget, and clipping value. However, as demonstrated in~\citet{li2021large}, larger batch sizes improve performance in their DP-SGD. As demonstrated later in the experiment, our DP-FP, on the other hand, prefers small batch sizes. Due to the fact that each batch is constructed by randomly sampling each data record, the batch size decreases as $p$ decreases. Thus, $\sigma^2$ is even smaller than $\frac{1}{M}\widetilde{\sigma}^2$ according to Eq.~(\ref{eqn:gdp-clt-dpfp}). \end{proposition} Finally, we summarize the DP-FP algorithm in Algorithm~\ref{alg:DP-FP}, including the micro-batch construction for DP amplification. Since the noise power in each step is calibrated according to the DP budget of $(\epsilon, \delta)$ and total steps $T$, $(\epsilon, \delta)$ is spent out after $T$ steps. \begin{algorithm}[t] \caption{DP-FP Training} \label{alg:DP-FP} \begin{algorithmic}[1] \REQUIRE DP budget $(\epsilon,\delta)$, sampling rate $p$, clipping threshold $C$, and representation $h(\cdot)$. \STATE Put $(\epsilon, \delta)$ into (\ref{eqn:compute_eps}) and compute $\mu$ as $\mu_{\text{tot}}$. \STATE Calibrate noise power $\sigma^2$ by substituting $\mu_{\text{tot}}$, $T$, $M$, and $C$ into~(\ref{eqn:gdp-clt-dpfp}). \FOR{$t=1, \ldots, T$} \FOR[$\triangleright$ $M$ micro-batches in each step:]{$m=1, \ldots, M$ in parallel} \STATE Sample micro-batch $x_m$ with Bernoulli trail for each data record \STATE $\widetilde x_m \gets \text{Clip}\left(h(x_m);C\right) + \mathcal{N}(0, \sigma^2 I_k)$ \STATE $w\gets \text{optimizer}(\widetilde x_m, w )$ \COMMENT{$\triangleright$ SGD-based off-the-shelf optimizer for model update} \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \subsection{Comparison to existing methods} In contrast to SGD, DP-SGD necessitates the computation and storage of individual gradients, resulting in batch- and model-size-dependent memory costs. Furthermore, the total noise power in DP-SGD scales linearly with model size. As a result, applying DP-SGD to large-scale models is difficult. \citet{li2021large} propose ghost clipping, a memory-saving technique that allows clipping in DP-SGD to run without instantiating per-example gradients. By extending the method in \citet{lee2020scaling}, ghost clipping consumes nearly the same memory as non-private SGD training while doubling the computation throughput via numerical validation. As a result, we use the memory and computational cost of SGD as a reference for ghost clipping. We also compare the costs of the most recent memory efficient method, reparameterized gradient perturbation (RGP)~\citep{yu2021large}. While RGP is faster per update, it requires more than three times as many epochs as the ghost clipping method as pointed out by~\citet{li2021large}. \footnotetext{We use slightly different symbol notion for complexity analysis from that in~\cite{yu2021large} without assuming the weight matrix is square as that in ~\cite{yu2021large}.} \subsection{Data and Settings} Following \newcite{li2021large}, we mainly focus on fine-tuning large pretrained models on classification tasks, including MNLI, QQP, QNLI, and SST-2 from the GLUE benchmark~\cite{wang2018glue} that each has more than 60k training instances. We provide the data statistics for the four tasks in Appendix~\ref{app:statistics}. Our non differential privacy (Non-DP) baselines are finetuned BERT-base, RoBERTa-base, and RoBERTa-large. For classification task, following common settings, we add a linear layer over the output of the pooler layer for encoder, the pooler layer simply takes the hidden state of \texttt{[CLS]} token as input, and applies another linear dense layer and a $tanh(\cdot)$ activation. We train our baselines on four data sets for 5 epochs with a learning rate $2\times 10^{-5}$, a batch size $32$, and a max input length $128$. We save and validate each model for each epoch, and report the best accuracy scores as our baseline systems. During the fine-tuning stage, our DP-FP method adds noise and clipping operations (as in Algorithm~\ref{alg:DP-FP}) before the linear classification layer based on the following two facts. First this approach treats pretrained model encoder classes as black boxes and does not require any code change inside encoder classes. Second, typically for large-pretrained models, the noise dimension, i.e., 768 for BERT-base and RoBERTa-base, and 1024 for RoBERT-large, is fixed and much smaller than the model size, i.e., 110M for BERT-base. Then we apply standard AdamW~\cite{adamw} optimizer in the back-propagation stage. Please note that we do not add any noise and clippings in the inference time, as we only need to protect the fine-tuning training data. In our following experiments, we use the following hyper-parameters as our default settings for our DP-FP method: total fine-tuning epoch is three, $M = 32$, $C=1.0$, learning rate is $5 \times 10^{-6}$, max input length is $128$, the micro-batch subsampling rate $p=\frac{B}{M\cdot D}$ and the expected batch size $B=32$. We consider a practical scenario in which the total amount of privacy budget $(\epsilon, \delta)$ is constrained. For both DP-FP and DP-SGD, this privacy budget constraint corresponds to a constraint on the number of data samples used in the tuning process. As a result, we report accuracy scores on development sets once the privacy budget has been depleted. \footnotetext{The results for SGD$^*$ and RGP$^*$ in Table~\ref{table:main_results} are from documented numbers in~\citet{yu2021large}. These results are under the DP guarantees of $\delta=10^{-5})$. These guarantees are strictly weaker than those provided by DP-SGD$^+$ and our DP-FP, which are based on $\delta = 1/2D$ (note that the smallest dataset in these tasks contains $D>60$k records).} To ensure a fair comparison with the DP-SGD method in large-scale models reported in the literature, we set the same privacy budget for Gaussian DP with CLT as that in~\citet{li2021large} for each experiment using $\epsilon$ in the set $\{1.73, 2, 2.52, 4.33, 4.75, 5.83, 5.85\}$ and $\delta = 1/2D $ with $D$ the data record number in the training set. We then numerically calibrate $\sigma^2$ as in Line 2 of Algorithm~\ref{alg:DP-FP}. We also report the corresponding total privacy cost documented in~\citep{li2021large} calculated by RDP and composing tradeoff function methods. Please see Section~\ref{sec:pre} and the references therein for further information. \subsection{Main Results} Table~\ref{table:main_results} shows the main results on four tasks. The larger the pretrained models, the higher the accuracies for the non-DP baselines, ranging from BERT-base (110M parameters) to RoBERTa-large (355M parameters). We compare full fine-tuning with reparameterized gradient perturbation (RGP)~\citep{yu2021large}, and memory efficient DP-SGD for large language model~\citep{li2021large} as they are the state-of-the-art methods for DP fine-tuning on sentence classification at the time of writing. The DP-SGD scores are documented in \newcite{li2021large}, and DP-SGD hurts the baseline performance by 4-6$\%$ in average for RoBERTa-base and RoBERTa-large, even with a larger $\epsilon$ at 8 (RDP). In particular, results of RoBERTa-base models show that DP-SGD still degrades performance by up to 8$\%$ for the SST-2 data set. By contrast, RGP of \newcite{yu2021large} reduces the gap significantly to 1$\%$ point on SST-2 data set, but is still at least 4$\%$ far behind Non-DP BERT-base on other three tasks. We run DP-FP on each level of the privacy budget for three epochs of steps, and report the final scores only for the model reaches the privacy budget. Note that, we use the default setting and same hyper-parameters as illustrated in the previous subsection for each experiment of our DP-FP in Table~\ref{table:main_results}. As shown in Table~\ref{table:main_results}, DP-FP significantly improves accuracy over existing methods and closes the gap to the Non-DP counterpart. It has only a 0.58$\%$ performance drop for SST2 on RoBERTa-large with $\epsilon$ set to 1.73 under GDP with CLT in particular. We further average this DP-FP performance drops across datasets for each of the models. When $\epsilon=3$ (RDP), the average performance drops to Non-DP model are within 0.83-1.78$\%$; and when $\epsilon=8$, they are within 0.68-1.43$\%$. Moreover, DP-FP is clearly better than DP-SGD and RGP approaches. This significant performance advantage stems in part from the fact that DP-FP overcomes the biased gradient problem in DP-SGD and also has a lower noise power due to micro-batch number as well as a lower noise dimension. More interestingly, the larger the pretrained model, the smaller the gap to the Non-DP model for DP-FP. For example, on the SST-2 task for $\epsilon=3$ (RDP), the gap between DP-FP and Non-DP is reduced from 2.41$\%$ (BERT-base) to 0.58$\%$ (RoBERTa-large). The main reason for this, we believe, is that because our DP-FP adds noise to the latent representation before the linear classification layer, the total noise power does not scale with model size. \begin{figure} \centering \includegraphics[width=.45\textwidth]{"batch_size.png"} \abovecaptionskip=2pt \caption{Accuracy scores for different batch sizes ($B$) on SST-2 development set.} \label{fig:batch_heatmap} \end{figure} \subsection{Hyperparameter Tuning} As suggested in~\newcite{li2021large}, DP optimization is sensitive to hyper-parameter selection. We therfore examine the performance of DP-FP for various hyper-parameters, as our DP-FP differs significantly from DP-SGD in terms of architecture. In this section, we report all results of RoBERTa-base with DP-FP on SST-2 data set, and we fix the total training epochs to be 3 to deplete the privacy budget, i.e., $(\epsilon,\delta)=(3,1/2D)$. Figure~\ref{fig:batch_heatmap} shows the heat map of accuracy scores for different batch sizes with $M = 1$ and $C = 1.0$. Those results suggest that 1) large batch sizes, like 128 and 256, hurt performance; 2) DP-FP requires a small learning rate in order to achieve better performance. Those two interesting observations are opposite of the findings of DP-SGD in~\newcite{li2021large}. The intuitive explanation is given below. By substituting $p=B/(M\cdot D)$ into Eq.~(\ref{eqn:gdp-clt-dpfp}), we have the privacy parameter \begin{equation} \label{eqn:exp} \mu_{\text{tot}} = \frac{B}{M\cdot D} \sqrt{T\cdot M \left(\mathrm{e}^{(C/\sigma)^2}-1\right)}. \end{equation} Intuitively, this demonstrates that, given a fixed privacy budget, which implies a fixed $\mu_{\text{tot}}$, noise power $\sigma^2$ decreases as batch-size $B$ decreases. However, we cannot reduce $B$ too much because the model will not converge. \begin{figure} \centering \includegraphics[width=.45\textwidth]{"clipping_norms.png"} \abovecaptionskip=2pt \caption{Accuracy scores for different clipping threshold ($C$) on SST-2 development set.} \label{fig:clip_heatmap} \end{figure} \begin{figure} \centering \includegraphics[width=.45\textwidth]{"micro_batch.png"} \abovecaptionskip=2pt \caption{Accuracy curve for different micro-batch numbers ($M$) on SST-2 development set.} \label{fig:micro_batch_curve} \end{figure} Figure~\ref{fig:clip_heatmap} shows the heat map of accuracy scores for different clipping threshold ($C$) with $\epsilon = 3$, $M = 1$, and $B = 32$. \newcite{li2021large} show that small clipping thresholds lead to the best performance by setting $C=0.1$. In contrast, we find different trends from that in~\newcite{li2021large} such that smaller clipping thresholds lower than 0.4 actually hurt performance, and there is no significant changes in larger clipping thresholds (from 0.6 to 1.0). Removing too much of the latent representation with a small $C$ in DP-FC results in too much loss of semantic information and leads to significant performance drop. Finally, Figure~\ref{fig:micro_batch_curve} shows the curve of DP-FP with different micro-batch numbers on SST-2 development set. In this experiment, we set the privacy budget $\epsilon$ to be 0.02 under Gaussian DP + CLT, a very strong privacy level, the batch size to be 32, and the total number of epoch to be 3. Larger micro-batch numbers clearly lead to better performance, as the larger the $M$, the more noise power is reduced (by $\frac{1}{M}$), as shown in Proposition~\ref{prop:noise-power}. \subsection{DP Preliminary} \label{sec:pre} \noindent{\textbf{DP Definition}}: DP stabilizes the output and introduces ``noise'' or random information into the process of computing the output of a function, such as an ML model, making it nearly impossible for the adversary to determine whether or not a specific data record, such as a sentence in the training data, was used. Individual data records face the same level of privacy risk whether or not they are included in the computation due to DP assurance. The rigorous DP definition is as follows. Let $X$ and $X^\prime$ be neighboring datasets, i.e., $X\sim X^\prime$, such that one can be obtained from the other by either adding or removing a data record~\citep{dwork2006calibrating}. In an NLP task, for example, $X$ and $X^\prime$ could be two datasets with sentences, and $X\sim X^\prime$ indicates that they differ by only one sentence. A randomized algorithm $\mathcal M$ is $(\epsilon, \delta)$-DP if for any subsets $Y$ of $\mathcal M$, and all neighboring datasets $X \sim X^{\prime}$, we have \begin{equation} \label{eq:dp-def} \Pr[{\mathcal M}(X)\in {Y}]\leq\mathrm{e}^{\epsilon }\Pr[{\mathcal M}(X^{\prime})\in {Y}]+\delta. \end{equation} The probability distributions of the outputs $\mathcal M(X)$ and $\mathcal M(X^\prime)$ differ only by a multiplicative factor $\mathrm{e}^{\epsilon }$ and a very small value $\delta$. Thus, the value of $\epsilon$ determines the strength of the privacy guarantee: the lower the value of $\epsilon$, the more privacy is guaranteed, and $\delta$ can be interpreted as the likelihood of failing to achieve DP. Note that $\mathcal M(X)$ can be any complicated random function of $X$. For instance, it could be a gradient estimate in DP-SGD as shown later in~Eq.~(\ref{eq:dpsgd}) or a token/latent representation computed by neural networks in DP-FP as shown later in~Eq.~(\ref{eqn:dp-fp}). To quantify privacy protection, data administrators impose a privacy loss cap, also referred to as a privacy budget, i.e., $(\epsilon, \delta)$, to calibrate the amount of random noise required to design $\mathcal M(\cdot)$. \noindent {\textbf {DP Mechanism}}: To achieve the $(\epsilon,\delta)$-DP protection defined in Eq.~(\ref{eq:dp-def}), the random function $\mathcal M(\cdot)$ must be specified. A simple but effective method for achieving DP protection of $X$ given $f(X)$ is obtained by first constraining the range of $f(X)$ by a clipping operator, i.e., $\mathrm{Clip}(f(X); C)$, and then randomizing the result with calibrated Gaussian noise~\citep{abadi2016deep,li2021large}. We introduce details of $\mathrm{Clip}(\cdot; C)$ in Eq.~(\ref{eqn:clipping-dpsgd}) and Eq.~(\ref{eqn:clipping-dpfp}) with concrete examples. The clipping threshold $C$ is also known as {\it{sensitivity}} that guarantees the greatest output variation for any pair of $X\sim X^{\prime}$ in terms of the $\ell_2$-norm. Mathematically, the DP mechanism is defined by \begin{equation} \mathcal M(f(X))=\mathrm{Clip}(f(X); C)+\mathcal{N}(0, \sigma^2) \end{equation} with $\sigma^2$ being calibrated according to the DP profile $(\epsilon(\delta), \delta)$ given by~\citep{balle2018improving}: \begin{equation} \label{eqn:compute_eps} \delta(\epsilon ; \mu) =\Phi\left(-\frac{\epsilon}{\mu}+\frac{\mu}{2}\right)-\mathrm{e}^{\epsilon} \Phi\left(-\frac{\epsilon}{\mu}-\frac{\mu}{2}\right), \end{equation} where \begin{equation} \label{eqn:mu} \mu = C / \sigma, \end{equation} and $\Phi(t)$ is the c.d.f. of Gaussian distribution. \noindent{\textbf{Post Processing Property}}: A key DP property is its immunity to {\it{post-processing}}~\cite{dwork2014algorithmic}, which states that a differentially private output, i.e., $\mathcal M(f(X))$, can be arbitrarily transformed using some data-independent function without compromising its privacy guarantees. \noindent{\textbf{DP Accounting}}: When each DP mechanism meets certain DP guarantees individually, privacy suffers as a result of the composition of these DP mechanisms. Subsampling used before a private mechanism, on the other hand, increases the guarantee of privacy. Because differentially private model training entails a series of composition of subsampling and updates, DP accounting for such a series operations is required. There are several widely used privacy accounting methodologies to adopt, such as moments accountant~\citep{abadi2016deep}, Re\'nyi DP (RDP)~\citep{mironov2017renyi}, Gaussian DP with central limit theorem~\citep{dong2021gaussian, bu2020deep}, and numerically composing tradeoff functions~\citep{gopi2021numerical, koskela2020computing, zhu2021optimal}. RDP, a generalization of moments accounting, provides strict upper bounds on the actual privacy cost, whereas Gaussian DP with central limit theorem (CLT), while asymptotically exact, tends to underestimate the privacy loss, and composing tradeoff functions~\citep{gopi2021numerical} provides a more precise estimate. We use Gaussian DP with CLT for DP analysis due to its simplicity and also report the total DP cost in the experimental analysis using the various methods listed above. To make the paper self-contained, we include more information about Gaussian DP with CLT in the appendix. \subsection{DP-SGD Challenges in Large Models} \label{sec:dpsgd} DP assurance has been incorporated into deep learning by appropriately randomizing conventional model updates to limit what can be breached from the training data when revealing the model~\citep{abadi2016deep}. DP-SGD, which randomizes the SGD-based optimizers such as SGD and Adam, is commonly used to achieve such a sanitized model parameter release while concealing individual training data record. Unlike traditional off-the-shelf optimizers, DP-SGD clips the $\ell_2$-norm of {\it per-sample gradient} before adding the calibrated noise to protect the input data in each step. In more concrete terms, the DP mechanism $\mathcal M(\cdot)$ for estimating the gradient in each $B$-sized batch is as follows: \begin{equation} \label{eq:dpsgd} {g}=\frac{1}{B} \sum_{i=1}^{B} \left(\mathrm{Clip}\left(\nabla \mathcal{L}_{i}, C\right)+ \mathcal{N}\left(0, \sigma^2I_{d}\right)\right) \end{equation} with $d$ the model dimension and $\mathcal{L}_{i}$ the loss function of data record $i$. The clipping operator that shrinks the gradient of an individual example whenever it exceeds some threshold $C$ is computed by \begin{equation} \label{eqn:clipping-dpsgd} \mathrm{Clip}\left(\nabla \mathcal{L}_{i}, C\right) \triangleq \nabla \mathcal{L}_{i}\cdot\min\left(1, \frac{C}{\left\|{\nabla \mathcal{L}_{i}} \right\|_2}\right). \end{equation} The model is then updated based on ${g}$, which is known as DP-SGD\footnote{The $\text {Optimizer}(\theta, g)$ represents the DP-enhanced version of most off-the-shelf optimizers, such as DP-Adam, which, like regular Adam, performs updates and moment accumulation with privatized gradients, i.e., $g$ in Eq.~(\ref{eq:dpsgd}). In this paper, we simply refer to the DP-version optimizers as DP-SGD.}: \begin{equation} \theta \leftarrow \text{Optimizer}\left(\theta, {g}\right). \end{equation} Since ${g}$ has been DP guaranteed with an $(\epsilon, \delta)$ privacy cost in Eq.~(\ref{eq:dpsgd}), $\theta$ on the left-hand-side is also DP protected with the same DP cost as DP is immune to post-processing. Furthermore, for $T$-step updates, the total privacy cost can be calculated by composing $(\epsilon,\delta)$ of each steps using the methods discussed in Section~\ref{sec:pre}'s DP Accounting paragraph. We denote the privacy budget by $(\epsilon_T, \delta_T)$ with $\epsilon_T>\epsilon$ and $\delta_T>\delta$. Applying the above DP-SGD to large-scale models raises the following challenges: \begin{itemize} \item DP-SGD requires the computation and storage of individual gradients in each step due to the clipping operation in Eq~(\ref{eq:dpsgd}). Because each individual gradient requires the same amount of memory as the model, storing individual gradients in DP-SGD consumes a significant amount of memory~\citep{li2021large}. \item The clipping operation in Eq.~(\ref{eqn:clipping-dpsgd}) inescapably introduces a significant bias~\citep{chen2020understanding} in the update direction, preventing convergence and significantly degrading model performance in general. \item The total noise power scales with the model size ($d$), as shown in Eq.~(\ref{eq:dpsgd}), and degrades the model performance significantly~\citep{yu2021large}. Even with small $\sigma$, the total noise power is still huge for large models, such as BERT, where $d$ scales to 110M. \end{itemize}
{'timestamp': '2021-12-30T02:22:14', 'yymm': '2112', 'arxiv_id': '2112.14430', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14430'}
arxiv
\section{Introduction}\label{s1} \noindent \subsection{Sparse Signal Reconstruction}\label{s1.1} \noindent In compressed sensing (CS), a crucial concern is to reconstruct a high-dimensional signals from a relatively small number of linear measurements \begin{equation}\label{systemequationsnoise} \bm{ b}=\bm{ A}\bm{x}+\bm{e}, \end{equation} where $\bm{ b}\in\mathbb{R}^m$ is a vector of measurements, $\bm{ A}\in\mathbb{R}^{m\times n}~(m\ll n)$ is a sensing matrix modeling the linear measurement process, $\bm{x}\in \mathbb{R}^{n}$ is an unknown sparse or compressible signal and $\bm{e}\in\mathbb{R}^{m}$ is a vector of measurement errors, see, e.g., \cite{candes2006stable,donoho2006compressed}. To reconstruct $\bm{ x}$, the most intuitive approach is to find the sparsest signal, that is, one solves via the $\ell_{0}$ minimization problem: \begin{equation}\label{VectorL0} \min_{\bm{x}\in\mathbb{R}^n}\|\bm{x}\|_0~~\text{subject~ to}~~\bm{b}-\bm{ A}\bm{ x}\in\mathcal{B}, \end{equation} where $\|\bm{x}\|_0$ is the number of nonzero coordinates of $\bm{ x}$ and $\mathcal{B}$ is a bounded set determined by the error structure. It is known that the problem \eqref{VectorL0} is NP-hard for high dimensional signals and faces challenges in both theoretical and computational (see, e.g., \cite{Donoho2005Stable,2006High,2006On}). Then many fast and effective algorithms have been developed to recover $\bm{ x}$ from \eqref{systemequationsnoise}. The Least Absolute Shrinkage and Selector Operator (Lasso) is among the most well-known algorithms, i.e., \begin{equation}\label{VectorL1-Lasso} \min_{\bm{ x}\in\mathbb{R}^n}~\lambda\|\bm{ x}\|_1+\frac{1}{2}\|\bm{ Ax} -\bm{b}\|_2^2, \end{equation} where $\lambda> 0$ is a parameter to balance the data fidelity term $\|\bm{Ax} -\bm{ b}\|_{2}^{2}/2$ and the regularized item $\|\bm{ x}\|_{1}$. In the paper, we mainly consider the case that $\bm{ x}$ in numerous practical applications is not sparse itself but is compressible with respect to some given tight frame $\bm{ D}\in\mathbb{R}^{n\times d}~(d\geq n)$. That is, $\bm{ x}=\bm{ D}\bm{ f}$, where $\bm{ f}\in\mathbb{R}^{d}$ is sparse. Here the Fig. \ref{figure.Original_signal_and_tansformation_coefficents} gives an example, in which the original signal is density but is sparse under a transformation. Readers can refer to \cite{majumdar2015energy} and find such a real signal example of electroencephalography (EEG) and electrocardiography (ECG). And we refer to \cite{han2007frames} for basic theory on tight frame. Many recovery results for standard sparse signals have been extended to the dictionary sparse recovery, see, e.g., \cite{bruckstein2009sparse,candes2011compressed,lin2012new} for $\ell_{1}$ and \cite{li2014compressed,lin2016restricted} for $\ell_{p}~(0<p<1)$ and references therein. Specially, based on the idea of \eqref{VectorL1-Lasso}, the following $\ell_1$-analysis problem in \cite{candes2011compressed} is developed: \begin{equation}\label{VectorL1-ana} \min_{\bm{ x}\in\mathbb{R}^n}\|\bm{D}^{\top}\bm{ x}\|_1~~\text{subject~ to} ~~\bm{b}-\bm{A}\bm{x}\in\mathcal{B}. \end{equation} One of the most commonly used frameworks to investigate the theoretical performance of the $\ell_{1}$-analysis method is the restricted isometry property adapted to $\bm{D}$ ($\bm{D}$-RIP), which is first proposed by Cand{\`e}s et al. \cite{candes2011compressed} and can be defined as follows. \begin{definition}\label{def.DRIP} A matrix $\bm{ A}\in\mathbb{R}^{m\times n}$ is said to obey the restricted isometry property adapted to $\bm{ D}\in\mathbb{R}^{n\times d}$ ($\bm{D}$-RIP) of order $s$ with constant $\delta_{s}$ if \begin{equation*} (1-\delta_{s})\|\bm{Dx}\|_{2}^{2}\leq \|\bm{ A}\bm{Dx}\|_2^2\leq (1+\delta_{s})\|\bm{Dx}\|_{2}^{2} \end{equation*} holds for all $s$-sparse vectors $\bm{ v}\in\mathbb{R}^{d}$. The smallest constant $\delta_{s}$ is called as the the restricted isometry constant adapted to $\bm{D}$ ($\bm{D}$-RIC). \end{definition} Note that when $\bm{D}$ is an identity matrix, i.e., $\bm{D}=\bm{I}\in\mathbb{R}^{n\times n}$, the definition of $\bm{D}$-RIP reduces to the standard RIP in \cite{candes2005decoding,candes2006stable}. In the recent literature \cite{lin2012new}, the restricted orthogonality constant (ROC) in \cite{candes2005decoding} for the standard CS is extended to the CS with tight frames, which is defined as follows. \begin{definition}\label{def.DROC} The $\bm{D}$-restricted orthogonality constant (abbreviated as $\bm{D}$-ROC) of order $(s,t)$, is the smallest positive number which satisfies \begin{equation*} |\langle \bm{ADu}, \bm{ADv}\rangle -\langle \bm{Du}, \bm{Dv}\rangle|\leq \theta_{s,t} \|\bm{u}\|_2\|\bm{v}\|_2 \end{equation*} for all $s$-sparse and $t$-sparse vectors $\bm{u}, \bm{v}\in\mathbb{R}^{d}$. \end{definition} Given the definition $\bm{D}$-RIP and $\bm{D}$-ROC. For any positive real number $\tau$ , we denote $\theta_{s,\tau t}$ and $\delta_{\tau t}$ as $\theta_{s,\lceil \tau t \rceil}$ and $\delta_{\lceil \tau t\rceil}$, respectively. Here and below, $\lceil t \rceil$ denotes the nearest integer greater than or equal to $t$. With the new notion, in term of $\bm{D}$-ROC, some sufficient conditions in \cite{lin2012new} have been proposed, such as $\delta_{s}+1.25\theta_{s,s}<1$, and $\delta_{1.25s}+\theta_{s,1.25s}<1$. \subsection{MRI Reconstruction Based on Compressed Sensing}\label{s1.2} \noindent On the other hand, the idea of sparse signal reconstruction (compressed sensing) also has been used in Magnetic Resonance Imaging (MRI) reconstruction. MRI is crucial in clinical applications for disease diagnosis, since its noninvasive and nonionizing radiation properties enables advanced visualization of anatomical structure. However, MRI is limited by the scanning time for physical and physiological constraints \cite{lustig2007sparse}. In order to reduce the scanning period, the CS method has been introduced into MRI achieving the capability of accelerating the imaging speed, which is called CS-MRI technology \cite{lustig2007sparse}. The success of CS-MRI largely relies on sparsity representation \cite{lustig2008compressed} of the MRI images. The image is always assumed to be sparse (or compressible) in sparse transform domain (as shown in Fig. \ref{figure.MRI_and_its_transformation}) for the sparsity-based image prior. Consequently, one can model the reconstruction process through minimizing the regularization function to promote the sparse solution. Sparse representations are confirmed to usually lead to lower reconstruction error \cite{ravishankar2010mr}. In recent years, some scholars used redundant representation systems instead of orthogonal ones in the MRI community. Some representatives of redundant representations systems are undecimated or shift-invariant wavelet frames \cite{baker2011translational,guerquin2011fast,liu2015balanced,vasanawala2011practical}, patch-based methods \cite{lai2016image,qu2014magnetic,zhan2015fast}, over-complete dictionaries \cite{ravishankar2010mr,huang2014bayesian}, etc. Redundancy in a redundant system obtains robust image representations and also introduces additional benefits. For instance, the redundancy in wavelet enables shift-invariant property. For patch-based methods, redundancy lead to better noise removal and artifact suppression. The redundant coming from over-complete dictionaries contains more atom signals than required to represent images, which can better capture different image features, and make the representations relatively sparser than orthogonal dictionaries do. Redundancy also makes the designing or training of such dictionaries more flexible. Even though the trained dictionary is orthogonal for image patches, the overall representation system for the whole image maybe still be redundant \cite{zhan2015fast,cai2014data} due to overlapping of patches. Most of these redundant representation systems above can be categorized as tight frame systems \cite{vetterli2012foundations}. More works about CS-MRI, readers can refer to two review papers \cite{sandilya2017compressed,ye2019compressed}. In this paper, we focus on tight frame-based MRI image reconstruction methods. \begin{figure*}[htbp!] \setlength{\tabcolsep}{4.0pt}\small \begin{tabular}{c} \includegraphics[width=16.0cm,height=8.0cm]{Original_signal_and_tansformation_coefficents_v2.eps} \end{tabular} \centering \caption{\label{figure.Original_signal_and_tansformation_coefficents} Original signal and its transformation coefficients. Upper: the original signal, which is density (not sparse); Down: the coefficients under tight frame transformation, which is sparse. } \vspace{-0.1cm} \end{figure*} \begin{figure*}[htbp!] \setlength{\tabcolsep}{4.0pt}\small \begin{tabular}{c} \includegraphics[width=16.0cm,height=8.0cm]{BarinMRI_and_its_transformation_v1.eps} \end{tabular} \centering \caption{\label{figure.MRI_and_its_transformation} Brain MRI and its transformation coefficients. Left: the original Brain MRI, which is density (not sparse); Right: the coefficients under tight frame transformation, which is sparse. Here the black and white colors denote the pixel value $0$ and $1$, respectively.} \vspace{-0.1cm} \end{figure*} \subsection{Contributions}\label{s1.3} \noindent In this paper, we introduce the unconstrained $\ell_{1}-\alpha\ell_{2}$-analysis minimization: \begin{equation}\label{VectorL1-alphaL2-ASSO} \min_{\bm{x}\in\mathbb{R}^n}~\lambda(\|\bm{ D}^{\top}\bm{x}\|_{1}-\alpha\|\bm{ D}^{\top}\bm{x}\|_{2}) +\frac{1}{2}\|\bm{Ax}-\bm{b}\|_{2}^{2} \end{equation} for some constant $0<\alpha\leq 1$, where $\lambda$ is a regularization parameter. Denote \eqref{VectorL1-alphaL2-ASSO} as Analysis $\ell_{1}-\alpha\ell_{2}$-Shrinkage and Selector Operator ($\ell_{1}-\alpha\ell_{2}$-ASSO). It is rooted to the sparse signal under tight frame and the constrained and unconstrained $\|\bm{x}\|_{1}-\alpha\|\bm{ x}\|_{2}$ minimizations, which has recently attracted a lot of attention. The constrained $\|\bm{x}\|_{1}-\alpha\|\bm{x}\|_{2}$ minimization \cite{li2020minimization,ge2021dantzig,liu2017further,lou2018fast,lou2015computing,yin2015minimization} is \begin{equation}\label{VectorL1-alphaL2} \min_{\bm{x}\in\mathbb{R}^n}~\|\bm{x}\|_{1}-\alpha\|\bm{x}\|_{2} \quad \text{subject \ to} \quad \bm{b}-\bm{A}\bm{x}\in\mathcal{B}. \end{equation} And they have been introduced and studied different conditions based on RIP for the recovery of $\bm{x}$. The unconstrained $\|\bm{x}\|_{1}-\alpha\|\bm{x}\|_{2}$ minimization \cite{liu2017further,lou2018fast,lou2015computing,yin2015minimization,geng2020Unconstrained} is \begin{equation}\label{VectorL1-L2-SSO} \min_{\bm{x}\in\mathbb{R}^n}~\lambda(\|\bm{x}\|_{1}-\|\bm{x}\|_{2})+\frac{1}{2}\|\bm{A}\bm{x}-\bm{b}\|_2^2. \end{equation} It is a key bridge for finding the solution of the constrained $\|\bm{x}\|_{1}-\alpha\|\bm{x}\|_{2}$ minimization \eqref{systemequationsnoise}. There is an effective algorithm based on the different of convex algorithm (DCA) to solve \eqref{VectorL1-L2-SSO}, see \cite{lou2015computing,yin2015minimization}. Numerical examples in \cite{li2020minimization,ge2021dantzig,lou2015computing,yin2015minimization} demonstrate that the $\ell_{1}-\alpha\ell_{2}$ minimization consistently outperforms the $\ell_{1}$ minimization and the $\ell_{p}$ minimization in \cite{lai2013improved} when the measurement matrix $\bm{A}$ is highly coherent. Motivated by the smoothing and decomposition transformations in \cite{tan2014smoothing}, the $\ell_{1}-\alpha\ell_{2}$-ASSO is written as a general nonsmooth convex optimization problem: \begin{equation}\label{VectorL1-alphaL2-RASSO} \min_{\bm{x}\in\mathbb{R}^n}~\lambda(\|\bm{z}\|_{1}-\alpha\|\bm{z}\|_{2}) +\frac{1}{2}\|\bm{Ax}-\bm{b}\|_{2}^{2}+\frac{\rho}{2}\|\bm{D}^{\top}\bm{x}-\bm{z}\|_{2}^{2}. \end{equation} We refer to it as Relaxed Analysis $\ell_{1}-\alpha\ell_{2}$-Shrinkage and Selector Operator ($\ell_{1}-\alpha\ell_{2}$-RASSO). The main contributions are as follows: \begin{enumerate} \item[(i)] We develop a new elementary technique for tight frames (Propositions \ref{prop.DROC} and \ref{NonsparseROC}) and show sufficient conditions based on $\bm{D}$-RIP and $\bm{D}$-ROC for the recovery of $\bm{x}$ from \eqref{systemequationsnoise} via the $\ell_{1}-\alpha\ell_{2}$-ASSO \eqref{VectorL1-alphaL2-ASSO}, see to Theorem \ref{StableRecoveryviaVectorL1-alphaL2-ASSO}. \item[(ii)] We show sufficient conditions based on $\bm{D}$-RIP frame for the recovery of the signal $\bm{x}$ from \eqref{systemequationsnoise} via the $\ell_{1}-\alpha\ell_{2}$-RASSO \eqref{VectorL1-alphaL2-RASSO}, see to Theorem \ref{StableRecoveryviaVectorL1-alphaL2-RASSO}. \item[(iii)]In order to find the solution of \eqref{VectorL1-alphaL2-ASSO}, we proposed an algorithm based on ADMM, which offers a noticeable boost to some sparse reconstruction algorithms for tight frames. Numerical examples based the effective algorithm is presented for both sparse signals and MRI. The recovery performance of the propose method is highly comparable (often better) to existing state-of-the-art methods. \end{enumerate} \subsection{Notations and Organization}\label{s1.4} \noindent Throughout the paper, we use the following basic notations. For any positive integer $n$, let $[[1,n]]$ be the set $\{1,\ldots,n\}$. For the index set $S\subseteq [[1,n]]$, let $|S|$ be the number of entries in $S$, $\bm{x}_S$ be the vector equal to $\bm{x}$ on $S$ and to zero on $S^c$, and $\bm{D}_{S}$ be $\bm{D}$ with all but the columns indexed by $S$ set to zero vector. For $\bm{x}\in\mathbb{R}^n$, denote $\bm{x}_{\max(s)}$ as the vector $\bm{x}$ with all but the largest $s$ entries in absolute value set to zero, and $\bm{x}_{-\max(s)}=\bm{x}-\bm{x}_{\max(s)}$. Let $\|\bm{D}^{\top}\bm{x}\|_{\alpha,1-2}$ be $\|\bm{D}^{\top}\bm{x}\|_1-\alpha\|\bm{D}^{\top}\bm{x}\|_2$. Especially, when $\alpha=1$, denote $\|\bm{D}^{\top}\bm{x}\|_{\alpha,1-2}$ with $\|\bm{D}^{\top}\bm{x}\|_{1-2}$. And we denote $n\times n$ identity matrix by $\bm{I}_{n}$, zeros matrix by $\bm{ O}$, and the transpose of matrix $\bm{A}$ by $\bm{A}^{\top}$. Use the phrase ``$s$-sparse vector" to refer to vectors of sparsity at most $s$. We use boldfaced letter to denote matrix or vector. We denote the standard inner product and Euclidean norm $\langle \cdot, \cdot\rangle$ and $\|\cdot\|_{2}$, respectively. The rest of the paper is organized as follows. In Section \ref{adds2}, we describe some preliminaries about the tight frame and the unconstraint $\ell_{1}-\alpha\ell_{2}$ analysis models. In Section \ref{s3}, we give the main conclusions and show their proof. Then we design an algorithm based on projected PISTA to solve the proposed model \eqref{VectorL1-alphaL2-ASSO} in Section \ref{s4}. And we also apply our algorithm to solve the proposed model for signal and MRI reconstruction in Section \ref{s5}. Conclusions are given in Section \ref{s6}. \section{Preliminaries}\label{adds2} \noindent In this section, we first recall some significant lemmas in order to analyse the $\ell_{1}-\alpha\ell_{2}$-ASSO \eqref{VectorL1-alphaL2-ASSO} and $\ell_{1}-\alpha\ell_{2}$-RASSO \eqref{VectorL1-alphaL2-RASSO}. In view of the above-mentioned facts in Section \ref{s1}, the $\bm{D}$-RIP plays a key role for the stable recovery of signal via the analysis approach. The following lemma show some basic properties in \cite{lin2012new} for the $\bm{D}$-RIP with $\delta_{s}$ and $\theta_{s,t}$. \begin{lemma}\label{Basicproperty} \begin{enumerate} \item[(i)]For any $s_{1}\leq s_{2}\leq d$, we have $\delta_{s_{1}}\leq \delta_{s_{2}}$. \item[(ii)]For any positive integers $s$ and $t_{1}\leq t_{2}$, we have $\theta_{s,t_{2}}\leq\sqrt{\frac{t_{2}}{t_{1}}}\theta_{s,t_{1}}$. \item[(iii)]$\theta_{s_{1},t_{1}}\leq\theta_{s_{2},t_{2}}$ if $s_{1}\leq s_{2}$ and $t_{1}\leq t_{2}$ with $s_{2}+t_{2}\leq d$. \item[(iv)]For all nonnegative integers $s,t\leq d$, we have $\theta_{s,t}\leq \delta_{s+t}$. \end{enumerate} \end{lemma} Here, we proposed the standard properties for the dictionary $\bm{D}$. \begin{proposition}\label{prop.DROC} Let $\bar{\bm{D}}\in\mathbb{R}^{(d-n)\times d}$ be the orthogonal complement of $\bm{D}\in\mathbb{R}^{n\times d}$, i.e., $\bar{\bm{D}}\bm{D}^{\top}=\bm{0}$, $\bar{\bm{D}}\bar{\bm{D}}^{\top}=\bm{I}_{n-d}$. Then, \begin{enumerate} \item[(i)] For any $\bm{v}\in\mathbb{R}^{d}$, $\|\bm{v}\|_{2}^{2}=\|\bm{Dv}\|_{2}^{2}+\|\bar{\bm{D}}\bm{v}\|_{2}^{2}$. \item[(ii)] For any $s$-sparse signal $\bm{v}\in\mathbb{R}^{d}$, we have $$ (1-\delta_{s})\|\bm{v}\|_{2}^{2}\leq \|\bm{A}\bm{Dv}\|_2^2+\|\bar{\bm{D}}\bm{v}\|_{2}^{2}\leq (1+\delta_{s})\|\bm{v}\|_{2}^{2}. $$ \item[(iii)]$\langle \bm{u}, \bm{v}\rangle=\langle \bar{\bm{D}}\bm{u}, \bar{\bm{D}}\bm{v}\rangle +\langle \bm{D}\bm{u}, \bm{D}\bm{v}\rangle$ for any $\bm{u}\in\mathbb{R}^{d}$. \item[(iv)] For any $\|\bm{u}\|_{0}\leq s$ and $\|\bm{v}\|_{0}\leq t$, we have $$ |\langle \bm{A}\bm{Du}, \bm{A}\bm{Dv}\rangle+\langle\bar{\bm{D}}\bm{u}, \bar{\bm{D}}\bm{v}\rangle -\langle\bm{u}, \bm{v}\rangle| \leq\theta_{s,t}\|\bm{u}\|_{2}\|\bm{v}\|_{2}. $$ Moreover, if $\text{\rm supp}(\bm{u})\cap\text{\rm supp}(\bm{v})=\emptyset$, we have $$ |\langle \bm{A}\bm{Du}, \bm{A}\bm{Dv}\rangle+\langle\bar{\bm{D}}\bm{u}, \bar{\bm{D}}\bm{v}\rangle| \leq\theta_{s,t}\|\bm{u}\|_{2}\|\bm{v}\|_{2}. $$ \end{enumerate} \end{proposition} \begin{proof} Despite the results $(i)$ and $(ii)$ in Proposition \ref{prop.DROC} are clear, we here give their proofs. As far as we know, the results (iii) and (iv) are first proved. $(i)$ For any $v\in\mathbb{R}^{d}$, there is \begin{align*} \|\bm{Dv}\|_{2}^{2}+\|\bar{\bm{D}}\bm{v}\|_{2}^{2} &=\langle \bm{D}^{\top} \bm{D}\bm{v}, \bm{v}\rangle +\langle \bar{\bm{D}}^{\top}\bar{\bm{D}}\bm{v},\bm{v}\rangle \nonumber\\ &=\bm{v}^{\top}\begin{bmatrix} \bm{D}^{\top} & \bar{\bm{D}}^{\top} \\ \end{bmatrix} \begin{bmatrix} \bm{D} \\ \bar{\bm{D}} \\ \end{bmatrix}\bm{v} =\|\bm{v}\|_{2}^{2}, \end{align*} where the last equality comes from the definition of tight frame $\bm{D}\bm{D}^{\top}=\bm{I}_{n}$ and the definition of the orthogonal complement of frame $\bar{\bm{D}}\bar{\bm{D}}^{\top}=\bm{I}_{n-d}$. $(ii)$ By the definition of $\bm{D}$-RIP, we have \begin{align}\label{prop.DROC.eq6} \|\bm{A}\bm{Dv}\|_2^2+\|\bar{\bm{D}}\bm{v}\|_{2}^{2} &\leq (1+\delta_{s})\|\bm{Dv}\|_{2}^{2}+\|\bar{\bm{D}}\bm{v}\|_{2}^{2} \leq (1+\delta_{s})\left(\|\bm{Dv}\|_{2}^{2}+\|\bar{\bm{D}}\bm{v}\|_{2}^{2}\right)\nonumber\\ &=(1+\delta_{s})\|\bm{v}\|_{2}^{2}, \end{align} where the equality comes from the item $(i)$. Similarly, we can show the lower bound \begin{eqnarray}\label{prop.DROC.eq7} \|\bm{A}\bm{Dv}\|_{2}^{2}+\|\bar{\bm{D}}\bm{v}\|_{2}^{2} \geq(1-\delta_{s})\|\bm{v}\|_{2}^{2}. \end{eqnarray} The combination of the upper bound \eqref{prop.DROC.eq6} and the lower bound \eqref{prop.DROC.eq7} gives the item (ii). Next, we show our new conclusions items (iii) and (iv). $(iii)$ According to the parallelogram identity, we have \begin{align*} \langle \bar{\bm{D}}\bm{u}, \bar{\bm{D}}\bm{v}\rangle &=\frac{1}{4}\left(\|\bar{\bm{D}}(\bm{u}+\bm{v})\|_{2}^{2} -\|\bar{\bm{D}}(\bm{u}-\bm{v})\|_{2}^{2}\right),\nonumber\\ \langle \bm{D}\bm{u}, \bm{D}\bm{v}\rangle &=\frac{1}{4}\left(\|\bm{D}(\bm{u}+\bm{v})\|_{2}^{2} -\|\bm{D}(\bm{u}-\bm{v})\|_{2}^{2}\right). \end{align*} Taking sum over both side of above two equalities, one has \begin{align}\label{prop.DROC.eq5} &\langle \bar{\bm{D}}\bm{u}, \bar{\bm{D}}\bm{v}\rangle +\langle \bm{D}\bm{u}, \bm{D}\bm{v}\rangle\nonumber\\ &=\frac{1}{4}\left(\left(\|\bar{\bm{D}}(\bm{u}+\bm{v})\|_{2}^{2}+\|\bm{D}(\bm{u}+\bm{v})\|_{2}^{2}\right) -\left(\|\bar{\bm{D}}(\bm{u}-\bm{v})\|_{2}^{2}+\|\bm{D}(\bm{u}-\bm{v})\|_{2}^{2}\right)\right)\nonumber\\ &=\frac{1}{4}\left(\|\bm{u}+\bm{v}\|_{2}^{2}-\|\bm{u}-\bm{v}\|_{2}^{2}\right), \end{align} where the second equality holds because of the item $(i)$. Last, by the above \eqref{prop.DROC.eq5} and the following parallelogram identity \begin{equation*} \langle \bm{u}, \bm{v}\rangle =\frac{1}{4}\left(\|(\bm{u}+\bm{v})\|_{2}^{2} -\|(\bm{u}-\bm{v})\|_{2}^{2}\right), \end{equation*} we get \begin{equation*} \langle \bm{u}, \bm{v}\rangle=\langle \bar{\bm{D}}\bm{u}, \bar{\bm{D}}\bm{v}\rangle +\langle \bm{D}\bm{u}, \bm{D}\bm{v}\rangle. \end{equation*} $(iv)$ It follows from the item $(ii)$ and the definition of $\bm{D}$-ROC that \begin{eqnarray*} &&|\langle \bm{A}\bm{Du}, \bm{A}\bm{Dv}\rangle+\langle\bar{\bm{D}}\bm{u}, \bar{\bm{D}}\bm{v}\rangle -\langle\bm{u}, \bm{v}\rangle| =|\langle \bm{A}\bm{Du}, \bm{A}\bm{Dv}\rangle-\langle\bm{D}\bm{u}, \bm{D}\bm{v}\rangle|nonumber\\ &&\leq\theta_{s,t}\|\bm{u}\|_{2}\|\bm{v}\|_{2}, \end{eqnarray*} which is our desired conclusion. \end{proof} Next, the following inequality is a modified cone constraint inequality for the unconstrained $\|\bm{D}^{\top}\bm{x}\|_{1}-\alpha\|\bm{D}^{\top}\bm{x}\|_{2}$ minimization \eqref{VectorL1-alphaL2-ASSO}. Its proof is similar as that of \cite[Lemma 2.3]{geng2020Unconstrained} and we omit its proof. \begin{lemma}\label{ConeTubeconstraint-L1-L2-ASSO} Let $\bm{b}=\bm{Ax}+\bm{e}$ with $\|\bm{e}\|_{2}\leq\lambda$, $T = \text{\rm supp}(\bm{D}^{\top}\bm {x}_{\max(t)})$, and $\hat{\bm{x}}$ be a minimization solution of \eqref{VectorL1-alphaL2-ASSO}. Then \begin{align}\label{ConeTubeconstraint-L1-L2-ASSO.eq1} \|\bm{Ah}\|_{2}^{2}+2\lambda\|\bm{D}_{T^c}^{\top}\bm{h}\|_{1}\leq2\lambda(\|\bm{D}_{T}^{\top}\bm{h}\|_1 +\alpha\|\bm{D}^{\top}\bm{h}\|_2+2\|\bm{D}_{T^c}^{\top}\bm{x}\|_{1} +\|\bm{Ah}\|_{2}), \end{align} where ${\bm h}=\hat{{\bm x}}-{\bm x}$. And moreover, \begin{align*} \|\bm{Ah}\|_2^2+2\lambda(\|{\bm D}_{T^c}^{\top}{\bm h}\|_1-\alpha\|{\bm D}_{T^c}^{\top}{\bm h}\|_2) \leq2\lambda(\|{\bm D}_{T}^{\top}{\bm h}\|_1+2\|{\bm D}_{T^c}^{\top}{\bm x}\|_1 +\alpha\|{\bm D}_{T}^{\top}{\bm h}\|_2+\|\bm {Ah}\|_2), \end{align*} \begin{align*} \|{\bm D}_{T^c}^{\top}{\bm h}\|_1\leq\|{\bm D}_{T}^{\top}{\bm h}\|_1+2\|{\bm D}_{T^c}^{\top}{\bm x}\|_1 +\alpha\|{\bm D}^{\top}{\bm h}\|_2+\|\bm {Ah}\|_2, \end{align*} and \begin{align*} \|{\bm Ah}\|_2^2\leq2\lambda(\|{\bm D}_{T}^{\top}{\bm h}\|_1+2\|{\bm D}_{T^c}^{\top}{\bm x}\|_1 +\alpha\|{\bm D}^{\top}{\bm h}\|_2+\|\bm {Ah}\|_2). \end{align*} \end{lemma} For the $\ell_{1}-\alpha\ell_{2}$-RASSO \eqref{VectorL1-alphaL2-RASSO}, there is a similar cone constraint inequality. \begin{lemma}\label{ConeTubeconstraint-L1-L2-RASSO} Let ${\bm b}={\bm {Ax}}+{\bm e}$ with $\|\bm e\|_2\leq\lambda$, and $T = \text{\rm supp}({\bm D}^{\top}{\bm x}_{\max(s)})$. Then the minimization solution $\hat{\bm x}$ of \eqref{VectorL1-alphaL2-RASSO} satisfies \begin{align}\label{ConeTubeconstraint-L1-L2-RASSO.eq1} \|\bm {Ah}\|_2^2+2\lambda\|{\bm D}_{T^c}^{\top}{\bm h}\|_1\leq2\lambda\bigg(\|{\bm D}_{T}^{\top}{\bm h}\|_1+\alpha\|{\bm D}^{\top}{\bm h}\|_2+2\|{\bm D}_{T^c}^{\top}{\bm x}\|_1 +\|\bm {Ah}\|_2+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\bigg), \end{align} where ${\bm h}=\hat{{\bm x}}-{\bm x}$. \end{lemma} \begin{proof} Our proof is motivated by the proof of \cite[Lemma 2.3]{geng2020Unconstrained} and \cite[Lemma IV.4]{tan2014smoothing}. Assume that $(\hat{\bm{x}},\hat{\bm{z}})$ is another solution of \eqref{VectorL1-alphaL2-RASSO}, then \begin{align}\label{ConeTubeconstraint-L1-L2-RASSO.eq2} 0&\geq \bigg(\lambda(\|\hat{{\bm z}}\|_{1}-\alpha\|\hat{{\bm z}}\|_{2})+\frac{1}{2}\|{\bm A}\hat{{\bm x}}-{\bm b}\|_{2}^{2}+\frac{\rho}{2}\|{\bm D}^{\top}\hat{{\bm x}}-\hat{{\bm z}}\|_{2}^{2}\bigg)\nonumber\\ &\hspace{12pt}-\bigg(\lambda(\|{\bm D}^{\top}{\bm x}\|_{1}-\alpha\|{\bm D}^{\top}{\bm x}\|_{2})+\frac{1}{2}\|{\bm A}{\bm x}-{\bm b}\|_{2}^{2}\bigg)\nonumber\\ &=\frac{1}{2}\bigg(\|{\bm A}\hat{{\bm x}}-{\bm b}\|_{2}^{2}-\|{\bm A}{\bm x}-{\bm b}\|_{2}^{2}\bigg)\nonumber\\ &\hspace{12pt}+\bigg(\lambda(\|\hat{{\bm z}}\|_{1}-\alpha\|\hat{{\bm z}}\|_{2})+\frac{\rho}{2}\|{\bm D}^{\top}\hat{{\bm x}}-\hat{{\bm z}}\|_{2}^{2}-\lambda(\|{\bm D}^{\top}{\bm x}\|_{1}-\alpha\|{\bm D}^{\top}{\bm x}\|_{2})\bigg)\nonumber\\ &=:I_1+I_2. \end{align} Next, we deal with terms $I_1$ and $I_2$, respectively. By $\hat{{\bm x}}={\bm h}+{\bm x}$ and ${\bm Ax}-{\bm b}=-{\bm e}$, \begin{align}\label{ConeTubeconstraint-L1-L2-RASSO.eq3} I_1&=\frac{1}{2}\bigg(\|{\bm A}{\bm h}-{\bm e}\|_{2}^{2}-\|-{\bm e}\|_{2}^{2}\bigg) =\frac{1}{2}\|{\bm A}{\bm h}\|_{2}^{2}-\langle {\bm A}{\bm h}, {\bm e}\rangle \nonumber\\ &\overset{(1)}{\geq} \frac{1}{2}\|{\bm A}{\bm h}\|_{2}^{2}-\|{\bm A}{\bm h}\|_{2}\|{\bm e}\|_{2} \overset{(2)}{\geq} \frac{1}{2}\|{\bm A}{\bm h}\|_{2}^{2}-\lambda\|{\bm A}{\bm h}\|_{2}, \end{align} where the inequality (1) comes from the Cauchy-Schwarz inequality, and the inequality (2) is from $\|{\bm e}\|_{2}\leq \lambda$. Then, we estimate the term $I_{2}$. The subgradient optimality condition for \eqref{VectorL1-alphaL2-RASSO} is \begin{align* {\bm 0}&={\bm A}^{\top}({\bm A}\hat{{\bm x}}-{\bm b})+\rho{\bm D}({\bm D}^{\top}\hat{{\bm x}}-\hat{{\bm z}}),\nonumber\\ {\bm 0}&\in\lambda{\bm v}-\rho({\bm D}^{\top}\hat{{\bm x}}-\hat{{\bm z}}), \end{align*} where ${\bm v}$ is a Frech$\acute{e}$t sub-differential of the function $\|\hat{{\bm z}}\|_{1}-\alpha\|\hat{{\bm z}}\|_{2}$. Then, we derive that \begin{align}\label{ConeTubeconstraint-L1-L2-RASSO.eq4} I_2&= \lambda(\|\hat{{\bm z}}\|_{1}-\|{\bm D}^{\top}{\bm x}\|_{1})-\lambda\alpha(\|\hat{{\bm z}}\|_{2}-\|{\bm D}^{\top}{\bm x}\|_{2}) +\frac{\rho}{2}\|{\bm D}^{\top}\hat{{\bm x}}-\hat{{\bm z}}\|_{2}^{2}\nonumber\\ &= \lambda\left(\left\|{\bm D}^{\top}\hat{{\bm x}}-\frac{\lambda}{\rho}{\bm v}\right\|_{1}-\|{\bm D}^{\top}{\bm x}\|_{1}\right) -\lambda\alpha\left(\left\|{\bm D}^{\top}\hat{{\bm x}}-\frac{\lambda}{\rho}{\bm v}\right\|_{2}-\|{\bm D}^{\top}{\bm x}\|_{2}\right) +\frac{\rho}{2}\|\frac{\lambda}{\rho}{\bm v}\|_{2}^{2}\nonumber\\ &\overset{(a)}{\geq}\lambda\left(\|{\bm D}^{\top}\hat{{\bm x}}\|_1-\|{\bm D}^{\top}{\bm x}\|_1 -\frac{\lambda}{\rho}\|{\bm v}\|_{1}\right) -\lambda\alpha\left(\|{\bm D}^{\top}\hat{{\bm x}}\|_2-\|{\bm D}^{\top}{\bm x}\|_2 +\frac{\lambda}{\rho}\|{\bm v}\|_{2} \right) +\frac{\lambda^2}{2\rho}\|{\bm v}\|_{2}^{2}\nonumber\\ &=\lambda\left(\left(\|{\bm D}^{\top}\hat{{\bm x}}\|_1-\|{\bm D}^{\top}{\bm x}\|_1\right) -\alpha\left(\|{\bm D}^{\top}\hat{{\bm x}}\|_2-\|{\bm D}^{\top}{\bm x}\|_2\right)\right)\nonumber\\ &\hspace*{12pt}+\frac{\lambda^2}{2\rho}(\|{\bm v}\|_{2}^{2}-2\|{\bm v}\|_{1}-2\alpha\|{\bm v}\|_{2})\nonumber\\ &=:I_{21}+I_{22}, \end{align} where (a) is because of $\|{\bm u}\|_{p}-\|{\bm v}\|_{p}\leq \|\bm{u +v}\|_{p}\leq \|{\bm u}\|_{p}+\|{\bm v}\|_{p}$ for any $1\leq p\leq\infty$. Note that \begin{align}\label{ConeTubeconstraint-L1-L2-RASSO.eq5} I_{21}&=\lambda\left(\|{\bm D}_{T}^{\top}(\bm{ h+ x})+{\bm D}_{T^c}^{\top}(\bm{ h+ x})\|_1-\|{\bm D}_{T}^{\top}{\bm x} +{\bm D}_{T^c}^{\top}{\bm x}\|_1\right)\nonumber\\ &\hspace*{12pt}-\lambda\alpha\left(\|{\bm D}^{\top}(\bm{ h+ x})\|_2-\|{\bm D}^{\top}{\bm x}\|_2\right)\nonumber\\ &\geq\lambda\left(\|{\bm D}_{T}^{\top}{\bm x}\|_1-\|{\bm D}_{T}^{\top}{\bm h}\|_1+\|{\bm D}_{T^c}^{\top}{\bm h}\|_1-\|{\bm D}_{T^c}^{\top}{\bm x}\|_1- \|{\bm D}_{T}^{\top}{\bm x}\|_1-\|{\bm D}_{T^c}^{\top}{\bm x}\|_1\right)\nonumber\\ &\hspace*{12pt}-\lambda\alpha\left(\|{\bm D}^{\top}{\bm h}\|_2\right)\nonumber\\ &=\lambda(\|{\bm D}_{T^c}^{\top}{\bm h}\|_1-\|{\bm D}_{T}^{\top}{\bm h}\|_1-2\|{\bm D}_{T^c}^{\top}{\bm x}\|_1-\alpha\|{\bm D}^{\top}{\bm h}\|_2), \end{align} where the inequality is because of $\|\bm{u +v}\|_{1}\geq \|{\bm u}\|_{1}-\|{\bm v}\|_{1}$ and $\|\bm{u +v}\|_{1}\leq\|{\bm u}\|_{1}+\|{\bm v}\|_{1}$. On the other hand, \begin{align}\label{ConeTubeconstraint-L1-L2-RASSO.eq6} I_{22}&\overset{(1)}{\geq}\frac{\lambda^2}{2\rho}\left(\|{\bm v}\|_{2}^{2}-2(1+\alpha)\|{\bm v}\|_{1}\right)\nonumber\\ &=\frac{\lambda^2}{2\rho}\sum_{j=1}^{d}\left((|v|_j-(1+\alpha))^2-(1+\alpha)^2\right) \overset{(2)}{\geq} -\frac{(1+\alpha)^2\lambda^2d}{2\rho}, \end{align} where (1) is because of $\|{\bm v}\|_{2}\leq \|{\bm v}\|_{1}$, and the equality (2) holds if and only if $|v|_j=(1+\alpha)$ for all $j=1,\ldots,d$. Substituting the estimate \eqref{ConeTubeconstraint-L1-L2-RASSO.eq5} and \eqref{ConeTubeconstraint-L1-L2-RASSO.eq6} into \eqref{ConeTubeconstraint-L1-L2-RASSO.eq4}, one has \begin{align}\label{ConeTubeconstraint-L1-L2-RASSO.eq7} I_2\geq\lambda\left(\|{\bm D}_{T^c}^{\top}{\bm h}\|_1-\|{\bm D}_{T}^{\top}{\bm h}\|_1-2\|{\bm D}_{T^c}^{\top}{\bm x}\|_1-\alpha\|{\bm D}^{\top}{\bm h}\|_2-\frac{(1+\alpha)^2d\lambda }{2\rho}\right). \end{align} Last, substituting the estimate of $I_1$ in \eqref{ConeTubeconstraint-L1-L2-RASSO.eq3} and $I_2$ in \eqref{ConeTubeconstraint-L1-L2-RASSO.eq7} into the inequality \eqref{ConeTubeconstraint-L1-L2-RASSO.eq2}, we get \eqref{ConeTubeconstraint-L1-L2-RASSO.eq1}. \end{proof} The following lemma is the fundamental properties of the metric $\|{\bm x}\|_1-\alpha\|{\bm x}\|_2$ with $0\leq\alpha\leq 1$, see \cite{yin2015minimization} and \cite{ge2021dantzig}. \begin{lemma}\label{LocalEstimateL1-L2} For any $\bm {x}\in \mathbb{R}^n$, the following statements hold: \begin{description} \item (a) Let $0 \leq \alpha\leq 1$, $T=\text{\rm supp}({\bm x})$ and $\|{\bm x}\|_0=s$. Then \begin{align}\label{e:l12alphas} (s-\alpha\sqrt{s})\min_{j\in T}|x_j|\leq\|{\bm x}\|_1-\alpha\|{\bm x}\|_2\leq(\sqrt{s}-\alpha)\|{\bm x}\|_2. \end{align} \item (b) Let $S, S_1, S_2\subseteq [n]$ satisfy $S=S_1\cup S_2$ and $S_1\cap S_2=\emptyset$. Then \begin{align}\label{e:uplowerbound} \|\bm {x}_{S_1}\|_{1}-\alpha\|\bm{x}_{S_1}\|_{2}+\|\bm{x}_{S_2}\|_{1}-\alpha\|\bm{x}_{S_2}\|_{2}\leq\|\bm{x}_{S}\|_{1}- \alpha\|\bm{x}_{S}\|_{2}. \end{align} \end{description} \end{lemma} Now, we can give the key technical tool used in the main results. It provides an estimation based on $\bm{D}$-ROC for $|\langle \bm{ ADu}, \bm{ ADv} \rangle +\langle \bar{{\bm D}}{\bm u},\bar{{\bm D}}{\bm v}\rangle|$, where one of $\bm{u}$ or $\bm{v}$ is sparse. Our idea is inspired by \cite[Lemma 5.1]{cai2013compressed} and \cite[Lemma 2.3]{li2019signal}. \begin{proposition}\label{NonsparseROC} Let $s_1, s_2\leq n$. Suppose ${\bm u},{\bm v}\in\mathbb{R}^d$ satisfy $\text{\rm supp}({\bm u})\cap \text{\rm supp}({\bm v})=\emptyset$ and $\bm u$ is $s_1$ sparse. If $\|{\bm v}\|_{1-2}\leq(s_2-\sqrt{s_2})\eta$ and $\|{\bm v}\|_\infty\leq\eta$, then \begin{align}\label{NonsparseROC.eq1} |\langle \bm{ ADu}, \bm{ ADv} \rangle +\langle \bar{{\bm D}}{\bm u},\bar{{\bm D}}{\bm v}\rangle| \leq\bigg(1+\frac{\sqrt{2}}{2}\bigg)\eta \sqrt{s_2}\theta_{s_1,s_2}\|\bm{u}\|_2. \end{align} \end{proposition} Before giving the proof of Proposition \ref{NonsparseROC}, we first recall a convex combination of sparse vectors for any point based on the metric $\|\cdot\|_1-\|\cdot\|_2$. \begin{lemma}\label{e:convexl1-2}\cite[Lemma2.2]{ge2021new} Let a vector $\bm {\nu}\in \mathbb{R}^d$ satisfy $\|\bm {\nu}\|_{\infty}\leq \eta$, where $\alpha$ is a positive constant. Suppose $\|\bm {\nu}\|_{1-2}\leq (s-\sqrt{s})\eta$ with a positive integer $s$ and $s\leq |\mathrm{supp}(\bm {\nu})|$. Then $\bm {\nu}$ can be represented as a convex combination of $s$-sparse vectors $\bm {v}^{(i)}$, i.e., \begin{align}\label{e:com} \bm {\nu}=\sum_{i=1}^N\lambda_i\bm {v}^{(i)}, \end{align} where $N$ is a positive integer, \begin{align}\label{e:thetaisum} 0<\lambda_i\leq1,\ \ \ \ \sum_{i=1}^N\lambda_i=1, \end{align} \begin{align}\label{e:setS} \mathrm{supp}(\bm {v}^{(i)})\subseteq \mathrm{supp}(\bm {\nu}), \ \ \|\bm {v}^{(i)}\|_0\leq {s},\ \ \|\bm {v}^{(i)}\|_{\infty}\leq \Big(1+\frac{\sqrt{2}}{2}\Big)\eta, \end{align} and \begin{align}\label{e:newinequality} \sum_{i=1}^N\lambda_i\|\bm {v}^{(i)}\|_2^2 \leq \Big[\Big(1+\frac{\sqrt{2}}{2}\Big)^2(s-\sqrt{s})+1\Big]\theta^2. \end{align} \end{lemma} Now, we give the proof of Proposition \ref{NonsparseROC} in details. \begin{proof} Suppose $\|\bm{v}\|_0=t$. We consider two cases as follows. \textbf{Case I: $t\leq s_2$.} By the item (iv) of Proposition \ref{prop.DROC} and $\|{\bm v}\|_\infty\leq\alpha$, we have \begin{align}\label{NonsparseROC.eq2} |\langle \bm{ ADu}, \bm{ ADv} \rangle +\langle \bar{{\bm D}}{\bm u},\bar{{\bm D}}{\bm v}\rangle|&\leq\theta_{s_1,t}\|{\bm u}\|_2\|{\bm v}\|_2\leq\theta_{s_1,t}\|{\bm u}\|_2\|{\bm v}\|_{\infty}\sqrt{\|{\bm v}\|_0}\nonumber\\ &\leq\eta\sqrt{s_2}\theta_{s_1,s_2}\|{\bm u}\|_2. \end{align} \textbf{Case II: $t> s_2$.} We shall prove by induction. Assume that \eqref{NonsparseROC.eq1} holds for $t-1$. Note that $\|{\bm v}\|_{1-2}\leq\eta (s_2-\sqrt{s_2})$ and $\|{\bm v}\|_{\infty}\leq \eta$. By Lemma \ref{e:convexl1-2}, ${\bm v}$ can be represented as the convex hull of $s_2$-sparse vectors: $$ {\bm v}=\sum_{j=1}^N\gamma_j{\bm v}^j, $$ where ${\bm v}^j$ is $s_2$-sparse for any $j\in[N]$ and \begin{align*} \sum_{j=1}^N\gamma_j=1,~~0<\gamma_j\leq 1, j\in[N]. \end{align*} Since $\bm{v}^j$ is $s_2$-sparse and $s_2\leq t-1$, we use the induction assumption, \begin{align}\label{NonsparseROC.eq3} &|\langle \bm{ ADu}, \bm{ ADv} \rangle +\langle \bar{{\bm D}}{\bm u},\bar{{\bm D}}{\bm v}\rangle| \leq\sum_{j=1}^N\gamma_j|\langle \bm{ ADu}, \bm{ AD}\bm{v}^j\rangle +\langle \bar{{\bm D}}{\bm u},\bar{{\bm D}}{\bm v}^j\rangle|\nonumber\\ &\overset{(a)}{\leq} \sum_{j=1}^N\gamma_j\bigg(\theta_{s_1,s_2}\|\bm{v}^j\|_2\|\bm{u}\|_2\bigg) \leq \sum_{j=1}^N\gamma_j\bigg(\theta_{s_1,s_2}\|\bm{v}^j\|_{\infty}\sqrt{\|\bm{v}^j\|_{0}}\|\bm{u}\|_2\bigg)\nonumber\\ &\overset{(b)}{\leq}\sum_{j=1}^N\gamma_j\bigg(\bigg(1+\frac{\sqrt{2}}{2}\bigg)\eta\sqrt{s_2}\theta_{s_1,s_2}\|\bm{u}\|_2\bigg) =\bigg(1+\frac{\sqrt{2}}{2}\bigg)\eta\sqrt{s_2}\theta_{s_1,s_2}\|\bm{u}\|_2, \end{align} where (a) is in view of the item (iv) of Proposition \ref{prop.DROC}, and (b) is in virtue of Lemma \ref{e:convexl1-2}. The combination of \textbf{Case I} and \textbf{Case II} is \eqref{NonsparseROC.eq1}. \end{proof} \section{Main Result based on D-RIC and D-ROC }\label{s3} \noindent In this section, we develop sufficient conditions based on $\bm{D}$-RIC and $\bm{D}$-ROC of the $\ell_{1}-\alpha \ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} and $\ell_{1}-\alpha \ell_2$-RASSO \eqref{VectorL1-alphaL2-RASSO} for the signal recovery applying the technique of the convex combination. \subsection{Auxiliary Lemmas Under RIP Frame}\label{s3.1} \noindent Combining the above auxiliary results in Section \ref{adds2}, we first introduce some main inequalities, which play an important role in establishing the recovery condition of the $\ell_{1}-\alpha \ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} and $\ell_{1}-\alpha \ell_2$-RASSO \eqref{VectorL1-alphaL2-RASSO}. \begin{proposition}\label{lem:CrossItem} For positive integers $s\geq 2$ and $k\geq 1$, let $S = \text{\rm supp}({\bm D}^{\top}{\bm h}_{\max(s)})$ and $T = \text{\rm supp}({\bm D}^{\top}{\bm x}_{\max(s)})$. Assume that \begin{eqnarray}\label{lem:CrossItem.eq1} \|\bm{D}_{S^c}^{\top}\bm{h}\|_1-\alpha\|\bm{D}_{S^c}^{\top}\bm{h}\|_2 \leq a\|\bm{D}_{S}^{\top}\bm{h}\|_1+b\|\bm{D}_{S}^{\top}\bm{h}\|_2+c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm {Ah}}\|_2 +\gamma, \end{eqnarray} where $a>0$ and $b,c, \eta,\gamma\geq0$ satisfy $(a-1)\sqrt{s}+(b+1)\geq0$. Then the following statements hold: \begin{description} \item[(i)] For the set $S$, one has \begin{align}\label{e:CrossItem1} &|\langle \bm{AD}\bm{D}_{S}^{\top}{\bm h},\bm{AD}\bm{D}_{S^c}^{\top}{\bm h}\rangle |\nonumber\\ &\leq \theta_{s,s}\sqrt{s}\Big(1+\frac{\sqrt{2}}{2}\Big)\Big(\frac{a\sqrt{s}+b}{\sqrt{s}-1}\frac{\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}} +\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm Ah}\|_2+\gamma}{s-\sqrt{s}}\Big)\|\bm{D}_{S}^{\top}{\bm h}\|_2, \end{align} \item \item[(ii)] Let the set \begin{align}\label{def:S} \tilde{S}=S\cup \Big\{i:|(\bm{D}_{S^c}^{\top}\bm{h})(i)|>\frac{1}{t-1}\frac{a\sqrt{s}+b}{\sqrt{s}-1}\frac{\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}} +\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm Ah}\|_2+\gamma}{(t-1)(s-\sqrt{s})}\Big\} \end{align} for any $t>3$. Then \begin{align}\label{e:CrossItem2} &|\langle \bm{AD}\bm{D}_{\tilde{S}}^{\top}{\bm h},\bm{AD}\bm{D}_{\tilde{S}^c}^{\top}{\bm h}\rangle |\leq\theta_{ts, (t-1)s} \frac{\sqrt{\lceil(t-1)s\rceil}}{t-1} \Big(1+\frac{\sqrt{2}}{2}\Big) \nonumber\\ &\times\Big(\frac{a\sqrt{s}+b}{\sqrt{s}-1}\frac{\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}} +\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm Ah}\|_2+\gamma}{s-\sqrt{s}}\Big)\|\bm{D}_{\tilde{S}}^{\top}{\bm h}\|_2. \end{align} \item[(iii)] Let $\bm {A}$ satisfy $\bm D$-RIP with \begin{align}\label{RIPConditiona1add} \rho_{s,t}=:\delta_{ts}+\sqrt{\frac{\lceil(t-1)s\rceil}{(t-1)^2s}}\frac{(\sqrt{2}+1)(\sqrt{s}+\alpha)}{\sqrt{2}(\sqrt{s}-1)} \theta_{st, (t-1)s}<1, \end{align} with $t\geq3$. Then \begin{align}\label{prop:NSP.eq1} \|\bm{D}_{S}^{\top}\bm{h}\|_2\leq&\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})}\frac{\sqrt{\lceil(t-1)s\rceil}}{(t-1)(s-\sqrt{s})}\Big(c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\gamma\Big) \nonumber\\ &+ \Big(\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})}\frac{\sqrt{(t-1)s}}{(t-1)(s-\sqrt{s})}+\frac{\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}\Big)\eta\|\bm{Ah}\|_{2}, \end{align} where $\eta\geq 1$. \item[(iv)] Let $\bm {A}$ satisfy $\bm D$-RIP with \begin{align}\label{RIPCondition1} \rho_{s}=:\delta_{s}+\frac{(\sqrt{2}+1)(\sqrt{s}+\alpha)}{\sqrt{2}(\sqrt{s}-1)} \theta_{s,s}<1. \end{align} Then \begin{align}\label{prop:NSP.eq2} \|\bm{D}_{S}^{\top}\bm{h}\|_2\leq&\frac{(\sqrt{2}+1)\theta_{s,s}}{\sqrt{2}(1-\rho_{s})(\sqrt{s}-1)}\Big(c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\gamma\Big) \nonumber\\ &+ \Big(\frac{(\sqrt{2}+1)\theta_{s,s}}{\sqrt{2}(1-\rho_{s})(\sqrt{s}-1)}+\frac{\sqrt{1+\delta_{s}}}{1-\rho_{s}}\Big)\eta\|\bm{Ah}\|_{2}, \end{align} where $\eta\geq 1$. \item[(v)] For the term $\|\bm{D}_{S^c}^{\top}\bm{h}\|_2$, there is \begin{align}\label{DSC} &\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\nonumber\\ &\leq\Bigg(\sqrt{\frac{a\sqrt{s}+b}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+\bar{\varepsilon}}{2\sqrt{s}}\Bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2 +\frac{1}{2\bar{\varepsilon}}\big(c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|\bm{Ah}\|_2+\gamma\big), \end{align} where $\bar{\varepsilon}>0$ is a constant. \end{description} \end{proposition} \begin{proof} Please see Appendix \ref{appendx1}. \end{proof} \subsection{Main Result Under RIP Frame }\label{s3.2} \noindent Now, we show the stable recovery conditions based $\bm{D}$-RIP for the $\ell_{1}-\alpha \ell_{2}$-ASSO (\ref{VectorL1-alphaL2-ASSO}) and the $\ell_{1}-\alpha \ell_{2}$-RASSO (\ref{VectorL1-alphaL2-RASSO}), respectively. \begin{theorem}\label{StableRecoveryviaVectorL1-alphaL2-ASSO} Consider $\bm { b}=\bm { Ax}+\bm {e}$ with $\|\bm {e}\|_{2}\leq \eta$. Let $\hat{\bm {x}}$ be the minimizer of the $\ell_{1}-\alpha \ell_{2}$-ASSO (\ref{VectorL1-alphaL2-ASSO}). The following statements hold: \begin{description} \item[(i)] If the measurement matrix $\bm {A}$ satisfies \eqref{RIPConditiona1add}, then \begin{align*} &\|\hat{\bm {x}}-\bm {x}\|_2\nonumber\\ \leq& \Bigg(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\left(\tau+\frac{\left(\tau(1-\rho_{s,t})+\sqrt{1+\delta_{ts}}\right)C}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\right)\nonumber\\ &\hspace*{12pt}+\frac{1}{2}\left(1+\frac{C(1-\rho_{s,t})}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\right)\Bigg) 2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1\nonumber\\ &+\left(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\frac{\tau(1-\rho_{s,t})+\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}+\frac{1}{2}\right)\nonumber\\ &\hspace*{12pt}\times\left(C+\frac{(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}{(1-\rho_{s,t})}\right)2\lambda, \end{align*} where the constants $\tau$ and $C$ are as follows \begin{align}\label{Constant.t>=3} \begin{cases} \tau=\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})}\frac{\sqrt{(t-1)s}}{(t-1)(s-\sqrt{s})},&\\ C=1+\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})}\frac{(\sqrt{s}+\alpha)}{(s-\sqrt{s})}\frac{\sqrt{(t-1)s}}{t-1}. \end{cases} \end{align} \item[(ii)]If the measurement matrix $\bm {A}$ satisfies \eqref{RIPCondition1}, then \begin{align*} \|\hat{\bm {x}}-\bm {x}\|_2 \leq& \Bigg(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\left(\tau+\frac{\left(\tau(1-\rho_{s})+\sqrt{1+\delta_{s}}\right)C}{C(1-\rho_{s})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{s}}}\right)\nonumber\\ &\hspace*{12pt}+\frac{1}{2}\left(1+\frac{C(1-\rho_{s})}{C(1-\rho_{s})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{s}}}\right)\Bigg) 2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1\nonumber\\ &+\left(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\frac{\tau(1-\rho_{s})+\sqrt{1+\delta_{s}}}{1-\rho_{s}}+\frac{1}{2}\right)\nonumber\\ &\hspace*{12pt}\times\left(C+\frac{(\sqrt{s}+\alpha)\sqrt{1+\delta_{s}}}{(1-\rho_{s})}\right)2\lambda, \end{align*} where the constants $\tau$ and $C$ are as follows \begin{align}\label{Constant.t=2} \begin{cases} \tau=\frac{(\sqrt{2}+1)\theta_{s,s}}{\sqrt{2}(1-\rho_{s})}\frac{1}{\sqrt{s}-1},&\\ C=1+\frac{(\sqrt{2}+1)\theta_{s,s}}{\sqrt{2}(1-\rho_{s})}\frac{\sqrt{s}+\alpha}{\sqrt{s}-1}. \end{cases} \end{align} \end{description} \end{theorem} \begin{theorem}\label{StableRecoveryviaVectorL1-alphaL2-RASSO} Consider $\bm { b}=\bm { Ax}+\bm {e}$ with $\|\bm {e}\|_{2}\leq \eta$. Let $\hat{\bm {x}}$ be the minimizer of the $\ell_{1}-\alpha \ell_{2}$-RASSO (\ref{VectorL1-alphaL2-RASSO}). The following statements hold: \begin{description} \item[(i)] If the measurement matrix $\bm {A}$ satisfies the $\bm D$-RIP with \eqref{RIPConditiona1add}, then \begin{align*} &\|\hat{\bm {x}}-\bm {x}\|_2\nonumber\\ \leq& \Bigg(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\left(\tau+\frac{\left(\tau(1-\rho_{s,t})+\sqrt{1+\delta_{ts}}\right)C}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\right)\nonumber\\ &\hspace*{12pt}+\frac{1}{2}\left(1+\frac{C(1-\rho_{s,t})}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\right)\Bigg)\nonumber\\ &\times\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right)\nonumber\\ &+\left(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\frac{\tau(1-\rho_{s,t})+\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}+\frac{1}{2}\right)\nonumber\\ &\hspace*{12pt}\times\left(C+\frac{(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}{(1-\rho_{s,t})}\right)2\lambda, \end{align*} where the constants $\tau$ and $C$ are in \eqref{Constant.t>=3}. \item[(ii)] If the measurement matrix $\bm {A}$ satisfies the $\bm D$-RIP with \eqref{RIPCondition1}, then \begin{align*} \|\hat{\bm {x}}-\bm {x}\|_2 \leq& \Bigg(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\left(\tau+\frac{\left(\tau(1-\rho_{s})+\sqrt{1+\delta_{s}}\right)C}{C(1-\rho_{s})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{s}}}\right)\nonumber\\ &\hspace*{12pt}+\frac{1}{2}\left(1+\frac{C(1-\rho_{s})}{C(1-\rho_{s})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{s}}}\right)\Bigg)\nonumber\\ &\times\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right)\nonumber\\ &+\left(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\frac{\tau(1-\rho_{s})+\sqrt{1+\delta_{s}}}{1-\rho_{s}}+\frac{1}{2}\right)\nonumber\\ &\hspace*{12pt}\times\left(C+\frac{(\sqrt{s}+\alpha)\sqrt{1+\delta_{s}}}{(1-\rho_{s})}\right)2\lambda, \end{align*} where the constants $\tau$ and $C$ are in \eqref{Constant.t=2}. \end{description} \end{theorem} \begin{remark} The condition \eqref{RIPCondition1} reduces to \begin{equation}\label{RIPCondition2} \delta_{2s}<\frac{1}{\frac{\bigg(1+\frac{\sqrt{2}}{2}\bigg)(\sqrt{s}+\alpha)}{\sqrt{s}-1}+1}. \end{equation} It is clearly weaker than the following condition in \cite[Theorem 2]{ge2021dantzig} \begin{equation* \delta_{2s}<\frac{1}{\sqrt{1+\frac{(\sqrt{s}+{\alpha})^2\Big(\Big(1+\frac{\sqrt{2}}{2}\Big)^2( s-\sqrt{s})+1\Big)}{s(\sqrt{s}-1)^2}}}, \end{equation*} and the following condition in \cite[Theorem 3.4]{ge2021new} \begin{equation*} \delta_{2s}<\frac{1}{\sqrt{1+\frac{(\sqrt{s}+1)^2\Big(\Big(1+\frac{\sqrt{2}}{2}\Big)^2( s-\sqrt{s})+1\Big)}{s(\sqrt{s}-1)^2}}}. \end{equation*} \end{remark} \begin{remark} We notice that Wang and Wang \cite[Equation (6)]{wang2019improved} established the following condition \begin{equation}\label{RIPCondition.wang2019improved} \delta_{s}+\frac{\sqrt{s}+\sqrt{2}-1}{\sqrt{s}-1} \theta_{s,s}<1. \end{equation} Though it is weaker than our condition \begin{equation}\label{RIPCondition3} \delta_{s}+\frac{(\sqrt{2}+1)(\sqrt{s}+\alpha)}{\sqrt{2}(\sqrt{s}-1)} \theta_{s,s}<1 \end{equation} for {$s\geq2$}, their condition is for the constraint $\ell_1-\ell_2$ model rather than unconstraint $\ell_1-\ell_2$ model. \end{remark} \begin{remark} Our condition \eqref{RIPCondition2} is weaker than that of \cite[Corollary 2]{geng2020Unconstrained} \begin{equation}\label{CoherenceCondition.geng2020Unconstrained} \mu<\frac{1}{3s+6}, \end{equation} owing to $\mu=\delta_{2s}$. \end{remark} Proofs of Theorems $1$ and $2$ is similar, so we only present the detail proof of Theorem \ref{StableRecoveryviaVectorL1-alphaL2-RASSO}. \begin{proof}[Proof of Theorem \ref{StableRecoveryviaVectorL1-alphaL2-RASSO}] We first show the conclusion $(\bm{i})$. By $\bm{D}\bm{D}^{\top}=\bm{I}_n$, we know \begin{align}\label{decomposition} \|\bm{h}\|_2=\|\bm{D}^{\top}\bm{h}\|_2=\sqrt{\|\bm{D}_{S}^{\top}\bm{h}\|_2^2+\|\bm{D}_{S^c}^{\top}\bm{h}\|_2^2} \leq \|\bm{D}_{S}^{\top}\bm{h}\|_2+ \|\bm{D}_{S^c}^{\top}\bm{h}\|_2, \end{align} where $\|\bm{D}_{S}^{\top}\bm{h}\|_2$ and $\|\bm{D}_{S^c}^{\top}\bm{h}\|_2$ are needed to estimated, respectively. We first estimate $\|\bm{D}_{S}^{\top}\bm{h}\|_2$. By Lemma \ref{ConeTubeconstraint-L1-L2-RASSO}, then the condition \eqref{lem:CrossItem.eq1} holds with $a=1,~b=\alpha,~c=2,~\eta=1,~\gamma=(\alpha+1)^{2}d\lambda/(2\rho)$. Using Proposition \ref{lem:CrossItem} $(iii)$, one has \begin{align}\label{prop:NSP.eq1cge} \|\bm{D}_{S}^{\top}\bm{h}\|_2\leq&\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})} \frac{\sqrt{\lceil(t-1)s\rceil}}{(t-1)(s-\sqrt{s})} \Big(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^{2}d\lambda}{2\rho}\Big) \nonumber\\ &+ \Big(\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})}\frac{\sqrt{\lceil(t-1)s\rceil}} {(t-1)(s-\sqrt{s})}+\frac{\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}\Big)\|\bm{Ah}\|_{2}\nonumber\\ =& \tau \Big(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^{2}d\lambda}{2\rho}\Big) +\bar{\tau}\|\bm{Ah}\|_{2}, \end{align} where \begin{align}\label{tau} \begin{cases} \tau=\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})}\frac{\sqrt{\lceil(t-1)s\rceil}}{(t-1)(s-\sqrt{s})},&\\ \bar{\tau}=\tau+\frac{\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}. \end{cases} \end{align} In order to estimate $\|\bm{D}_{S}^{\top}\bm{h}\|_2$, we need an upper bound of $\|\bm{Ah}\|_{2}$. Using Lemma \ref{ConeTubeconstraint-L1-L2-RASSO}, we derive \begin{align*} &\|\bm{Ah}\|_2^2-2\lambda\|\bm{Ah}\|_2\nonumber\\ &\leq2\lambda\left(\|\bm{D}_{S}^{\top}\bm{h}\|_1+2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}+\alpha\|\bm{D}^{\top }\bm{h}\|_2-\|\bm{D}_{S^c}^{\top}\bm{h}\|_1\right)\nonumber\\ &\leq2\sqrt{s}\lambda\|\bm{D}_{S}^{\top}\bm{h}\|_2 +2\lambda\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}+\alpha\|\bm{D}_{S}^{\top}\bm{h}\|_2+\alpha\|\bm{D}_{S^c}^{\top }\bm{h}\|_2-\|\bm{D}_{S^c}^{\top}\bm{h}\|_1\right)\nonumber\\ &\overset{(a)}{\leq} 2\lambda(\sqrt{s}+\alpha)\|\bm{D}_{S}^{\top}\bm{h}\|_2+2\lambda\left(2\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\right)\nonumber\\ &\overset{(b)}{\leq}2\lambda(\sqrt{s}+\alpha)\left(\bar{\tau}\|\bm{Ah}\|_2+\tau\left(2\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\right)\right)\nonumber\\ &\hspace*{12pt}+2\lambda\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\right)\nonumber\\ &=2\lambda(\sqrt{s}+\alpha)\bar{\tau}\|\bm{Ah}\|_2+2\lambda(1+(\sqrt{s}+\alpha)\tau)\left(2\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\right), \end{align*} where (a) follows from $\alpha\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\leq\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\leq\|\bm{D}_{S^c}^{\top}\bm{h}\|_1$, (b) is because of \eqref{prop:NSP.eq1cge}. Thus \begin{align*} \|\bm{Ah}\|_2^2-2\lambda(1+(\sqrt{s}+\alpha)\bar{\tau})\|\bm{Ah}\|_2-2\lambda(1+(\sqrt{s}+\alpha)\tau )\left(2\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\right)\leq0. \end{align*} By the fact that the second order inequality $aX^2-bX-c\leq0$ for $a,b,c>0$ has the solution $$X\leq \frac{b+\sqrt{b^2+4ac}}{2a}\leq\frac{b+\sqrt{(b+2ac/b)^2}}{2a} =\frac{b}{a}+\frac{c}{b},$$ then \begin{align}\label{Ah} \|\bm{Ah}\|_2 &\leq(1+(\sqrt{s}+\alpha)\bar{\tau})2\lambda+\frac{(1+(\sqrt{s}+\alpha)\tau )\left(2\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\right)}{1+(\sqrt{s}+\alpha)\bar{\tau}}\nonumber\\ &=2 \bar{C}\lambda+\frac{C}{\bar{C}}\Big(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\Big), \end{align} where \begin{align}\label{C.constant} \begin{cases} C=1+(\sqrt{s}+\alpha)\tau =1+\frac{(\sqrt{2}+1)\theta_{ts,(t-1)s}}{\sqrt{2}(1-\rho_{s,t})}\frac{(\sqrt{s}+\alpha)}{(s-\sqrt{s})}\frac{\sqrt{(t-1)s}}{t-1},&\\ \bar{C}=1+(\sqrt{s}+\alpha)\bar{\tau}=C + \frac{(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}. \end{cases} \end{align} Combining \eqref{prop:NSP.eq1cge} with \eqref{Ah}, one has \begin{eqnarray}\label{StableRecoveryviaVectorL1-alphaL2-ASSO.eq1} &&\|\bm{D}_{S}^{\top}\bm{h}\|_2\nonumber\\ &&\leq\tau \left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right)+\bar{\tau} \left(2\lambda \bar{C}+\frac{C}{\bar{C}}\Big(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\Big)\right)\nonumber\\ &&=\left(\tau +\frac{C}{\bar{C}}\bar{\tau}\right)\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right) +2\bar{\tau}\bar{C}\lambda. \end{eqnarray} Next, we consider an upper bound of $\|\bm{D}_{S^c}^{\top}\bm{h}\|_2$. And from Proposition \eqref{lem:CrossItem} $(v)$ with $\bar{\varepsilon}=1$, it follows that \begin{align}\label{DSCge} &\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\nonumber\\ &\leq\Bigg(\sqrt{\frac{\sqrt{s}+\alpha}{\sqrt{s}} +\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}\Bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2 +\frac{1}{2}\Big(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\|\bm{Ah}\|_2+\frac{(\alpha+1)^{2}d\lambda}{2\rho}\Big). \end{align} Similarly, combining \eqref{Ah} with \eqref{StableRecoveryviaVectorL1-alphaL2-ASSO.eq1}, \eqref{DSCge} reduces to \begin{align}\label{StableRecoveryviaVectorL1-alphaL2-ASSO.eq2} &\|\bm{D}_{S^c}^{\top}\bm{h}\|_2 \leq\Bigg(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}\Bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2 +\frac{1}{2}\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right)\nonumber\\ &\hspace*{12pt}+\frac{1}{2}\Big(2\bar{C} \lambda +\frac{C}{\bar{C}}\Big(2\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\frac{(\alpha+1)^2d\lambda}{2\rho}\Big)\Big)\nonumber\\ &\leq\Bigg(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}} \Bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2 +\frac{1}{2}\bigg(1+\frac{C}{\bar{C}}\bigg)\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right)\nonumber\\ &\hspace*{12pt}+\bar{C}\lambda. \end{align} Therefore, substituting the estimation of $\|\bm{D}_{S}^{\top}\bm{h}\|_2$ and $\|\bm{D}_{S^c}^{\top}\bm{h}\|_2$ into \eqref{decomposition}, one has \begin{align*} \|\bm {h}\|_2 &\overset{(a)}{\leq}\Bigg(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \Bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2\nonumber\\ &\hspace*{12pt}+\frac{1}{2}\bigg(1+\frac{C}{\bar{C}}\bigg)\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right) +\bar{C}\lambda\nonumber\\ &\overset{(b)}{\leq}\Bigg(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \Bigg)\left(\left(\tau +\bar{\tau}\frac{C}{\bar{C}}\right)\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right) +\bar{\tau}\bar{C}2\lambda\right)\nonumber\\ &\hspace{24pt}+\frac{1}{2}\bigg(1+\frac{C}{\bar{C}}\bigg)\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right) +\bar{C}\lambda\nonumber\\ &= \Bigg(\Bigg(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \Bigg)\left(\tau +\bar{\tau}\frac{C}{\bar{C}}\right)+\frac{1}{2}\bigg(1+\frac{C}{\bar{C}}\bigg)\Bigg)\nonumber\\ &\hspace*{12pt}\times\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right) +\left(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\bar{\tau}+\frac{1}{2}\right)2\bar{C}\lambda\nonumber\\ &=:E_{1}\left(2\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\frac{(\alpha+1)^2d}{2}\frac{\lambda}{\rho}\right) +E_{2}2\lambda, \end{align*} where (a) is due to \eqref{StableRecoveryviaVectorL1-alphaL2-ASSO.eq2}, and (b) is from \eqref{StableRecoveryviaVectorL1-alphaL2-ASSO.eq1}. Recall the definition of the constants $\tau,\bar{\tau}$ in \eqref{tau} and $C,\bar{C}$ in \eqref{C.constant}, we get \begin{align} &E_{1} =\Bigg(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1\Bigg)\nonumber\\ &\hspace*{12pt}\times\left(\tau +\left(\tau+\frac{\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}\right)\left(\frac{C(1-\rho_{s,t})}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\right)\right) \nonumber\\ &+\frac{1}{2}\bigg(1+\frac{C(1-\rho_{s,t})}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\bigg)\nonumber\\ &=\Bigg(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \Bigg)\left(\tau +\frac{\big(\tau(1-\rho_{s,t})+\sqrt{1+\delta_{ts}}\big)C}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\right)\nonumber\\ &+\frac{1}{2}\bigg(1+\frac{C(1-\rho_{s,t})}{C(1-\rho_{s,t})+(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}\bigg),\nonumber\\ E_{2}&=\left(\left(\sqrt{\frac{\alpha+\sqrt{s}}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+1}{2\sqrt{s}}+1 \right)\frac{\tau(1-\rho_{s,t})+\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}+\frac{1}{2}\right)\nonumber\\ &\hspace*{12pt}\times\left(C+\frac{(\sqrt{s}+\alpha)\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}\right). \end{align} Therefore, we complete the proof of item ($i$). ($ii$) We can prove the conclusion ($ii$) in a similar way only by replacing Proposition \ref{lem:CrossItem} (iii) with Proposition \ref{lem:CrossItem} (iv). \end{proof} \section{Numerical Algorithm }\label{s4} \noindent In this section, we develop an efficient algorithm to solve the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO}. The projected fast iterative soft-thresholding algorithm (pFISTA) for tight frames in \cite{liu2016projected} is suited solving the $\ell_1$-analysis problem \eqref{VectorL1-ana} for MRI reconstruction. Compared to the common iterative reconstruction methods such as iterative soft-thresholding algorithm (ISTA) in \cite{daubechies2004iterative} and fast iterative soft-thresholding algorithm (FISTA) in \cite{beck2009fast}, the pFISTA algorithm achieves better reconstruction and converges faster. Inspired by the pFISTA algorithm, an efficient algorithm is introduced to solve the nonconvex-ASSO problem \eqref{VectorL1-alphaL2-ASSO} in this section. For the given frame $\bm{D}\in\mathbb{R}^{n\times d}$, there are many dual frames. Here, we only consider its canonical dual frame \begin{equation}\label{canonicaldual} \bm{\Phi}=(\bm{D}\bm{D}^{\top})^{-1}\bm{D}, \end{equation} which satisfies $$ \bm{\Phi}\bm{D}^{\top}=\bm{I}_{n}, $$ and is also the pseudo-inverse of $\bm{D}$ \cite{elad2007analysis}. Taking $\bm{z}=\bm{D}^{\top}\bm{x}$, the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} is written as \begin{equation}\label{VectorL1-alphaL2-ASSO.equi1} \min_{\bm{ z}\in\text{Range}(\bm{D}^{\top})}~\lambda(\|\bm{z}\|_{1}-\alpha\|\bm{z}\|_{2})+\frac{1}{2}\|\bm{ A}\bm{\Phi}\bm{ z}-\bm{ b}\|_{2}^{2}. \end{equation} Now, we solve \eqref{VectorL1-alphaL2-ASSO.equi1} by the idea of the pFISTA algorithm. First, we introduce an indicator function \begin{equation*} \chi(\bf{z})= \begin{cases} \bm{0},~\bm{z}\in\text{Range}(\bm{D}^{\top}),&\\ +\bm{\infty},~\text{otherwise}, \end{cases} \end{equation*} then an equivalent unconstrained model of \eqref{VectorL1-alphaL2-ASSO.equi1} is \begin{equation}\label{VectorL1-alphaL2-ASSO.equi2} \min_{\bm{ z}\in\mathbb{R}^{d}}~\lambda(\|\bm{ z}\|_{1}-\alpha\|\bm{ z}\|_{2})+\chi(\bm{z})+\frac{1}{2}\|\bm{ A}\bm{\Phi}\bm{ z}-\bm{ b}\|_{2}^{2}. \end{equation} Let $$ g(\bm{z})=\lambda(\|\bm{ z}\|_{1}-\alpha\|\bm{ z}\|_{2})+\chi(\bm{z}),~~h(\bm{z})=\frac{1}{2}\|{\bm A}\bm{\Phi}{\bm z}-{\bm b}\|_{2}^{2}, $$ then \eqref{VectorL1-alphaL2-ASSO.equi2} can be rewritten as \begin{equation}\label{OptimizationProblem} \min_{{\bm z}\in\mathbb{R}^{d}}~g(\bm{z})+h(\bm{z}), \end{equation} where $g$ is a non-smooth function, and $h$ is a smooth function with a $\ell_{h}$-Lipschitz continuous gradient ($\ell_{h}>0$), i.e $$ \|\nabla h(\bm{z}_1)- \nabla h(\bm{z}_2)\|_{2}\leq\ell_{h}\|\bm{z}_1-\bm{z}_2\|_{2}. $$ Next, we solve \eqref{VectorL1-alphaL2-ASSO.equi2} via ISTA by incorporating the proximal mapping \begin{align}\label{ISTA1} \bm{z}^{k+1}&=\text{Prox}_{\gamma g}(\bm{z}^{k}-\gamma \nabla h(\bm{z}^{k}))\nonumber\\ &=\arg\min_{\bm{ z}\in\text{Range}(\bm{D}^{\top})}\gamma\lambda(\|\bm{ z}\|_{1}-\alpha\|\bm{z}\|_{2}) +\frac{1}{2}\left\|\bm{z}-\left(\bm{z}^{k}-\gamma \nabla h(\bm{z}^{k})\right)\right\|_{2}^{2}, \end{align} where $\gamma$ is the step size and $\text{Prox}_{\gamma g}(\cdot)$ is the proximal operator of the function $\gamma g$. The proximal operator of $\mu_1\ell_1-\mu_2\ell_2$ in \cite[Proposition 7.1]{liu2017further} and \cite[Section 2]{lou2018fast} is \begin{equation}\label{L1L2-ProximalMap4} \text{Prox}_{\lambda(\ell_1-\alpha\ell_2)}({\bm b})=\arg\min_{\bm{x}}\frac{1}{2}\|\bm{x}-\bm{b}\|_2^2+\lambda(\|\bm{ x}\|_1-\alpha\|\bm{ x}\|_2), \ \ \ \ 0<\alpha\leq 1, \end{equation} which has an explicit formula for ${\bm x}$. And the solution in \eqref{L1L2-ProximalMap4} is unique in some special cases. Therefore the problem \eqref{ISTA1} is just as follows \begin{align}\label{ISTA1.2} \bm{z}^{k+1} =\text{Proj}_{\text{Range}(\bm{D}^{\top})}\left(\text{Prox}_{\lambda(\ell_1-\alpha\ell_2)}\left(\left(\bm{z}^{k}-\gamma \nabla h(\bm{z}^{k})\right)\right)\right), \end{align} where $\text{Proj}_{\mathcal{C}}(\cdot)$ is a projection operator on the set $\mathcal{C}$. So far, the original analysis model \eqref{VectorL1-alphaL2-ASSO} has been converted into a much simpler form \eqref{ISTA1}. However, it is a challenge to find an analytical solution of \eqref{ISTA1} since there is the constraint ${\bm z}\in\text{Range}(\bm{D}^{\top})$. Note that the orthogonal projection operator on $\text{Range}(\bm{D}^{\top})=\{\bm{\Phi}\bm{z}:\bm{z}\in\mathbb{R}^{d}\}$ is $$ \text{Proj}_{\text{Range}(\bm{D}^{\top})}(\bm{z})=\bm{D}^{\top}\bm{\Phi}\bm{z}. $$ Therefore, we propose to replace \eqref{ISTA1} by \begin{align}\label{ISTA2} \begin{cases} \tilde{\bm{z}}^{k+1}=\text{Prox}_{\lambda\gamma(\ell_1-\alpha\ell_2)}\left(\bm{z}^{k}-\gamma \bm{\Phi}^{\top}\bm{A}^{\top}(\bm{A}\bm{\Phi}\bm{z}^{k}-\bm{b})\right),&\\ \bm{z}^{k+1}=\text{Proj}_{\text{Range}(\bm{D}^{\top})}(\tilde{\bm{z}}^{k+1})=\bm{D}^{\top}\bm{\Phi}\tilde{\bm{z}}^{k+1}.& \end{cases} \end{align} By the fact that $\bm{\Phi}\bm{D}^{\top}=\bm{I}_{n}$ and \eqref{canonicaldual}, the two steps in \eqref{ISTA2} can be recast as \begin{align}\label{ISTA3} \tilde{\bm{z}}^{k+1}=\text{Prox}_{\lambda\gamma(\ell_1-\alpha\ell_2)}\left(\bm{D}^{\top}\left(\bm{\Phi}\tilde{\bm{z}}^{k}-\gamma (\bm{D}\bm{D}^{\top})^{-1}\bm{A}^{\top}(\bm{A}\bm{\Phi}\tilde{\bm{z}}^{k}-\bm{b})\right)\right). \end{align} Now, let us turn our attention to how to get the formulation of $\bm{x}^{k+1}$. By substituting the coefficients $\bm{x}^{k}=\bm{\Phi}\bm{z}^{k}=\bm{\Phi}\bm{D}^{\top}\bm{\Phi}\tilde{\bm{z}}^{k}= \bm{\Phi}\tilde{\bm{z}}^{k}$ into \eqref{ISTA3}, one has \begin{align}\label{ISTA4} \bm{x}^{k+1}=\bm{\Phi}\text{Prox}_{\lambda\gamma(\ell_1-\alpha\ell_2)}\left(\bm{D}^{\top}\left(\bm{x}^{k}-\gamma (\bm{D}\bm{D}^{\top})^{-1}\bm{A}^{\top}(\bm{A}\bm{x}^{k}-\bm{b})\right)\right), \end{align} which is a solution of the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO}. For a tight frame, we have $\bm{\Phi}=\bm{D}$ and $\bm{D}\bm{D}^{\top}=\bm{I}_{n}$, then \eqref{ISTA4} reduces to \begin{align}\label{ISTA5} \bm{x}^{k+1}=\bm{D}\text{Prox}_{\lambda\gamma(\ell_1-\alpha\ell_2)}\left(\bm{D}^{\top}\left(\bm{x}^{k}-\gamma \bm{A}^{\top}(\bm{A}\bm{x}^{k}-\bm{b})\right)\right). \end{align} Based on all the above derivations, the efficient algorithm of the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} is proposed and summarized in Algorithm $1$ as follows. \medskip \noindent\rule[0.25\baselineskip]{\textwidth}{1pt} \label{al:pFISTA} \centerline {\bf Algorithm $1$: the $\ell_1-\alpha\ell_2$-pFISTA for solving \eqref{VectorL1-alphaL2-ASSO}}\\ {\bf Input:}\ ${\bm A}$,${\bm D}$, ${\bm b}$, $0<\alpha\leq 1$, $\lambda$, $\gamma$. \\ {\bf Initials:}\ $\bm{ x}=\bm{x}^0$, $\bm{ y}=\bm{y}^0=\bm{x}^0$, $t=t^0=1$, $k=0$.\\ {\bf Circulate} Step 1--Step 4 until ``some stopping criterion is satisfied": ~{\bf Step 1:} Update ${\bm x}^{k+1}$ according to \begin{equation}\label{FISTA1} \bm{x}^{k+1}=\bm{D}~\text{Prox}_{\lambda\gamma(\ell_1-\alpha\ell_2)}\left(\bm{D}^{\top}\left(\bm{y}^{k}-\gamma \bm{A}^{\top}(\bm{A}\bm{y}^{k}-\bm{b})\right)\right). \end{equation} ~{\bf Step 2:} Update ${\bm t}^{k+1}$ as follows \begin{equation}\label{FISTA2} t_{k+1}=\frac{1+\sqrt{1+4t_{k}^2}}{2}. \end{equation} ~{\bf Step 3:} Update $\bm{y}^{k+1}$ as follows \begin{equation}\label{FISTA3} \bm{y}_{k+1}=\bm{x}^{k+1}+\frac{t_k-1}{t_{k+1}}(\bm{x}^{k+1}-\bm{x}^{k}). \end{equation} ~{\bf Step 4:} Update $k$ to $k+1$.\\ {\bf Output:} $\hat{\bm {x}}$.\\ \noindent\rule[0.25\baselineskip]{\textwidth}{1pt} \begin{remark} In our algorithm, we set the total iterated number $K=1000$, and take the stopping criterion $\|\bm{x}^{k+1}-\bm{x}^{k}\|_{2}/\|\bm{x}^{k}\|_{2}<\epsilon$ with the tolerate error $\epsilon=10^{-6}$. \end{remark} \section{Numerical Experiments}\label{s5} \noindent In this section, we demonstrate the performance of the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} via simulation experiments and compare the proposed $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} to the state-of-art the $\ell_1$-analysis and $\ell_p$-analysis minimization methods. All experiments were performed under Windows Vista Premium and MATLAB v7.8 (R2016b) running on a Huawei laptop with an Intel(R) Core(TM)i5-8250U CPU at 1.8 GHz and 8195MB RAM of memory. \subsection{Signal Reconstruct Under Tight Frame}\label{s5.1} \noindent In this subsection, we evaluate the performance of the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} and compared our method with the following models: \begin{equation}\label{VectorL1-ABP} \min_{{\bm x}\in\mathbb{R}^n}~\lambda\|{\bm D}^{\top}{\bm x}\|_{p}^{p}~\text{subject~to~}{\bm A}{\bm x}={\bm b}. \end{equation} When $p=1$, the method \eqref{VectorL1-ABP} is Analysis Basis Pursuit, which is solved by CVX package (see \cite{genzel2021analysis,nam2013cosparse}). When $0<p<1$, Lin and Li \cite{lin2016restricted} present an algorithm based on iteratively reweighted least squares (IRLS) to solve the $\ell_{p}$-analysis model \eqref{VectorL1-ABP}. Many papers have showed that IRLS method with smaller value of $p$ (for example $p= 0.1, 0.5$) perform better than that of larger value of $p$ (for example $p= 0.7, 0.9$). In addition, $p=0.5$ gave slightly higher success frequency than $p=0.1$. Please refer to \cite[Section 4]{chartrand2008restricted}, \cite[Section 8.1]{daubechies2010iteratively}, and \cite[Section 4.1]{lai2013improved}. Therefore, we only compare our method with the $\ell_{p}$ model \eqref{VectorL1-ABP} for $p=0.5$. First of all, we roughly follow a construction of tight random frames from \cite{nam2013cosparse}: \begin{enumerate} \item[(i)]First, draw a $n\times d$ Gaussian random matrix $\bm{E}$ and compute its singular value decomposition $\bm{E}=\bm{U}\bm{\Sigma}\bm{V}^{\top}$. \item[(ii)] If $n\leq d$, we replace $\bm{\Sigma}$ by the matrix $\tilde{\bm{\Sigma}}=[\tau\bm{I}_n, \bm{0}]\in\mathbb{R}^{n\times d}$ with $\tau=\sqrt{d/n}$, which yields a tight frame $\bm{D}=\bm{U}\tilde{\bm{\Sigma}}\bm{V}^{\top}$. If $n> d$, we replace $\bm{\Sigma}$ by the matrix $\tilde{\bm{\Sigma}}=[\tau\bm{I}_d, \bm{0}]^{\top}\in\mathbb{R}^{n\times d}$ with $\tau=\sqrt{d/n}$, which yields a tight frame $\bm{D}=\bm{U}\tilde{\bm{\Sigma}}\bm{V}^{\top}$.\\ \end{enumerate} Nam et.al. \cite{nam2013cosparse} also showed us how to generate cosparse signal $\bm{x}_{0}\in\mathbb{R}^{n}$. We adopt their scheme and produce an $s$-cosparse signal in the following way: \begin{enumerate} \item[(a)] First, choose $s$ rows of the analysis operator $\bm{D}^{\top}=\bm{\Omega}\in\mathbb{R}^{n\times d}$ at random, and those are denoted by an index set $|S|$ (thus, $|S|=s$). \item[(b)] Second, form an arbitrary signal $\bm{y}$ in $\mathbb{R}^n$--e.g., a random vector with Gaussian i.i.d. entries. \item[(c)] Then, project $\bm{y}$ onto the orthogonal complement of the subspace generated by the rows of $\bm{\Omega}$ that are indexed by $S$, this way getting the cosparse signal $\bm{x}_0$. Explicitly, $\bm{x}_0=\left(\bm{I}_n-\bm{\Omega}_{S}^{\top }(\bm{\Omega}_{S}\bm{\Omega}_{S}^{\top})^{-1}\bm{\Omega}_{S}\right)\bm{y}$. In fact, $\bm{D}^{\top}\bm{x}_0=[\bm{0};\bm{\Omega}_{S^c}\bm{x}_0]\in\mathbb{R}^{d}$ is $(d-s)$-sparse. \end{enumerate} Alternatively, one could first find a basis for the orthogonal complement and then generate a random coefficient vector for the basis. In the experiment, the entries of $\bm{A}\in\mathbb{R}^{m\times n}$ are drawn independently from the normal distribution. The observation is obtained by $\bm{b} =\bm{A}\bm{x}_{0}$. Let $\hat{\bm x}$ be the reconstructed signal. We record the success rate over $100$ independent trials. The recovery is regarded as successful if \begin{equation}\label{rel.err} \text{rel-err}(\hat{\bm x},{\bm x}_0)=\frac{\|\hat{\bm x}-{\bm x}_0\|_2}{\|{\bm x}_0\|_2}<\varepsilon, \end{equation} for $\varepsilon=10^{-2}$. We display success rate of different algorithms to recover sparse signals over $100$ repeated trials for different cosparsity $s$. For fairness of comparison, the key parameters of our proposed method and compared algorithms have been tuned in all experiments according to \cite{nam2013cosparse}. In all cases, the signal dimension $n$ is set to 100. We then varied the number $m$ of measurements, the cosparsity $\ell$ of the target signal, and the operator size $d$ according to the following formulae: \begin{equation}\label{cosparsity.setup} m=\varrho n, d=\varsigma n, \ell=n-\rho m \end{equation} where $0<\varrho \leq 1$, $\varsigma\geq 1$, $0<\rho\leq1$. Here we take $\varsigma=1, \rho=\{0.05,0.10,0.15,\ldots,1\}$ and $\varrho=\{0.05,0.1,0.15,\ldots,1\}$, i.e., the measurement $m=\{5,10,15,\dots,100\}$. In Figure \ref{figure.SuccnumberPhaseTrransition-Comparion}, we plot the phase transition diagram, which characterizes sharp shifts in the success probability of reconstruction when the dimension parameter crosses a threshold. The $x$-axis and the $y$-axis represent the under-sampling ratio and co-sparsity ratio, respectively. Yellow and blue denote perfect recovery and failure in all experiments, respectively. It can be clearly seen that Success Rate (the yellow) of the proposed $\ell_1-\alpha\ell_2$ methods are the highest in all experiments. Experimental results show that $\ell_1-\alpha\ell_2$ methods outperform $\ell_1$ method and $\ell_p$ methods. Figure \ref{figure.CPUtimePhaseTrransition-Comparion} shows the average CPU time of all methods at different $\varrho$ and $\rho$. We can observe that the CPU time of the proposed method is significantly lower than those of $\ell_{1}$ method at whole, and higher than those of $\ell_p$ method for $p=0.5$. Thus, $\ell_1-\alpha\ell_2$-ASSO method can achieve a good balance between CPU time and recovery performance. \begin{figure*}[t] \begin{tabular}{ccc} \includegraphics[width=4.5cm,height=4.5cm]{L1_Succ_v3.eps}& \includegraphics[width=4.5cm,height=4.5cm]{IRLSp_Succ_v3.eps}& \includegraphics[width=4.5cm,height=4.5cm]{L1L2_Succ_v2.eps} \end{tabular} \centering \caption{Success percentage of the $\ell_1$-, $\ell_p$-~($p=0.5)$ and $\ell_{1}-\alpha\ell_{2}$-analysis for recover sparse signals versus the ratios $\varrho$ and $\rho$. } \label{figure.SuccnumberPhaseTrransition-Comparion} \end{figure*} \begin{figure*}[t] \begin{tabular}{c} \includegraphics[width=16.0cm]{Phase_Transition_Time_v4.eps} \end{tabular} \centering \caption{ CPU time of the $\ell_1$-, $\ell_p$-~($p=0.5)$ and $\ell_{1}-\alpha\ell_{2}$-analysis for the sparse signal recovery versus the ratios $\varrho$ and $\rho$.} \label{figure.CPUtimePhaseTrransition-Comparion} \end{figure*} \subsection{Reconstruction of Compressed Sensing Magnetic Resonance Imaging under Tight Frame}\label{s5.2} \noindent In this subsection, we consider the shift-invariant discrete wavelet transform (SIDWT) for tight frame $\bm{D}$, which is a typical tight frame in simulation \cite{baker2011translational,baraniukrice,coifman1995translation,kayvanrad2014stationary}. And SIDWT is also called as undecimated, translation-invariant, or fully redundant wavelets. In all the experiments, we utilize Daubechies wavelets with 4 decomposition levels in SIDWT. In CS-MRI, the sampling operator is $$\bm{A}=\bm{U}\mathcal{F},$$ where $\mathcal{F}$ is the discrete Fourier transform, and $\bm{U}$ is the sampling mask in the frequency space. The matrix $\bm{U}$ is also called the undersampling matrix. We keep samples along certain radial lines passing through the center of the Fourier data ($k$-space). We reconstruct magnetic resonance images (MRI) from incomplete spectral Fourier data: $256\times 256$ Brain MRI and $512\times 512$ Foot MRI (see \cite[Section 4.1]{li2020compressive}) via the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO}. Similarly, we compare the $\ell_1-\alpha\ell_2$-ASSO \eqref{VectorL1-alphaL2-ASSO} to the $\ell_1$-analysis and $\ell_p$($0<p<1$)-analysis minimization methods. We adopt the pFISTA for tight frames in \cite{liu2016projected} to solve the $\ell_1$-analysis minimization problem. The $\ell_p$($0<p<1$)-analysis model is \begin{equation}\label{Lp-Analysis} \min_{{\bm x}}~\lambda\|{\bm D}^{\top}{\bm x}\|_{p}^{p}+\frac{1}{2}\|\bm{UF}{\bm x}-{\bm b}\|_{2}^{2}, \end{equation} which is solved by the idea of the pFISTA for tight frames. In fact, as shown in section \ref{s4}, the equality \eqref{FISTA1} is replaced by \begin{equation}\label{FISTALp} \bm{x}^{k+1}=\bm{D}~\text{Prox}_{\lambda\gamma\ell_p}\left(\bm{D}^{\top}\left(\bm{y}^{k}-\gamma \bm{A}^{*}(\bm{A}\bm{y}^{k}-\bm{b})\right)\right), \end{equation} where $0<p<1$ and the notation ${Prox}_{\lambda\ell_p}(\bf{b})$ is the proximal operator of $\ell_{p}$ norm, see \cite{marjanovic2012optimization}. The quantitative comparison is done in terms of the relative error (RE) defined as $$ \text{RE}=\frac{\|\hat{\bm{x}}-\bm{x}_0\|_{2}}{\|\bm{x}_0\|_{2}}, $$ where $\bm{x}_0$ is the truth image and $\hat{\bm{x}}$ is the reconstructed image. To demonstrate how $\ell_1-\alpha\ell_2$-ASSO method compares with other methods in terms of image quality, we show the restored versions of Brain images and Foot images and reconstruction errors in Figures \ref{figure.Reconstruct-image-comparsion}, \ref{figure.Reconstruct-FootMRI-comparsion} and Table \ref{tab:MRI-Time}, respectively. In Figures \ref{figure.Reconstruct-image-comparsion} and \ref{figure.Reconstruct-FootMRI-comparsion}, we show the reconstructed images of different methods for $76$ radial sampling lines (sampling rate 30.81$\%$ and 16.17$\%$ for Brain-MRI and Foot-MRI, respectively). By inspecting the recovered images of brain, it can be seen that $\ell_1-\alpha\ell_2$ method can obtain better performance than other methods. We also record the CPU time of all methods in Table \ref{tab:MRI-Time}. \section{Conclusions }\label{s6} \noindent In this paper, we consider the signal and compressed sensing magnetic resonance imaging reconstruction under tight frame. We propose the unconstrained $\ell_{1}-\alpha\ell_{2}$-analysis model \eqref{VectorL1-alphaL2-ASSO} and \eqref{VectorL1-alphaL2-RASSO}. Based on the restricted isometry property and restricted orthogonality constant adapted to tight frame $\bm{D}$ ($\bm{D}$-RIP and $\bm{D}$-ROC), we develop new vital auxiliary tools (see Propositions \ref{prop.DROC} and \ref{NonsparseROC}) and sufficient conditions of stable recovery (see Theorems \ref{StableRecoveryviaVectorL1-alphaL2-ASSO} and \ref{StableRecoveryviaVectorL1-alphaL2-RASSO}). Based on the Projected FISTA \cite{liu2016projected}, we establish the fast and efficient algorithm to solve the unconstrained $\ell_{1}-\alpha\ell_{2}$-analysis model in Section \ref{s4}. The proposed method has better performance than the $\ell_p$-analysis model with $0<p\leq 1$ in numerical examples for the signal and compresses sensing MRI recovery. \begin{figure*}[htbp!] \setlength{\tabcolsep}{4.0pt}\small \begin{tabular}{c} \includegraphics[width=16.0cm,height=8.0cm]{Reconstruct_image_comparsion_different_v3.eps} \end{tabular} \centering \caption{\label{figure.Reconstruct-image-comparsion} Reconstructed Brain-MRI by the $\ell_1$-, $\ell_p$-~($0<p<1$) and $\ell_{1}-\alpha\ell_{2}$-analysis. From left to right in the first line: Ground truth, sample lines, $\ell_1$ reconstruction image, difference images of $\ell_1$ to the ground truth image. From left to right in the second line: $\ell_{0.1}$ reconstruction image, difference images of $\ell_{0.1}$ to the ground truth image, $\ell_{0.5}$ reconstruction image, difference images of $\ell_{0.5}$ to the ground truth image. From left to right in the third line: $\ell_{0.9}$ reconstruction image, difference images of $\ell_{0.9}$ to the ground truth image, $\ell_1-\alpha\ell_2$ reconstruction image, difference images of $\ell_1-\alpha\ell_2$ to the ground truth image. } \vspace{-0.1cm} \end{figure*} \begin{figure*}[htbp!] \setlength{\tabcolsep}{4.0pt}\small \begin{tabular}{c} \includegraphics[width=16.0cm,height=8.0cm]{Reconstruct_FootMRI_comparsion_different_v1.eps} \end{tabular} \centering \caption{\label{figure.Reconstruct-FootMRI-comparsion} Reconstructed Foot-MRI by the $\ell_1$-, $\ell_p$-~($0<p<1$) and $\ell_{1}-\alpha\ell_{2}$-analysis. From left to right in the first line: Ground truth, sample lines, $\ell_1$ reconstruction image, difference images of $\ell_1$ to the ground truth image. From left to right in the second line: $\ell_{0.1}$ reconstruction image, difference images of $\ell_{0.1}$ to the ground truth image, $\ell_{0.5}$ reconstruction image, difference images of $\ell_{0.5}$ to the ground truth image. From left to right in the third line: $\ell_{0.9}$ reconstruction image, difference images of $\ell_{0.9}$ to the ground truth image, $\ell_1-\alpha\ell_2$ reconstruction image, difference images of $\ell_1-\alpha\ell_2$ to the ground truth image. } \vspace{-0.1cm} \end{figure*} \begin{table}[htbp] \setlength{\tabcolsep}{5pt}\small \begin{center} \caption{The CPU Time (s) of Different reconstruction Models}\label{tab:MRI-Time} \begin{tabular}{|c|c|c|c|c|c|c|}\hline Image & Sampling Rate &$\ell_{1}$ &$\ell_{0.1}$ &$\ell_{0.5}$ &$\ell_{0.9}$ &$\ell_{1}-\alpha\ell_{2}$ \\\hline Brain-MRI &30.08$\%$ &80.9519 &164.4825 &238.4073 &322.2761 &85.1567 \\\hline Foot-MRI &16.17$\%$ &308.3546 &441.8828 &657.7717 &857.9363 &340.5498 \\\hline \end{tabular} \end{center} \end{table} \newpage \begin{appendices} \section{The proof of Lemma \ref{lem:CrossItem}}\label{appendx1} \noindent \begin{proof} $(\bm i)$ From the condition \eqref{lem:CrossItem.eq1}, it follows that \begin{align}\label{Coneconstraintinequality} \|\bm{D}_{S^c}^{\top}\bm{h}\|_1-\|\bm{D}_{S^c}^{\top}\bm{h}\|_2 &\overset{(a)}{\leq} \|\bm{D}_{S^c}^{\top}\bm{h}\|_1-\alpha\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\nonumber\\ &\leq a\|\bm{D}_{S}^{\top}\bm{h}\|_1+b\|\bm{D}_{S}^{\top}\bm{h}\|_2+c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm Ah}\|_2 +\gamma\nonumber\\ &\overset{(b)}{\leq}(a\sqrt{s}+b)\|\bm{D}_{S}^{\top}\bm{h}\|_2+c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm Ah}\|_2 +\gamma\nonumber\\ &\leq(s-\sqrt{s})\bigg( \frac{a\sqrt{s}+b}{\sqrt{s}-1}\frac{\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}}+\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm Ah}\|_2 +\gamma}{s-\sqrt{s}}\bigg)\nonumber\\ &=:(s-\sqrt{s})\varrho, \end{align} where $(a)$ is due to $0<\alpha\leq 1$, and $(b)$ follows from the fact $\|\bm{D}_{S}^{\top}\bm{h}\|_1\leq \sqrt{s}\|\bm{D}_{S}^{\top}\bm{h}\|_2$. Furthermore, using the fact that $(a-1)\sqrt{s}+(b+1)\geq0$, i.e., $\frac{a\sqrt{s}+b}{\sqrt{s}-1}\geq1$, one has \begin{align}\label{e:etainftynew} \|\bm{D}_{S^c}^{\top}\bm{h}\|_{\infty}\leq \frac{\|\bm{D}_{S}^{\top}\bm{h}\|_{1}}{s}\leq\frac{\|\bm{D}_{S}^{\top}\bm{h}\|_{2}}{\sqrt{s}}\leq\frac{\sqrt{s}+\alpha}{\sqrt{s}-1}\frac{\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}}\leq \varrho, \end{align} where the last inequality is due to the definition of $\varrho$ in \eqref{Coneconstraintinequality}. By Proposition \ref{NonsparseROC} with $\bm{u}=\|\bm{D}_{S}^{\top}\bm{h}\|_1$ and $\bm v=\|\bm{D}_{S^c}^{\top}\bm{h}\|_1$, the desired inequality \eqref{e:CrossItem1} is clear. $(\bm{ii})$ From the definition of $\tilde{S}$ in \eqref{def:S} and $\varrho$ in \eqref{Coneconstraintinequality}, it follows that \begin{align}\label{e:etaW2infty} \|\bm{D}_{{\tilde{S}}^c}^{\top}\bm{h}\|_{\infty}\leq\frac{\varrho}{t-1}, \end{align} and \begin{align}\label{e:etaW2} \|\bm{D}_{{\tilde{S}}^c}^{\top}\bm{h}\|_1-\|\bm{D}_{{\tilde{S}}^c}^{\top}\bm{h}\|_2 =&\|\bm{D}_{S^c}^{\top}\bm{h}-\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{1} -\|\bm{D}_{S^c}^{\top}\bm{h}-\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{2}\nonumber\\ \overset{(a)}{=}&\|\bm{D}_{S^c}^{\top}\bm{h}\|_1-\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{1} -\|\bm{D}_{S^c}^{\top}\bm{h}-\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{2}\nonumber\\ \overset{(b)}{\leq}&\big(\|\bm{D}_{S^c}^{\top}\bm{h}\|_1-\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\big) -(\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{1}-\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{2})\nonumber\\ \overset{(c)}{\leq}&(s-\sqrt{s})\varrho-(\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{1}-\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_{2}), \end{align} where $(a)$, $(b)$ and $(c)$ follow from $\tilde{S}\setminus S \subseteq S^{c}$, the triangle inequality on $\|\cdot\|_2$, and \eqref{Coneconstraintinequality}, respectively. For the second term of the above inequality, using Lemma \ref{LocalEstimateL1-L2} (b) with $S_1=\tilde{S}\setminus S$ and $S_2=\tilde{S}^c$, we derive that \begin{align}\label{e:eta-maxkuplowbound} \|\bm{D}_{S^c}^{\top}\bm{h}\|_1-\|\bm{D}_{S^c}^{\top}\bm{h}\|_2 \geq&\big(\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_1-\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_2\big) +\big(\|\bm{D}_{\tilde{S}^c}^{\top}\bm{h}\|_1-\|\bm{D}_{\tilde{S}^c}^{\top}\bm{h}\|_2\big)\nonumber\\ \geq&\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_1-\|\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h}\|_2\nonumber\\ \overset{(a)}{\geq}&(|\tilde{S}\setminus S|-\sqrt{|\tilde{S}\setminus S|})\min_{i\in \tilde{S}\setminus S}|(\bm{D}_{\tilde{S}\setminus S}^{\top}\bm{h})(i)|\nonumber\\ \overset{(b)}{\geq}&(|\tilde{S}\setminus S|-\sqrt{|\tilde{S}\setminus S|})\frac{\varrho}{t-1}, \end{align} where we use Lemma \ref{LocalEstimateL1-L2} (a) and the definition of $\tilde{S}$ in $(a)$ and $(b)$, respectively. Substituting \eqref{e:eta-maxkuplowbound} into \eqref{e:etaW2}, there is \begin{align}\label{e:l1-2upperbounds} \|\bm{D}_{\tilde{S}^c}^{\top}\bm{h}\|_1-\|\bm{D}_{\tilde{S}^c}^{\top}\bm{h}\|_2 \leq \Big((s(t-1)-|\tilde{S}\setminus S|)- (\sqrt{s}(t-1)-\sqrt{|\tilde{S}\setminus S|})\Big)\frac{\varrho}{t-1}. \end{align} Since $t\geq3$ and $s\geq 2$, as shown in the items (a) and (b) of \cite[Page 18]{ge2021dantzig}, we have $$|\tilde{S}\setminus S|< s(t-1),\ \ \ \ \sqrt{s(t-1)-|\tilde{S}\setminus S|}\leq \sqrt{s}(t-1)-\sqrt{|\tilde{S}\setminus S|}.$$ Then, \begin{align}\label{e:etaW2upperbound} \|\bm{D}_{\tilde{S}^c}^{\top}\bm{h}\|_1-\|\bm{D}_{\tilde{S}^c}^{\top}\bm{h}\|_2 \leq \Big(s(t-1)-|\tilde{S}\setminus S|-\sqrt{s(t-1)-|\tilde{S}\setminus S|}\Big)\frac{\varrho}{t-1}. \end{align} Therefore, from \eqref{e:etaW2infty}, \eqref{e:etaW2upperbound} and Proposition \ref{NonsparseROC} with $\bm u=\bm{D}_{\tilde{S}}^{\top}{\bm h}$, $\bm {v}=\bm{D}_{\tilde{S}^c}^{\top}\bm{h}$, it follows that \begin{align}\label{e:omegal2high} &|\langle \bm{AD}\bm{D}_{\tilde{S}}^{\top}{\bm h},\bm{AD}\bm{D}_{\tilde{S}^c}^{\top}{\bm h}\rangle +\langle\bar{\bm{ D}}\bm{D}_{\tilde{S}}^{\top}{\bm h},\bar{\bm{ D}}\bm{D}_{\tilde{S}^c}^{\top}{\bm h} \rangle|\nonumber\\ &\leq\bigg(1+\frac{\sqrt{2}}{2}\bigg)\theta_{ts, (t-1)s-|\tilde{S}\setminus S|}\sqrt{\lceil(t-1)s\rceil-|\tilde{S}\setminus S|} \frac{\varrho}{t-1}\|\bm{D}_{\tilde{S}}^{\top}{\bm h}\|_2\nonumber\\ &\leq \bigg(1+\frac{\sqrt{2}}{2}\bigg)\theta_{ts, (t-1)s}\sqrt{\lceil(t-1)s\rceil} \frac{\varrho}{t-1}\|\bm{D}_{\tilde{S}}^{\top}{\bm h}\|_2. \end{align} Based on the fact $\bar{\bm{ D}}\bm{D}^{\top}=\bm{0}$, the above inequality reduces to the desired \eqref{e:CrossItem2}. $(\bm{iii})$ For the term $\langle \bm{Ah}, \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\rangle$, there is \begin{align}\label{Upperbound} &|\langle \bm{Ah}, \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\rangle\big|\leq\| \bm{Ah}\|_{2}\|\bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_{2} \overset{(a)}{\leq}\sqrt{1+\delta_{ts}}\|\bm{D}\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_{2}\|\bm{Ah}\|_{2}\nonumber\\ &\leq\sqrt{1+\delta_{ts}}\|\bm{D}\|_{2\rightarrow 2}^{1/2}\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_{2}\|\bm{Ah}\|_{2} \overset{(b)}{=} \sqrt{1+\delta_{ts}}\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_{2}\|\bm{Ah}\|_{2}, \end{align} where $(a)$ is because of the matrix $\bm{A}$ satisfying the $\bm D$-RIP of $ts$ order, and $(b)$ follows from $\|\bm{D}\|_{2\rightarrow 2}=\|\bm{D}\bm{D}^{\top}\|_{2\rightarrow 2}^{1/2}=1$. Next, we will establish the lower bound of $\big|\langle \bm{Ah}, \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\rangle\big|$. Note that \begin{align*} \big|\langle \bm{Ah}, \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\rangle\big|\geq \| \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2-\big|\langle \bm{AD}\bm{D}_{\tilde{S}^c}^{\top}\bm{h}, \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\rangle\big|. \end{align*} From Proposition \ref{prop.DROC} with $\bm v=\bm{D}_{\tilde{S}^c}^{\top}\bm{h}$ and $\bar{\bm{ D}}\bm{D}^{\top}=\bm{0}$, it follows that \begin{align*} \| \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2 =\| \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2+\|\bar{\bm{D}}\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2 \geq(1-\delta_{ts})\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2. \end{align*} By \eqref{e:CrossItem2} in item (ii) and $\varrho$ in \eqref{Coneconstraintinequality}, we have \begin{align*} \big|\langle \bm{AD}\bm{D}_{\tilde{S}^c}^{\top}\bm{h}, \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\rangle\big| \leq \theta_{ts, (t-1)s}\sqrt{\lceil(t-1)s\rceil}\bigg(1+\frac{\sqrt{2}}{2}\bigg) \frac{\varrho}{t-1}\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2 \end{align*} Then, \begin{align}\label{Lowerbound} &\big|\langle \bm{Ah}, \bm{AD}\bm{D}_{\tilde{S}}^{\top}\bm{h}\rangle\big|\nonumber\\ &\geq(1-\delta_{ts})\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2-\theta_{ts, (t-1)s} \bigg(1+\frac{\sqrt{2}}{2}\bigg)\frac{\sqrt{\lceil(t-1)s\rceil}}{t-1}\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2\nonumber\\ &\cdot\bigg(\frac{a\sqrt{s}+b}{\sqrt{s}-1}\frac{\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}} +\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm Ah}\|_2+\gamma}{s-\sqrt{s}}\bigg)\nonumber\\ &\geq\bigg( 1-\delta_{ts}-\bigg(1+\frac{\sqrt{2}}{2}\bigg)\sqrt{\frac{\lceil(t-1)s\rceil}{(t-1)^2s}}\frac{a\sqrt{s}+b}{\sqrt{s}-1} \theta_{ts, (t-1)s }\bigg)\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2\nonumber\\ &-\theta_{ts,(t-1)s}\bigg(1+\frac{\sqrt{2}}{2}\bigg)\frac{\sqrt{\lceil(t-1)s\rceil}}{t-1}\frac{c\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\eta\|{\bm Ah}\|_2+\gamma}{s-\sqrt{s}}\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2, \end{align} where the last inequality is due to $S\subseteq \tilde{S}$. Combining \eqref{Lowerbound} with \eqref{Upperbound}, one has \begin{align* &\bigg( 1-\delta_{ts}-\sqrt{\frac{\lceil(t-1)s\rceil}{(t-1)^2s}}\frac{(\sqrt{2}+1)(\sqrt{s}+\alpha)}{\sqrt{2}(\sqrt{s}-1)} \theta_{ts,(t-1)s}\bigg)\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2^2\nonumber\\ &-\bigg(\theta_{ts,(t-1)s}\frac{\sqrt{2}+1}{\sqrt{2}}\frac{\sqrt{\lceil(t-1)s\rceil}}{t-1}\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|\bm{ Ah}\|_2+\gamma}{s-\sqrt{s}}\nonumber\\ &+\sqrt{1+\delta_{ts}}\|\bm{Ah}\|_{2}\bigg)\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2\leq 0. \end{align*} Therefore, using \eqref{RIPConditiona1add} we derive that \begin{align}\label{Estimate.hmax(s).eq1} &\|\bm{D}_{S}^{\top}\bm{h}\|_2\leq\|\bm{D}_{\tilde{S}}^{\top}\bm{h}\|_2\nonumber\\ &\leq\frac{\theta_{ts,(t-1)s}}{(1-\rho_{s,t})}\frac{\sqrt{2}+1}{\sqrt{2}}\frac{\sqrt{\lceil(t-1)s\rceil}}{(t-1)(s-\sqrt{s})} \left(c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\gamma\right)\nonumber\\ &+\bigg(\frac{\theta_{ts,(t-1)s}}{(1-\rho_{s,t})}\frac{\sqrt{2}+1}{\sqrt{2}}\frac{ \sqrt{\lceil(t-1)s\rceil}}{(t-1)(s-\sqrt{s})} +\frac{\sqrt{1+\delta_{ts}}}{1-\rho_{s,t}}\bigg)\eta\|\bm{Ah}\|_{2}, \end{align} where $\eta\geq 1$. $(\bm{iv})$ As shown in the proof of $(iii)$, we can prove the item (iv) by item (i) and \eqref{RIPCondition1}. We here omit the detail proof. $(\bm{v})$ The idea of the proof is the argument in \cite[ Step 2]{ge2021new}. By \eqref{lem:CrossItem.eq1} and the fact that $\|\bm{D}_{S^c}^{\top}\bm{h}\|_{\infty}\leq \|\bm{D}_{S}^{\top}\bm{h}\|_{1}/s\leq\|\bm{D}_{S}^{\top}\bm{h}\|_{2}/\sqrt{s}$, we have \begin{align*} &\|\bm{D}_{S^c}^{\top}\bm{h}\|_2^2 \leq \|\bm{D}_{S^c}^{\top}\bm{h}\|_{1}\|\bm{D}_{S^c}^{\top}\bm{h}\|_{\infty}\nonumber\\ &\leq\big(a\|\bm{D}_{S}^{\top}\bm{h}\|_1+b\|\bm{D}_{S}^{\top}\bm{h}\|_2+c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm {Ah}}\|_2+\gamma+\alpha\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\big) \frac{\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}}\nonumber\\ &\leq\frac{\alpha\|\bm{D}_{S}^{\top}\bm{h}\|_2}{\sqrt{s}}\|\bm{D}_{S^c}^{\top}\bm{h}\|_2+\frac{a\sqrt{s}+b}{\sqrt{s}}\|\bm{D}_{S}^{\top}\bm{h}\|_2^2+\frac{c\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\eta\|{\bm {Ah}}\|_2+\gamma}{\sqrt{s}}\|\bm{D}_{S}^{\top}\bm{h}\|_2 . \end{align*} That is, \begin{align*} &\bigg(\|\bm{D}_{S^c}^{\top}\bm{h}\|_2-\frac{\alpha\|\bm{D}_{S}^{\top}\bm{h}\|_2}{2\sqrt{s}}\bigg)^2\\ &\leq\bigg(\frac{\alpha^2}{4s}+\frac{a\sqrt{s}+b}{\sqrt{s}}\bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2^2 +\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm {Ah}}\|_2+\gamma}{\sqrt{s}}\|\bm{D}_{S}^{\top}\bm{h}\|_2. \end{align*} Then, we obtain \begin{align}\label{e:anotherupperbound} &\|\bm{D}_{S^c}^{\top}\bm{h}\|_2\nonumber\\ &\leq \Bigg(\sqrt{\frac{a\sqrt{s}+b}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha}{2\sqrt{s}}\Bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2 +\sqrt{\frac{c\|\bm{D}_{T^c}^{\top}\bm{x}\|_1+\eta\|{\bm {Ah}}\|_2+\gamma}{\sqrt{s}}\|\bm{D}_{S}^{\top}\bm{h}\|_2}\nonumber\\ &\leq\Bigg(\sqrt{\frac{a\sqrt{s}+b}{\sqrt{s}}+\frac{\alpha^2}{4s}}+\frac{\alpha+\bar{\varepsilon}}{2\sqrt{s}}\Bigg)\|\bm{D}_{S}^{\top}\bm{h}\|_2 +\frac{1}{2\bar{\varepsilon}}\big(c\|\bm{D}_{T^c}^{\top }\bm{x}\|_1+\eta\|\bm{Ah}\|_2+\gamma\big), \end{align} where the second inequality comes from the basic inequality $\sqrt{|a||b|}\leq \frac{|a|+|b|}{2}$, and the constant $\bar{\varepsilon}>0$. \end{proof} \end{appendices} \section*{Acknowledgments} The project is partially supported by the Natural Science Foundation of China (Nos. 11901037, 72071018), NSFC of Gansu Province, China (Grant No. 21JR7RA511), the NSAF (Grant No. U1830107) and the Science Challenge Project (TZ2018001). Authors thanks Professors Xiaobo Qu for making the pFISTA code available online. \hskip\parindent \bibliographystyle{plain}
{'timestamp': '2021-12-30T02:25:42', 'yymm': '2112', 'arxiv_id': '2112.14510', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14510'}
arxiv
\section{Introduction} Image classification is a long-standing yet important task with a wide range of applications such as autonomous driving, industrial automation, medical diagnosis, and biometric identification~\cite{autonomous_driving, industrial_automation, medical_diagnosis, biometric_identification}. In solving the task, supervised learning (SL) techniques have been popularly used for its superiority~\cite{VGG, ResNet}. Well-known drawback of SL is that a large number of training data are required for each and every class to be identified. Unfortunately, in many practical scenarios, it is difficult to collect training data for certain classes (e.g., endangered species and newly observed species such as variants of COVID-19). When there are \textit{unseen} classes where training data is unavailable, SL-based models are biased towards the \textit{seen} classes, impeding the identification of the unseen classes. Recently, to overcome this drawback, a technique to train a classifier using manually annotated attributes (e.g., color, size, and shape; see Fig.~\ref{fig:CUB}) has been proposed~\cite{zsl_proposal, gzsl_intro}. Key idea of this technique, dubbed as generalized zero-shot learning (GZSL), is to learn the relationship between the image and the attribute from seen classes and then use the trained model in the identification of unseen classes. In~\cite{ALE}, for example, an approach to identify unseen classes by measuring the compatibility between the image feature and attribute has been proposed. In~\cite{CVAE-GZSL}, a network synthesizing the image feature from the attribute has been employed to generate training data of unseen classes. In extracting the image feature, a network trained using the classification task (e.g., ResNet~\cite{ResNet}) has been popularly used. A potential drawback of this extraction method is that the image feature might contain attribute-irrelevant information (e.g., human fingers in Fig.~\ref{fig:CUB}), disturbing the process of learning the relationship between the image and the attribute~\cite{DLFZRL, RFF-GZSL, Disentangled-VAE}. \begin{figure}[!t] \centering \centerline{\includegraphics[width=1\linewidth]{CUB.png}} \caption{Images and attributes for different bird species sampled from the CUB dataset~\cite{CUB}.} \label{fig:CUB} \end{figure} \begin{figure*}[!t] \centering \centerline{\includegraphics[width=15cm]{autoencoder.eps}} \caption{Illustration of the image feature decomposition.} \label{fig:SD} \end{figure*} In this paper, we propose a new GZSL technique that removes the interference caused by the attribute-irrelevant information. Key idea of the proposed approach is to extract the \textit{semantic feature}, feature containing the attribute-related information, from the image feature and then use it in learning the relationship between the image and the attribute. In extracting the semantic feature, we use a modified autoencoder consisting of two encoders, viz., \textit{semantic} and \textit{residual} encoders (see Fig.~\ref{fig:SD}). In a nutshell, the semantic encoder captures all the attribute-related information in the image feature and the residual encoder catches the attribute-irrelevant information. In the conventional autoencoder, only reconstruction loss (difference between the input and the reconstructed input) is used for the training. In our approach, to encourage the semantic encoder to capture the attribute-related information only, we use two novel loss functions on top of the reconstruction loss. First, we employ the mutual information (MI)-based loss to maximize (minimize) MI between the semantic (residual) encoder output and the attribute. Since MI is a metric to measure the level of dependency between two random variables, by exploiting the MI-based loss, we can encourage the semantic encoder to capture the attribute-related information and at the same time discourage the residual encoder to capture any attribute-related information. As a result, all the attribute-related information can be solely captured by the semantic encoder. Second, we use the similarity-based loss to enforce the semantic encoder not to catch any attribute-irrelevant information. For example, when a bird image contains human fingers (see Fig.~\ref{fig:CUB}), we do not want features related to the finger to be included in the semantic encoder output. To do so, we maximize the similarity between the semantic encoder outputs of images that are belonging to the same class (bird images in our example). Since attribute-irrelevant features are contained only in a few image samples (e.g., human fingers are included in a few bird images), by maximizing the similarity between the semantic encoder outputs of the same class, we can remove attribute-irrelevant information from the semantic encoder output. From extensive experiments using various benchmark datasets (AwA1, AwA2, CUB, and SUN), we demonstrate that the proposed approach outperforms the conventional GZSL techniques by a large margin. For example, for the AwA2 and CUB datasets, our model achieves 2\% improvement in the GZSL classification accuracy over the state-of-the-art techniques. \section{Related Work and Background} \subsection{Conventional GZSL Approaches} The main task in GZSL is to learn the relationship between the image and the attribute from seen classes and then use it in the identification of unseen classes. Early GZSL works have focused on the training of a network measuring the compatibility score between the image feature and the attribute~\cite{ALE, DeViSE}. Once the network is trained properly, images can be classified by identifying the attribute achieving the maximum compatibility score. Recently, generative model-based GZSL approaches have been proposed~\cite{CVAE-GZSL, CLSWGAN}. Key idea of these approaches is to generate synthetic image features of unseen classes from the attributes by employing a generative model~\cite{CVAE-GZSL, CLSWGAN}. As a generative model, conditional variational autoencoder (CVAE)~\cite{vae} and conditional Wasserstein generative adversarial network (CWGAN)~\cite{WGAN} have been popularly used. By exploiting the generated image features of unseen classes as training data, a classification network identifying unseen classes can be trained in a supervised manner. Over the years, many efforts have been made to improve the performance of the generative model. In~\cite{f-vaegan-d2, CADA-VAE, Zero-VAE-GAN}, an approach to combine multiple generative models (e.g., CVAE and CWGAN) has been proposed. In~\cite{cycle-WGAN, DASCN}, an additional network estimating the image attribute from the image feature has been used to make sure that the synthetic image features satisfy the attribute of unseen classes. In~\cite{CLSWGAN, LsrGAN, LisGAN}, an additional image classifier has been used in the generative model training to generate distinct image features for different classes. Our approach is conceptually similar to the generative model-based approach in the sense that we generate synthetic image features of unseen classes using the generative model. The key distinctive point of the proposed approach over the conventional approaches is that we use the features containing only attribute-related information in the classification to remove the interference, if any, caused by the attribute-irrelevant information. \subsection{MI for Deep Learning} Mathematically, the MI $I(\mathbf{u}, \mathbf{v})$ between two random variables $\mathbf{u}$ and $\mathbf{v}$ is defined as \begin{align} I(\mathbf{u}, \mathbf{v}) &= \mathbb{E}_{p(\mathbf{u}, \mathbf{v})} \left [ \log \frac{p(\mathbf{u}, \mathbf{v})}{p(\mathbf{u}) p(\mathbf{v})} \right ] \nonumber \\ &= \int_{\mathbf{u}} \int_{\mathbf{v}} p(\mathbf{u}, \mathbf{v}) \log \frac{p(\mathbf{u}, \mathbf{v})}{p(\mathbf{u}) p(\mathbf{v})} d \mathbf{u} d \mathbf{v}, \label{eq:MI_definition} \end{align} where $p(\mathbf{u}, \mathbf{v})$ is the joint probability density function (PDF) of $\mathbf{u}$ and $\mathbf{v}$, and $p(\mathbf{u})$ and $p(\mathbf{v})$ are marginal PDFs of $\mathbf{u}$ and $\mathbf{v}$, respectively. In practice, it is very difficult to compute the exact value of MI since the joint PDF $p(\mathbf{u}, \mathbf{v})$ is generally unknown and the integrals in~\eqref{eq:MI_definition} are often intractable. To approximate MI, various MI estimators have been proposed~\cite{InfoNCE, CLUB}. Representative estimators include InfoNCE~\cite{InfoNCE} and contrastive log-ratio upper bound (CLUB)~\cite{CLUB}, defined as \begin{align} I_{\text{InfoNCE}}(\mathbf{u}, \mathbf{v}) &= \mathbb{E}_{p(\mathbf{u}, \mathbf{v})} [ f(\mathbf{u}, \mathbf{v}) ] \hspace{-.5mm} \nonumber \\ &~~~- \hspace{-.5mm} \mathbb{E}_{p(\mathbf{u})} \hspace{-1mm} \left [ \log \left ( \mathbb{E}_{p(\mathbf{v})} [ \exp ( f(\mathbf{u}, \mathbf{v} ) ) ] \right ) \right ], \label{eq:MI_lower bound_InfoNCE} \\ I_{\text{CLUB}}(\mathbf{u}, \mathbf{v}) &= \mathbb{E}_{p(\mathbf{u}, \mathbf{v})} \hspace{-1mm} \left [ \log p(\mathbf{v} | \mathbf{u} ) \right ] \hspace{-.5mm} - \hspace{-.5mm} \mathbb{E}_{p(\mathbf{u})p(\mathbf{v})} \hspace{-1mm} \left [ \log p(\mathbf{v} | \mathbf{u} ) \right ], \label{eq:MI_upper bound_CLUB} \end{align} where $f$ is a pre-defined score function measuring the compatibility between $\mathbf{u}$ and $\mathbf{v}$, and $p(\mathbf{v} | \mathbf{u})$ is the conditional PDF of $\mathbf{v}$ given $\mathbf{u}$, which is often approximated by a neural network. The relationship between MI, InfoNCE, and CLUB is given by \begin{align} I_{\text{InfoNCE}}(\mathbf{u}, \mathbf{v}) \le I(\mathbf{u}, \mathbf{v}) \le I_{\text{CLUB}}(\mathbf{u}, \mathbf{v}). \label{eq:MI inequality} \end{align} Recently, InfoNCE and CLUB have been used to strengthen or weaken the independence between different parts of the neural network. For example, when one tries to enforce the independence between $\mathbf{u}$ and $\mathbf{v}$, that is, to reduce $I(\mathbf{u}, \mathbf{v})$, an approach to minimize the upper bound $I_{\text{CLUB}}(\mathbf{u}, \mathbf{v})$ of MI can be used~\cite{MI_minimization}. Whereas, when one wants to maximize the dependence between $\mathbf{u}$ and $\mathbf{v}$, that is, to increase $I(\mathbf{u}, \mathbf{v})$, an approach to maximize the lower bound $I_{\text{InfoNCE}}(\mathbf{u}, \mathbf{v})$ of MI~\cite{MI_maximization} can be used. \section{SE-GZSL} In this section, we present the proposed GZSL technique called semantic feature extraction-based GZSL (SE-GZSL). We first discuss how to extract the semantic feature from the image feature and then delve into the GZSL classification using the extracted semantic feature. \subsection{Semantic Feature Extraction} In extracting the semantic feature from the image feature, the proposed SE-GZSL technique uses the modified autoencoder architecture where two encoders, called semantic and residual encoders, are used in capturing the attribute-related information and the attribute-irrelevant information, respectively (see Fig~\ref{fig:SD}). As mentioned, in the autoencoder training, we use two loss functions: 1) MI-based loss to encourage the semantic encoder to capture all attribute-related information and 2) similarity-based loss to encourage the semantic encoder not to capture attribute-irrelevant information. In this subsection, we discuss the overall training loss with emphasis on these two. \paragraph{MI-based Loss} To make sure that all the attribute-related information is contained in the semantic encoder output, we use MI in the autoencoder training. To do so, we maximize MI between the semantic encoder output and the attribute which is given by manual annotation. At the same time, to avoid capturing of attribute-related information in the residual encoder, we minimize MI between the residual encoder output and the attribute. Let $\mathbf{z}_{s}$ and $\mathbf{z}_{r}$ be the semantic and residual encoder outputs corresponding to the image feature $\mathbf{x}$, and $\mathbf{a}$ be the image attribute (see Fig.~\ref{fig:SD}). Then, our training objective can be expressed as \begin{align} \text{minimize}~~~-\lambda_{s} I(\mathbf{z}_{s}, \mathbf{a}) + \lambda_{r} I(\mathbf{z}_{r}, \mathbf{a}), \label{eq:separation loss_MI form} \end{align} where $\lambda_{s}$ and $\lambda_{r}$ ($\lambda_{s}, \lambda_{r} > 0$) are weighting coefficients. Since the computation of MI is not tractable, we use InfoNCE and CLUB (see~\eqref{eq:MI_lower bound_InfoNCE} and~\eqref{eq:MI_upper bound_CLUB}) as a surrogate of MI. In our approach, to minimize the objective function in~\eqref{eq:separation loss_MI form}, we express its upper bound using InfoNCE and CLUB and then train the autoencoder in a way to minimize the upper bound. Using the relationship between MI and its estimators in~\eqref{eq:MI inequality}, the upper bound $\mathcal{L}_{\text{MI}}$ of the objective function in~\eqref{eq:separation loss_MI form} is \begin{align} \mathcal{L}_{\text{MI}} &= -\lambda_{s} I_{\text{InfoNCE}}(\mathbf{z}_{s}, \mathbf{a}) + \lambda_{r} I_{\text{CLUB}} (\mathbf{z}_{r}, \mathbf{a}) \nonumber \\ &= -\lambda_{s} \mathbb{E}_{p(\mathbf{z}_{s}, \mathbf{a})} [ f(\mathbf{z}_{s}, \mathbf{a}) ] \nonumber \\ &~~~ + \hspace{-.5mm} \lambda_{s} \mathbb{E}_{p(\mathbf{z}_{s})} \hspace{-1mm} \left [ \log \left ( \mathbb{E}_{p(\mathbf{a})} [ \exp ( f(\mathbf{z}_{s}, \mathbf{a}) ) ] \right ) \right ] \nonumber \\ &~~~ +\lambda_{r} \left ( \mathbb{E}_{p(\mathbf{z}_{r}, \mathbf{a})} \hspace{-1mm} \left [ \log p(\mathbf{a} | \mathbf{z}_{r} ) \right ] \hspace{-.5mm} - \hspace{-.5mm} \mathbb{E}_{p(\mathbf{z}_{r})p(\mathbf{a})} \hspace{-1mm} \left [ \log p(\mathbf{a} | \mathbf{z}_{r} ) \right ] \right ) \hspace{-1mm}. \label{eq:separation loss_expectation form} \end{align} Let $\mathcal{Y}_{s}$ be the set of seen classes, $\mathbf{a}_{c}$ be the attribute of a seen class $c \in \mathcal{Y}_{s}$, and $\{ \mathbf{x}_{c}^{(i)} \}_{i=1}^{N_{c}}$ be the set of training image features for the class $c$. Further, let $\mathbf{z}_{c, s}^{(i)}$ and $\mathbf{z}_{c, r}^{(i)}$ be the semantic and residual encoder outputs corresponding to the input image feature $\mathbf{x}_{c}^{(i)}$, respectively, then $\mathcal{L}_{\text{MI}}$ can be expressed as \begin{align} \mathcal{L}_{\text{MI}} &= -\frac{\lambda_{s}}{N} \sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \log \frac{\exp ( f ( \mathbf{z}_{c, s}^{(i)}, \mathbf{a}_{c} ) )} {\frac{1}{|\mathcal{Y}_{s}|} \hspace{-.5mm} \underset{c^{\prime} \in \mathcal{Y}_{s}}{\sum} \exp ( f ( \mathbf{z}_{c, s}^{(i)}, \mathbf{a}_{c^{\prime}} ) )} \nonumber \\ &~+\frac{\lambda_{r}}{N} \hspace{-.5mm} \sum_{c \in \mathcal{Y}_{s}} \hspace{-.5mm} \sum_{i=1}^{N_{c}} \hspace{-.5mm} \left ( \log p(\mathbf{a}_{c} | \mathbf{z}_{c, r}^{(i)}) - \hspace{-2mm} \underset{c^{\prime} \in \mathcal{Y}_{s}}{\sum} \hspace{-.5mm} \frac{\log p(\mathbf{a}_{c^{\prime}} | \mathbf{z}_{c, r}^{(i)})}{|\mathcal{Y}_{s}|} \hspace{-.5mm} \right ) \hspace{-1mm}, \label{eq:separation loss} \end{align} where $N = \sum_{c \in \mathcal{Y}_{s}} N_{c}$ is the total number of training image features. \paragraph{Similarity-based Loss} We now discuss the similarity-based loss to enforce the semantic encoder not to capture any attribute-irrelevant information. Since images belonging to the same class have the same attribute, attribute-related image features of the same class would be more or less similar. This means that if the semantic encoder captures attribute-related information only, then the similarity between semantic encoder outputs of the same class should be large. Inspired by this observation, to remove the attribute-irrelevant information from the semantic encoder output, we train the semantic encoder in a way to maximize the similarity between outputs of the same class: \begin{align} \text{maximize}~~~\sum_{j=1}^{N_{c}} \exp (\operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c, s}^{(j)} ) ), \label{eq:similarity loss_same class} \end{align} where the similarity is measured using the cosine-similarity function defined as \begin{align*} \operatornamewithlimits{sim}(\mathbf{u}, \mathbf{v}) &= \frac{\langle \mathbf{u}, \mathbf{v} \rangle} {\| \mathbf{u} \|_{2} \| \mathbf{v} \|_{2}}. \end{align*} Also, we minimize the similarity between semantic encoder outputs of different classes to obtain sufficiently distinct semantic encoder outputs for different classes: \begin{align} \text{minimize}~~~\sum_{c^{\prime} \neq c} \sum_{j=1}^{N_{c^{\prime}}} \exp ( \operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c^{\prime}, s}^{(j)} ) ). \label{eq:similarity loss_different classes} \end{align} Using the fact that one can maximize $A$ and minimize $B$ at the same time by minimizing $-\log \frac{1}{1+B/A} = -\log \frac{A}{A+B}$, we obtain the similarity-based loss as \begin{align} \mathcal{L}_{\text{sim}} &= -\frac{1}{N} \sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \log \frac{\underset{j=1}{\overset{N_{c}}{\sum}} \exp \hspace{-.7mm} \left ( \hspace{-.5mm} \operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c, s}^{(j)} ) \hspace{-.5mm} \right )} { \underset{c^{\prime} \in \mathcal{Y}_{s}}{\sum} \underset{j=1}{\overset{N_{c^{\prime}}}{\sum}} \exp \hspace{-.7mm} \left ( \hspace{-.5mm} \operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c^{\prime}, s}^{(j)} ) \hspace{-.5mm} \right ) }. \label{eq:similarity loss} \end{align} \subsubsection{Overall Loss} By adding the conventional reconstruction loss $\mathcal{L}_{\text{recon}}$ for the autoencoder, the MI-based loss $\mathcal{L}_{\text{MI}}$, and the similarity-based loss $\mathcal{L}_{\text{sim}}$, we obtain the overall loss function as \begin{align} \mathcal{L}_{\text{total}} &= \mathcal{L}_{\text{recon}} + \mathcal{L}_{\text{MI}} + \lambda_{\text{sim}} \mathcal{L}_{\text{sim}}, \label{eq:decomposition loss} \end{align} where $\lambda_{\text{sim}}$ is a weighting coefficient and $\mathcal{L}_{\text{recon}}$ is the reconstruction loss given by \begin{align} \mathcal{L}_{\text{recon}} &= \frac{1}{N} \sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \| \mathbf{x}_{c}^{(i)} - \widehat{\mathbf{x}}_{c}^{(i)} \|_{2}. \end{align} Here, $\widehat{\mathbf{x}}_{c}^{(i)}$ is the image feature reconstructed using the semantic and residual encoder outputs ($\mathbf{z}_{c, s}^{(i)}$ and $\mathbf{z}_{c, r}^{(i)}$) in the decoder. When the training is finished, we only use the semantic encoder for the purpose of extracting the semantic feature. \subsection{GZSL Classification Using Semantic Features} So far, we have discussed how to extract the semantic feature from the image feature. We now discuss how to perform the GZSL classification using the semantic feature. In a nutshell, we synthesize semantic feature samples for unseen classes from their attributes. Once the synthetic samples are generated, the semantic classifier identifying unseen classes from the semantic feature is trained in a supervised manner. \paragraph{Semantic Feature Generation} \begin{figure*}[h] \centering \centerline{\includegraphics[width=13cm]{generator.eps}} \caption{Illustration of the synthetic semantic feature generation for unseen classes.} \label{fig:generator} \end{figure*} To synthesize the semantic feature samples for unseen classes, we first generate image features from the attributes of unseen classes and then extract the semantic features from the synthetic image features using the semantic encoder (see Fig.~\ref{fig:generator}). In synthesizing the image feature, we employ WGAN that mitigates the unstable training issue of GAN by exploiting a Wasserstein distance-based loss function~\cite{WGAN}. The main component in WGAN is a generator $G$ synthesizing the image feature $\widetilde{\mathbf{x}}_{c}$ from a random noise vector $\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})$ and the image attribute $\mathbf{a}_{c}$ (i.e., $\widetilde{\mathbf{x}}_{c} = G(\boldsymbol{\epsilon}, \mathbf{a}_{c})$). Conventionally, WGAN is trained to minimize the Wasserstein distance between the distributions of real image feature $\mathbf{x}_{c}$ and generated image feature $\widetilde{\mathbf{x}}_{c}$ given by \begin{align} \lefteqn{\hspace{-.2cm} \mathcal{L}_{G, \text{WGAN}}} \nonumber \\ &\hspace{-.3cm}= \max_{D} \hspace{-.5mm} \bigg ( \mathbb{E}_{p(\mathbf{x}_{c} | \mathbf{a}_{c})} [ D(\mathbf{x}_{c}, \mathbf{a}_{c}) ] - \mathbb{E}_{p(\widetilde{\mathbf{x}}_{c} | \mathbf{a}_{c})} [ D(\widetilde{\mathbf{x}}_{c}, \mathbf{a}_{c}) ] \nonumber \\ &\hspace{-.3cm}~~~~~~~~~~~~~~ -\lambda_{\text{gp}} \mathbb{E}_{p(\widehat{\mathbf{x}}_{c} | \mathbf{a}_{c})} \hspace{-.8mm} \left [ \left ( \| \nabla_{\widehat{\mathbf{x}}_{c}} D(\widehat{\mathbf{x}}_{c}, \mathbf{a}_{c}) \|_{2} - 1 \right )^{2} \right ] \hspace{-.8mm} \bigg ), \label{eq:generator_WGAN loss} \end{align} where $D$ is an auxiliary network (called critic), $\widehat{\mathbf{x}}_{c} = \alpha \mathbf{x}_{c} + (1 - \alpha) \widetilde{\mathbf{x}}_{c}~(\alpha \sim \mathcal{U}(0, 1))$, and $\lambda_{\text{gp}}$ is the regularization coefficient (a.k.a., gradient penalty coefficient)~\cite{WGAN-GP}. In our scheme, to make sure that the semantic feature $\widetilde{\mathbf{z}}_{c, s}$ obtained from $\widetilde{\mathbf{x}}_{c}$ is similar to the real semantic feature $\mathbf{z}_{c, s}$, we additionally use the following losses in the WGAN training: \begin{align} \mathcal{L}_{G, \text{MI}} &= -I_{\text{InfoNCE}}(\widetilde{\mathbf{z}}_{c, s}, \mathbf{a}_{c}), \label{eq:generator_InfoNCE loss} \\ \mathcal{L}_{G, \text{sim}} &= -\mathbb{E}_{p(\widetilde{\mathbf{z}}_{c, s})} \hspace{-1mm} \left [ \log \frac{\underset{i=1}{\overset{N_{c}}{\sum}} \exp ( \operatornamewithlimits{sim} (\widetilde{\mathbf{z}}_{c, s}, \mathbf{z}_{c, s}^{(i)}) )} {\underset{c^{\prime}=1}{\overset{S}{\sum}} \underset{i=1}{\overset{N_{c^{\prime}}}{\sum}} \exp ( \operatornamewithlimits{sim} (\widetilde{\mathbf{z}}_{c, s}, \mathbf{z}_{c^{\prime}, s}^{(i)}) )} \right ]. \label{eq:generator_similarity loss} \end{align} We note that these losses are analogous to the losses with respect to the real semantic feature $\mathbf{z}_{c, s}$ in~\eqref{eq:separation loss_expectation form} and~\eqref{eq:similarity loss}, respectively. By combining~\eqref{eq:generator_WGAN loss},~\eqref{eq:generator_InfoNCE loss}, and~\eqref{eq:generator_similarity loss}, we obtain the overall loss function as \begin{align} \mathcal{L}_{G} &= \mathcal{L}_{G, \text{WGAN}} + \lambda_{G, \text{MI}} \mathcal{L}_{G, \text{MI}} + \lambda_{G, \text{sim}} \mathcal{L}_{G, \text{sim}}, \label{eq:generator loss} \end{align} where $\lambda_{G, \text{MI}}$ and $\lambda_{G, \text{sim}}$ are weighting coefficients. After the WGAN training, we use the generator $G$ and the semantic encoder $E_{s}$ in synthesizing semantic feature samples of unseen classes. Specifically, for each unseen class $u \in \mathcal{Y}_{u}$, we generate the semantic feature $\widetilde{\mathbf{z}}_{u, s}$ by synthesizing the image feature $\widetilde{\mathbf{x}}_{u} = G(\boldsymbol{\epsilon}, \mathbf{a}_{u})$ using the generator and then exploiting it as an input to the semantic encoder (see Fig.~\ref{fig:generator}): \begin{align} \widetilde{\mathbf{z}}_{u, s} = E_{s}(\widetilde{\mathbf{x}}_{u}) = E_{s}(G(\boldsymbol{\epsilon}, \mathbf{a}_{u})). \end{align} By resampling the noise vector $\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})$, a sufficient number of synthetic semantic features can be generated. \paragraph{Semantic Feature-based Classification} After generating synthetic semantic feature samples for all unseen classes, we train the semantic feature classifier using a supervised learning model (e.g., softmax classifier, support vector machine, and nearest neighbor). Suppose, for example, that the softmax classifier is used as a classification model. Let $\{ \widetilde{\mathbf{z}}_{u, s}^{(i)} \}_{i=1}^{N_{u}}$ be the set of synthetic semantic feature samples for the unseen class $u$, then the semantic feature classifier is trained to minimize the cross entropy loss\footnote{We recall that $\{ \mathbf{z}_{c, s}^{(i)} \}_{i=1}^{N_{c}}$ is the set of semantic features for the seen class $c \in \mathcal{Y}_{s}$.} \begin{align} \mathcal{L}_{\text{CE}} &= -\sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \log P( c | \mathbf{z}_{c, s}^{(i)} ) - \sum_{u \in \mathcal{Y}_{u}} \sum_{i=1}^{N_{u}} \log P( u | \widetilde{\mathbf{z}}_{u, s}^{(i)} ), \end{align} where \begin{align} P(y|\mathbf{z}) &= \frac{\exp (\mathbf{w}_{y}^{T} \mathbf{z} + b_{y})}{ \sum_{y^{\prime} \in \mathcal{Y}_{s} \cup \mathcal{Y}_{u}} \exp (\mathbf{w}_{y^{\prime}}^{T} \mathbf{z} + b_{y^{\prime}})} \end{align} and $\mathbf{w}_{y}$ and $b_{y}$ are weight and bias parameters of the softmax classifier to be learned. \subsection{Comparison with Conventional Approaches} There have been previous efforts to extract the semantic feature from the image feature~\cite{DLFZRL, RFF-GZSL, Disentangled-VAE, SDGZSL}. While our approach seems to be a bit similar to~\cite{Disentangled-VAE} and~\cite{SDGZSL} in the sense that the autoencoder-based image feature decomposition method is used for the semantic feature extraction, our work is dearly distinct from those works in two respects. First, we use different training strategy in capturing the attribute-related information. In our approach, to make sure that the semantic encoder output contains all the attribute-related information, we use two complementary loss terms: 1) the loss term to encourage the semantic encoder to capture the attribute-related information and 2) the loss term to discourage the residual encoder to capture any attribute-related information (see~\eqref{eq:separation loss_MI form}). Whereas, the training loss used to remove the attribute-related information from the residual encoder output has not been used in~\cite{Disentangled-VAE, SDGZSL}. Also, we employ a new training loss $\mathcal{L}_{\text{sim}}$ to remove the attribute-irrelevant information from the semantic encoder output (see~\eqref{eq:similarity loss}), for which there is no counterpart in~\cite{Disentangled-VAE, SDGZSL}. \section{Experiments} \begin{table}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c | c | c | c } \toprule Classifier input & AwA1 & AwA2 & CUB & SUN \\ \midrule Image feature & 90.9 & 92.8 & 73.8 & 47.1 \\ Semantic feature & \textbf{91.9} & \textbf{93.4} & \textbf{76.1} & \textbf{49.3} \\ \bottomrule \end{tabular} }} \caption{Top-1 accuracy of image feature-based and semantic feature-based image classifiers.} \label{tab:result_effect of attribute-related feature extraction} \end{table} \begin{figure*}[!t] \begin{minipage}[b]{0.33 \linewidth} \centering \centerline{\includegraphics[width=6cm]{tsne_semantic.png}} \centerline{(a) Semantic features} \end{minipage} \hfill \begin{minipage}[b]{0.33 \linewidth} \centering \centerline{\includegraphics[width=6cm]{tsne_visual.png}} \centerline{(b) Image features} \end{minipage} \hfill \begin{minipage}[b]{0.33 \linewidth} \centering \centerline{\includegraphics[width=6cm]{tsne_residual.png}} \centerline{(c) Residual features} \end{minipage} \caption{t-SNE visualization of (a) semantic features, (b) image features, and (c) residual features. Samples for the same class are indicated in the same color.} \label{fig:t-SNE} \end{figure*} \begin{table*}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c | c c c | c c c | c c c | c c c} \toprule \multirow{2}{2.2cm}{\centering Method} & \multirow{2}{2.2cm}{\centering Feature Type} & \multicolumn{3}{c|}{AwA1} & \multicolumn{3}{c|}{AwA2} & \multicolumn{3}{c|}{CUB} & \multicolumn{3}{c}{SUN} \\ \cline{3-14} & & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ \\ \toprule CVAE-GZSL & \multirow{9}{2.2cm}{\centering ResNet} & - & - & 47.2 & - & - & 51.2 & - & - & 34.5 & - & - & 26.7 \\ f-CLSWGAN & & 61.4 & 57.9 & 59.6 & - & - & - & 57.7 & 43.7 & 49.7 & 36.6 & 42.6 & 39.4 \\ cycle-CLSWGAN & & 64.0 & 56.9 & 60.2 & - & - & - & 61.0 & 45.7 & 52.3 & 33.6 & 49.4 & 40.0 \\ f-VAEGAN-D2 & & - & - & - & 70.6 & 57.6 & 63.5 & 60.1 & 48.4 & 53.6 & 38.0 & 45.1 & 41.3 \\ LisGAN & & 76.3 & 52.6 & 62.3 & - & - & - & 57.9 & 46.5 & 51.6 & 37.8 & 42.9 & 40.2 \\ CADA-VAE & & 72.8 & 57.3 & 64.1 & 75.0 & 55.8 & 63.9 & 53.5 & 51.6 & 52.4 & 35.7 & 47.2 & 40.6 \\ DASCN & & 68.0 & 59.3 & 63.4 & - & - & - & 59.0 & 45.9 & 51.6 & 38.5 & 42.4 & 40.3 \\ LsrGAN & & 74.6 & 54.6 & 63.0 & - & - & - & 59.1 & 48.1 & 53.0 & 37.7 & 44.8 & 40.9 \\ Zero-VAE-GAN & & 66.8 & 58.2 & 62.3 & 70.9 & 57.1 & 62.5 & 47.9 & 43.6 & 45.5 & 30.2 & 45.2 & 36.3 \\ \midrule DLFZRL & \multirow{3}{2.2cm}{\centering Semantic} & - & - & 61.2 & - & - & 60.9 & - & - & 51.9 & - & - & {\underline{42.5}} \\ RFF-GZSL & & 75.1 & 59.8 & {\underline{66.5}} & - & - & - & 56.6 & 52.6 & {\underline{54.6}} & 38.6 & 45.7 & 41.9 \\ Disentangled-VAE & & 72.9 & 60.7 & 66.2 & 80.2 & 56.9 & {\underline{66.6}} & 58.2 & 51.1 & 54.4 & 36.6 & 47.6 & 41.4 \\ \midrule {\bf{SE-GZSL}} & Semantic & 76.7 & 61.3 & {\bf{68.1}} & 80.7 & 59.9 & {\bf{68.8}} & 60.3 & 53.1 & {\bf{56.4}} & 40.7 & 45.8 & {\bf{43.1}} \\ \bottomrule \end{tabular} }} \caption{GZSL classification performance of the proposed SE-GZSL technique and conventional approaches. `-' means that the result is not reported in the references. The best results are in bold, and the second best results are underlined.} \label{tab:result_GZSL performance} \end{table*} \begin{table*}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c c c | c c c | c c c | c c c} \toprule \multirow{2}{2.2cm}{\centering Loss}& \multicolumn{3}{c|}{AwA1} & \multicolumn{3}{c|}{AwA2} & \multicolumn{3}{c|}{CUB} & \multicolumn{3}{c}{SUN} \\ \cline{2-13} & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ \\ \toprule $\mathcal{L}_{\text{recon}}$ & 64.6 & 53.1 & 58.3 & 68.9 & 55.7 & 61.6 & 54.5 & 46.1 & 49.9 & 38.4 & 40.6 & 39.4 \\ $\mathcal{L}_{\text{recon}}$ + $\mathcal{L}_{\text{MI}}$ & 75.0 & 57.9 & 65.4 & 74.2 & 58.6 & 65.5 & 59.4 & 51.5 & 55.1 & 37.1 & 46.5 & 41.3 \\ $\mathcal{L}_{\text{recon}}$ + $\mathcal{L}_{\text{MI}}$ + $\mathcal{L}_{\text{sim}}$ & 76.7 & 61.3 & \textbf{68.1} & 80.7 & 59.9 & \textbf{68.8} & 60.3 & 53.1 & \textbf{56.4} & 40.7 & 45.8 & \textbf{43.1} \\ \bottomrule \end{tabular} }} \caption{Ablation study on the performance of SE-GZSL.} \label{tab:result_ablation study} \end{table*} \subsection{Experimental Setup} \paragraph{Datasets} In our experiments, we evaluate the performance of our model using four benchmark datasets: AwA1, AwA2, CUB, and SUN. The AwA1 and AwA2 datasets contain 50 classes of animal images annotated with 85 attributes~\cite{zsl_proposal, AwA2}. The CUB dataset contains 200 species of bird images annotated with 312 attributes~\cite{CUB}. The SUN dataset contains 717 classes of scene images annotated with 102 attributes~\cite{SUN}. In dividing the total classes into seen and unseen classes, we adopt the conventional dataset split presented in~\cite{AwA2}. \paragraph{Implementation Details} As in~\cite{CLSWGAN, CADA-VAE}, we use ResNet-101~\cite{ResNet} as a pre-trained classification network and fix it in our training process. We implement all the networks in SE-GZSL (semantic encoder, residual encoder, and decoder in the image feature decomposition network, and generator and critic in WGAN) using the multilayer perceptron (MLP) with one hidden layer as in~\cite{CLSWGAN, f-vaegan-d2}. We set the number of hidden units to 4096 and use LeakyReLU with a negative slope of 0.02 as a nonlinear activation function. For the output layer of the generator, the ReLU activation is used since the image feature extracted by ResNet is non-negative. As in~\cite{InfoNCE}, we define the score function $f$ in~\eqref{eq:separation loss_expectation form} as $f(\mathbf{z}_{s}, \mathbf{a}) = \mathbf{z}_{s}^{T} \mathbf{W} \mathbf{a}$ where $\mathbf{W}$ is a weight matrix to be learned. Also, as in~\cite{CLUB}, we approximate the conditional PDF $p(\mathbf{a} | \mathbf{z}_{r})$ in~\eqref{eq:separation loss_expectation form} using a variational encoder consisting of two hidden layers. The gradient penalty coefficient in the WGAN loss $\mathcal{L}_{G, \text{WGAN}}$ is set to $\lambda_{\text{gp}} = 10$ as suggested in the original WGAN paper~\cite{WGAN-GP}. We set the weighting coefficients in~\eqref{eq:separation loss}, ~\eqref{eq:decomposition loss}, and~\eqref{eq:generator loss} to $\lambda_{s}=20, \lambda_{r}=50, \lambda_{\text{sim}}=1, \lambda_{G, \text{MI}}=1, \lambda_{G, \text{sim}} = 0.025$. \subsection{Semantic Feature-based Image Classification} We first investigate whether the image classification performance can be improved by exploiting the semantic feature. To this end, we train two image classifiers: the classifier exploiting the image feature and the classifier utilizing the semantic feature extracted by the semantic encoder. To compare the semantic feature directly with the image feature, we use the simple softmax classifier as a classification model. In Table~\ref{tab:result_effect of attribute-related feature extraction}, we summarize the top-1 classification accuracy of each classifier on test image samples for seen classes. We observe that the semantic feature-based classifier outperforms the image feature-based classifier for all datasets. In particular, for the SUN and CUB datasets, the semantic feature-based classifier achieves about $2\%$ improvement in the top-1 classification accuracy over the image feature-based classifier, which demonstrates that the image classification performance can be enhanced by removing the attribute-irrelevant information in the image feature. \subsection{Visualization of Semantic Features} In Fig.~\ref{fig:t-SNE}, we visualize semantic feature samples obtained from the CUB dataset using a t-distributed stochastic neighbor embedding (t-SNE), a tool to visualize high-dimensional data in a two-dimensional plane~\cite{t-SNE}. For comparison, we also visualize image feature samples and residual feature samples extracted by the residual encoder. We observe that semantic feature samples containing only attribute-related information are well-clustered, that is, samples of the same class are grouped and samples of different classes are separated (see Fig.~\ref{fig:t-SNE}(a)). Whereas, image feature samples of different classes are not separated sufficiently (see Fig.~\ref{fig:t-SNE}(b)) and residual feature samples are scattered randomly (see Fig.~\ref{fig:t-SNE}(c)). \subsection{Comparison with State-of-the-art} We next evaluate the GZSL classification performance of the proposed approach using the standard evaluation protocol presented in~\cite{AwA2}. Specifically, we measure the average top-1 classification accuracies $acc_{s}$ and $acc_{u}$ on seen and unseen classes, respectively, and then use their harmonic mean $acc_{h}$ as a metric to evaluate the performance. In Table~\ref{tab:result_GZSL performance}, we summarize the performance of SE-GZSL on different datasets. For comparison, we also summarize the performance of conventional methods among which DLFZRL, RFF-GZSL, and Disentangled-VAE are semantic feature-based approaches~\cite{DLFZRL, RFF-GZSL, Disentangled-VAE} and other methods are image feature-based approaches~\cite{CVAE-GZSL, CLSWGAN, cycle-WGAN, f-vaegan-d2, LisGAN, CADA-VAE, DASCN, LsrGAN, Zero-VAE-GAN}. From the results, we observe that the proposed SE-GZSL outperforms conventional image feature-based approaches by a large margin. For example, for the AwA2 dataset, SE-GZSL achieves about 5\% improvement in the harmonic mean accuracy over image feature-based approaches. We also observe that SE-GZSL outperforms existing semantic feature-based approaches for all datasets. For example, for the AwA1, AwA2, and CUB datasets, our model achieves about 2\% improvement in the harmonic mean accuracy over the state-of-the-art approaches. \subsection{Ablation Study} \paragraph{Effectiveness of Loss Functions} In training the semantic feature extractor, we have used the MI-based loss $\mathcal{L}_{\text{MI}}$ and the similarity-based loss $\mathcal{L}_{\text{sim}}$. To examine the impact of each loss function, we measure the performance of three different versions of SE-GZSL: 1) SE-GZSL trained only with the reconstruction loss $\mathcal{L}_{\text{recon}}$, 2) SE-GZSL trained with $\mathcal{L}_{\text{recon}}$ and $\mathcal{L}_{\text{MI}}$, and 3) SE-GZSL trained with $\mathcal{L}_{\text{recon}}$, $\mathcal{L}_{\text{MI}}$, and $\mathcal{L}_{\text{sim}}$. From the results in Table~\ref{tab:result_ablation study}, we observe that the performance of SE-GZSL can be enhanced greatly by exploiting the MI-based loss $\mathcal{L}_{\text{MI}}$. In particular, for the AwA1 and CUB datasets, we achieve more than $5\%$ improvement in the harmonic mean accuracy by utilizing $\mathcal{L}_{\text{MI}}$. Also, for the AwA2 dataset, we achieve about $4\%$ improvement of the accuracy. One might notice that when $\mathcal{L}_{\text{MI}}$ is not used, SE-GZSL performs worse than conventional image feature-based methods (see Table~\ref{tab:result_GZSL performance}). This is because the semantic encoder cannot capture all the attribute-related information without $\mathcal{L}_{\text{MI}}$, and thus using the semantic encoder output in the classification incurs the loss of the attribute-related information. We also observe that the performance of SE-GZSL can be improved further by exploiting the similarity-based loss $\mathcal{L}_{\text{sim}}$. For example, for the AwA2 dataset, more than $3\%$ improvement in the harmonic mean accuracy can be achieved by utilizing $\mathcal{L}_{\text{sim}}$. \paragraph{Importance of Residual Encoder} \begin{table}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c | c | c | c} \toprule Method & AwA1 & AwA2 & CUB & SUN \\ \toprule SE-GZSL w/o residual encoder & 66.7 & 67.5 & 55.1 & 42.1 \\ \midrule SE-GZSL w/ residual encoder & {\bf{68.1}} & {\bf{68.8}} & {\bf{56.4}} & {\bf{43.1}} \\ \bottomrule \end{tabular} }} \caption{Harmonic mean accuracy of SE-GZSL with and without the residual encoder.} \label{tab:rebuttal_residual encoder} \end{table} For the semantic feature extraction, we have decomposed the image feature into the attribute-related feature and the attribute-irrelevant feature using the semantic and residual encoders. An astute reader might ask why the residual encoder is needed to extract the semantic feature. To answer this question, we measure the performance of SE-GZSL without using the residual encoder. From the results in Table~\ref{tab:rebuttal_residual encoder}, we can observe that the GZSL performance of SE-GZSL is degraded when the residual encoder is not used. This is because if the residual encoder is removed, then the attribute-irrelevant information, required for the reconstruction of the image feature, would be contained in the semantic encoder output and therefore mess up the process to learn the relationship between the image feature and the attribute. \section{Conclusion} In this paper, we presented a new GZSL technique called SE-GZSL. Key idea of the proposed SE-GZSL is to exploit the semantic feature in learning the relationship between the image and the attribute, removing the interference caused by the attribute-irrelevant information. To extract the semantic feature, we presented the autoencoder-based image feature decomposition network consisting of semantic and residual encoders. In a nutshell, the semantic and residual encoders capture the attribute-related information and the attribute-irrelevant information, respectively. In training the image feature decomposition network, we used MI-based loss to encourage the semantic encoder to capture all the attribute-related information and similarity-based loss to discourage the semantic encoder to capture any attribute-irrelevant information. Our experiments on various datasets demonstrated that the proposed SE-GZSL outperforms conventional GZSL approaches by a large margin. \section{Acknowledgements} This work was supported in part by the Samsung Research Funding \& Incubation Center for Future Technology of Samsung Electronics under Grant SRFC-IT1901-17 and in part by the National Research Foundation of Korea (NRF) grant funded by the Korea government (MSIT) under Grant 2020R1A2C2102198. {\small \section{Introduction} Image classification is a long-standing yet important task with a wide range of applications such as autonomous driving, industrial automation, medical diagnosis, and biometric identification~\cite{autonomous_driving, industrial_automation, medical_diagnosis, biometric_identification}. In solving the task, supervised learning (SL) techniques have been popularly used for its superiority~\cite{VGG, ResNet}. Well-known drawback of SL is that a large number of training data are required for each and every class to be identified. Unfortunately, in many practical scenarios, it is difficult to collect training data for certain classes (e.g., endangered species and newly observed species such as variants of COVID-19). When there are \textit{unseen} classes where training data is unavailable, SL-based models are biased towards the \textit{seen} classes, impeding the identification of the unseen classes. Recently, to overcome this drawback, a technique to train a classifier using manually annotated attributes (e.g., color, size, and shape; see Fig.~\ref{fig:CUB}) has been proposed~\cite{zsl_proposal, gzsl_intro}. Key idea of this technique, dubbed as generalized zero-shot learning (GZSL), is to learn the relationship between the image and the attribute from seen classes and then use the trained model in the identification of unseen classes. In~\cite{ALE}, for example, an approach to identify unseen classes by measuring the compatibility between the image feature and attribute has been proposed. In~\cite{CVAE-GZSL}, a network synthesizing the image feature from the attribute has been employed to generate training data of unseen classes. In extracting the image feature, a network trained using the classification task (e.g., ResNet~\cite{ResNet}) has been popularly used. A potential drawback of this extraction method is that the image feature might contain attribute-irrelevant information (e.g., human fingers in Fig.~\ref{fig:CUB}), disturbing the process of learning the relationship between the image and the attribute~\cite{DLFZRL, RFF-GZSL, Disentangled-VAE}. \begin{figure}[!t] \centering \centerline{\includegraphics[width=1\linewidth]{CUB.png}} \caption{Images and attributes for different bird species sampled from the CUB dataset~\cite{CUB}.} \label{fig:CUB} \end{figure} \begin{figure*}[!t] \centering \centerline{\includegraphics[width=15cm]{autoencoder.eps}} \caption{Illustration of the image feature decomposition.} \label{fig:SD} \end{figure*} In this paper, we propose a new GZSL technique that removes the interference caused by the attribute-irrelevant information. Key idea of the proposed approach is to extract the \textit{semantic feature}, feature containing the attribute-related information, from the image feature and then use it in learning the relationship between the image and the attribute. In extracting the semantic feature, we use a modified autoencoder consisting of two encoders, viz., \textit{semantic} and \textit{residual} encoders (see Fig.~\ref{fig:SD}). In a nutshell, the semantic encoder captures all the attribute-related information in the image feature and the residual encoder catches the attribute-irrelevant information. In the conventional autoencoder, only reconstruction loss (difference between the input and the reconstructed input) is used for the training. In our approach, to encourage the semantic encoder to capture the attribute-related information only, we use two novel loss functions on top of the reconstruction loss. First, we employ the mutual information (MI)-based loss to maximize (minimize) MI between the semantic (residual) encoder output and the attribute. Since MI is a metric to measure the level of dependency between two random variables, by exploiting the MI-based loss, we can encourage the semantic encoder to capture the attribute-related information and at the same time discourage the residual encoder to capture any attribute-related information. As a result, all the attribute-related information can be solely captured by the semantic encoder. Second, we use the similarity-based loss to enforce the semantic encoder not to catch any attribute-irrelevant information. For example, when a bird image contains human fingers (see Fig.~\ref{fig:CUB}), we do not want features related to the finger to be included in the semantic encoder output. To do so, we maximize the similarity between the semantic encoder outputs of images that are belonging to the same class (bird images in our example). Since attribute-irrelevant features are contained only in a few image samples (e.g., human fingers are included in a few bird images), by maximizing the similarity between the semantic encoder outputs of the same class, we can remove attribute-irrelevant information from the semantic encoder output. From extensive experiments using various benchmark datasets (AwA1, AwA2, CUB, and SUN), we demonstrate that the proposed approach outperforms the conventional GZSL techniques by a large margin. For example, for the AwA2 and CUB datasets, our model achieves 2\% improvement in the GZSL classification accuracy over the state-of-the-art techniques. \section{Related Work and Background} \subsection{Conventional GZSL Approaches} The main task in GZSL is to learn the relationship between the image and the attribute from seen classes and then use it in the identification of unseen classes. Early GZSL works have focused on the training of a network measuring the compatibility score between the image feature and the attribute~\cite{ALE, DeViSE}. Once the network is trained properly, images can be classified by identifying the attribute achieving the maximum compatibility score. Recently, generative model-based GZSL approaches have been proposed~\cite{CVAE-GZSL, CLSWGAN}. Key idea of these approaches is to generate synthetic image features of unseen classes from the attributes by employing a generative model~\cite{CVAE-GZSL, CLSWGAN}. As a generative model, conditional variational autoencoder (CVAE)~\cite{vae} and conditional Wasserstein generative adversarial network (CWGAN)~\cite{WGAN} have been popularly used. By exploiting the generated image features of unseen classes as training data, a classification network identifying unseen classes can be trained in a supervised manner. Over the years, many efforts have been made to improve the performance of the generative model. In~\cite{f-vaegan-d2, CADA-VAE, Zero-VAE-GAN}, an approach to combine multiple generative models (e.g., CVAE and CWGAN) has been proposed. In~\cite{cycle-WGAN, DASCN}, an additional network estimating the image attribute from the image feature has been used to make sure that the synthetic image features satisfy the attribute of unseen classes. In~\cite{CLSWGAN, LsrGAN, LisGAN}, an additional image classifier has been used in the generative model training to generate distinct image features for different classes. Our approach is conceptually similar to the generative model-based approach in the sense that we generate synthetic image features of unseen classes using the generative model. The key distinctive point of the proposed approach over the conventional approaches is that we use the features containing only attribute-related information in the classification to remove the interference, if any, caused by the attribute-irrelevant information. \subsection{MI for Deep Learning} Mathematically, the MI $I(\mathbf{u}, \mathbf{v})$ between two random variables $\mathbf{u}$ and $\mathbf{v}$ is defined as \begin{align} I(\mathbf{u}, \mathbf{v}) &= \mathbb{E}_{p(\mathbf{u}, \mathbf{v})} \left [ \log \frac{p(\mathbf{u}, \mathbf{v})}{p(\mathbf{u}) p(\mathbf{v})} \right ] \nonumber \\ &= \int_{\mathbf{u}} \int_{\mathbf{v}} p(\mathbf{u}, \mathbf{v}) \log \frac{p(\mathbf{u}, \mathbf{v})}{p(\mathbf{u}) p(\mathbf{v})} d \mathbf{u} d \mathbf{v}, \label{eq:MI_definition} \end{align} where $p(\mathbf{u}, \mathbf{v})$ is the joint probability density function (PDF) of $\mathbf{u}$ and $\mathbf{v}$, and $p(\mathbf{u})$ and $p(\mathbf{v})$ are marginal PDFs of $\mathbf{u}$ and $\mathbf{v}$, respectively. In practice, it is very difficult to compute the exact value of MI since the joint PDF $p(\mathbf{u}, \mathbf{v})$ is generally unknown and the integrals in~\eqref{eq:MI_definition} are often intractable. To approximate MI, various MI estimators have been proposed~\cite{InfoNCE, CLUB}. Representative estimators include InfoNCE~\cite{InfoNCE} and contrastive log-ratio upper bound (CLUB)~\cite{CLUB}, defined as \begin{align} I_{\text{InfoNCE}}(\mathbf{u}, \mathbf{v}) &= \mathbb{E}_{p(\mathbf{u}, \mathbf{v})} [ f(\mathbf{u}, \mathbf{v}) ] \hspace{-.5mm} \nonumber \\ &~~~- \hspace{-.5mm} \mathbb{E}_{p(\mathbf{u})} \hspace{-1mm} \left [ \log \left ( \mathbb{E}_{p(\mathbf{v})} [ \exp ( f(\mathbf{u}, \mathbf{v} ) ) ] \right ) \right ], \label{eq:MI_lower bound_InfoNCE} \\ I_{\text{CLUB}}(\mathbf{u}, \mathbf{v}) &= \mathbb{E}_{p(\mathbf{u}, \mathbf{v})} \hspace{-1mm} \left [ \log p(\mathbf{v} | \mathbf{u} ) \right ] \hspace{-.5mm} - \hspace{-.5mm} \mathbb{E}_{p(\mathbf{u})p(\mathbf{v})} \hspace{-1mm} \left [ \log p(\mathbf{v} | \mathbf{u} ) \right ], \label{eq:MI_upper bound_CLUB} \end{align} where $f$ is a pre-defined score function measuring the compatibility between $\mathbf{u}$ and $\mathbf{v}$, and $p(\mathbf{v} | \mathbf{u})$ is the conditional PDF of $\mathbf{v}$ given $\mathbf{u}$, which is often approximated by a neural network. The relationship between MI, InfoNCE, and CLUB is given by \begin{align} I_{\text{InfoNCE}}(\mathbf{u}, \mathbf{v}) \le I(\mathbf{u}, \mathbf{v}) \le I_{\text{CLUB}}(\mathbf{u}, \mathbf{v}). \label{eq:MI inequality} \end{align} Recently, InfoNCE and CLUB have been used to strengthen or weaken the independence between different parts of the neural network. For example, when one tries to enforce the independence between $\mathbf{u}$ and $\mathbf{v}$, that is, to reduce $I(\mathbf{u}, \mathbf{v})$, an approach to minimize the upper bound $I_{\text{CLUB}}(\mathbf{u}, \mathbf{v})$ of MI can be used~\cite{MI_minimization}. Whereas, when one wants to maximize the dependence between $\mathbf{u}$ and $\mathbf{v}$, that is, to increase $I(\mathbf{u}, \mathbf{v})$, an approach to maximize the lower bound $I_{\text{InfoNCE}}(\mathbf{u}, \mathbf{v})$ of MI~\cite{MI_maximization} can be used. \section{SE-GZSL} In this section, we present the proposed GZSL technique called semantic feature extraction-based GZSL (SE-GZSL). We first discuss how to extract the semantic feature from the image feature and then delve into the GZSL classification using the extracted semantic feature. \subsection{Semantic Feature Extraction} In extracting the semantic feature from the image feature, the proposed SE-GZSL technique uses the modified autoencoder architecture where two encoders, called semantic and residual encoders, are used in capturing the attribute-related information and the attribute-irrelevant information, respectively (see Fig~\ref{fig:SD}). As mentioned, in the autoencoder training, we use two loss functions: 1) MI-based loss to encourage the semantic encoder to capture all attribute-related information and 2) similarity-based loss to encourage the semantic encoder not to capture attribute-irrelevant information. In this subsection, we discuss the overall training loss with emphasis on these two. \paragraph{MI-based Loss} To make sure that all the attribute-related information is contained in the semantic encoder output, we use MI in the autoencoder training. To do so, we maximize MI between the semantic encoder output and the attribute which is given by manual annotation. At the same time, to avoid capturing of attribute-related information in the residual encoder, we minimize MI between the residual encoder output and the attribute. Let $\mathbf{z}_{s}$ and $\mathbf{z}_{r}$ be the semantic and residual encoder outputs corresponding to the image feature $\mathbf{x}$, and $\mathbf{a}$ be the image attribute (see Fig.~\ref{fig:SD}). Then, our training objective can be expressed as \begin{align} \text{minimize}~~~-\lambda_{s} I(\mathbf{z}_{s}, \mathbf{a}) + \lambda_{r} I(\mathbf{z}_{r}, \mathbf{a}), \label{eq:separation loss_MI form} \end{align} where $\lambda_{s}$ and $\lambda_{r}$ ($\lambda_{s}, \lambda_{r} > 0$) are weighting coefficients. Since the computation of MI is not tractable, we use InfoNCE and CLUB (see~\eqref{eq:MI_lower bound_InfoNCE} and~\eqref{eq:MI_upper bound_CLUB}) as a surrogate of MI. In our approach, to minimize the objective function in~\eqref{eq:separation loss_MI form}, we express its upper bound using InfoNCE and CLUB and then train the autoencoder in a way to minimize the upper bound. Using the relationship between MI and its estimators in~\eqref{eq:MI inequality}, the upper bound $\mathcal{L}_{\text{MI}}$ of the objective function in~\eqref{eq:separation loss_MI form} is \begin{align} \mathcal{L}_{\text{MI}} &= -\lambda_{s} I_{\text{InfoNCE}}(\mathbf{z}_{s}, \mathbf{a}) + \lambda_{r} I_{\text{CLUB}} (\mathbf{z}_{r}, \mathbf{a}) \nonumber \\ &= -\lambda_{s} \mathbb{E}_{p(\mathbf{z}_{s}, \mathbf{a})} [ f(\mathbf{z}_{s}, \mathbf{a}) ] \nonumber \\ &~~~ + \hspace{-.5mm} \lambda_{s} \mathbb{E}_{p(\mathbf{z}_{s})} \hspace{-1mm} \left [ \log \left ( \mathbb{E}_{p(\mathbf{a})} [ \exp ( f(\mathbf{z}_{s}, \mathbf{a}) ) ] \right ) \right ] \nonumber \\ &~~~ +\lambda_{r} \left ( \mathbb{E}_{p(\mathbf{z}_{r}, \mathbf{a})} \hspace{-1mm} \left [ \log p(\mathbf{a} | \mathbf{z}_{r} ) \right ] \hspace{-.5mm} - \hspace{-.5mm} \mathbb{E}_{p(\mathbf{z}_{r})p(\mathbf{a})} \hspace{-1mm} \left [ \log p(\mathbf{a} | \mathbf{z}_{r} ) \right ] \right ) \hspace{-1mm}. \label{eq:separation loss_expectation form} \end{align} Let $\mathcal{Y}_{s}$ be the set of seen classes, $\mathbf{a}_{c}$ be the attribute of a seen class $c \in \mathcal{Y}_{s}$, and $\{ \mathbf{x}_{c}^{(i)} \}_{i=1}^{N_{c}}$ be the set of training image features for the class $c$. Further, let $\mathbf{z}_{c, s}^{(i)}$ and $\mathbf{z}_{c, r}^{(i)}$ be the semantic and residual encoder outputs corresponding to the input image feature $\mathbf{x}_{c}^{(i)}$, respectively, then $\mathcal{L}_{\text{MI}}$ can be expressed as \begin{align} \mathcal{L}_{\text{MI}} &= -\frac{\lambda_{s}}{N} \sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \log \frac{\exp ( f ( \mathbf{z}_{c, s}^{(i)}, \mathbf{a}_{c} ) )} {\frac{1}{|\mathcal{Y}_{s}|} \hspace{-.5mm} \underset{c^{\prime} \in \mathcal{Y}_{s}}{\sum} \exp ( f ( \mathbf{z}_{c, s}^{(i)}, \mathbf{a}_{c^{\prime}} ) )} \nonumber \\ &~+\frac{\lambda_{r}}{N} \hspace{-.5mm} \sum_{c \in \mathcal{Y}_{s}} \hspace{-.5mm} \sum_{i=1}^{N_{c}} \hspace{-.5mm} \left ( \log p(\mathbf{a}_{c} | \mathbf{z}_{c, r}^{(i)}) - \hspace{-2mm} \underset{c^{\prime} \in \mathcal{Y}_{s}}{\sum} \hspace{-.5mm} \frac{\log p(\mathbf{a}_{c^{\prime}} | \mathbf{z}_{c, r}^{(i)})}{|\mathcal{Y}_{s}|} \hspace{-.5mm} \right ) \hspace{-1mm}, \label{eq:separation loss} \end{align} where $N = \sum_{c \in \mathcal{Y}_{s}} N_{c}$ is the total number of training image features. \paragraph{Similarity-based Loss} We now discuss the similarity-based loss to enforce the semantic encoder not to capture any attribute-irrelevant information. Since images belonging to the same class have the same attribute, attribute-related image features of the same class would be more or less similar. This means that if the semantic encoder captures attribute-related information only, then the similarity between semantic encoder outputs of the same class should be large. Inspired by this observation, to remove the attribute-irrelevant information from the semantic encoder output, we train the semantic encoder in a way to maximize the similarity between outputs of the same class: \begin{align} \text{maximize}~~~\sum_{j=1}^{N_{c}} \exp (\operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c, s}^{(j)} ) ), \label{eq:similarity loss_same class} \end{align} where the similarity is measured using the cosine-similarity function defined as \begin{align*} \operatornamewithlimits{sim}(\mathbf{u}, \mathbf{v}) &= \frac{\langle \mathbf{u}, \mathbf{v} \rangle} {\| \mathbf{u} \|_{2} \| \mathbf{v} \|_{2}}. \end{align*} Also, we minimize the similarity between semantic encoder outputs of different classes to obtain sufficiently distinct semantic encoder outputs for different classes: \begin{align} \text{minimize}~~~\sum_{c^{\prime} \neq c} \sum_{j=1}^{N_{c^{\prime}}} \exp ( \operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c^{\prime}, s}^{(j)} ) ). \label{eq:similarity loss_different classes} \end{align} Using the fact that one can maximize $A$ and minimize $B$ at the same time by minimizing $-\log \frac{1}{1+B/A} = -\log \frac{A}{A+B}$, we obtain the similarity-based loss as \begin{align} \mathcal{L}_{\text{sim}} &= -\frac{1}{N} \sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \log \frac{\underset{j=1}{\overset{N_{c}}{\sum}} \exp \hspace{-.7mm} \left ( \hspace{-.5mm} \operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c, s}^{(j)} ) \hspace{-.5mm} \right )} { \underset{c^{\prime} \in \mathcal{Y}_{s}}{\sum} \underset{j=1}{\overset{N_{c^{\prime}}}{\sum}} \exp \hspace{-.7mm} \left ( \hspace{-.5mm} \operatornamewithlimits{sim} ( \mathbf{z}_{c, s}^{(i)}, \mathbf{z}_{c^{\prime}, s}^{(j)} ) \hspace{-.5mm} \right ) }. \label{eq:similarity loss} \end{align} \subsubsection{Overall Loss} By adding the conventional reconstruction loss $\mathcal{L}_{\text{recon}}$ for the autoencoder, the MI-based loss $\mathcal{L}_{\text{MI}}$, and the similarity-based loss $\mathcal{L}_{\text{sim}}$, we obtain the overall loss function as \begin{align} \mathcal{L}_{\text{total}} &= \mathcal{L}_{\text{recon}} + \mathcal{L}_{\text{MI}} + \lambda_{\text{sim}} \mathcal{L}_{\text{sim}}, \label{eq:decomposition loss} \end{align} where $\lambda_{\text{sim}}$ is a weighting coefficient and $\mathcal{L}_{\text{recon}}$ is the reconstruction loss given by \begin{align} \mathcal{L}_{\text{recon}} &= \frac{1}{N} \sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \| \mathbf{x}_{c}^{(i)} - \widehat{\mathbf{x}}_{c}^{(i)} \|_{2}. \end{align} Here, $\widehat{\mathbf{x}}_{c}^{(i)}$ is the image feature reconstructed using the semantic and residual encoder outputs ($\mathbf{z}_{c, s}^{(i)}$ and $\mathbf{z}_{c, r}^{(i)}$) in the decoder. When the training is finished, we only use the semantic encoder for the purpose of extracting the semantic feature. \subsection{GZSL Classification Using Semantic Features} So far, we have discussed how to extract the semantic feature from the image feature. We now discuss how to perform the GZSL classification using the semantic feature. In a nutshell, we synthesize semantic feature samples for unseen classes from their attributes. Once the synthetic samples are generated, the semantic classifier identifying unseen classes from the semantic feature is trained in a supervised manner. \paragraph{Semantic Feature Generation} \begin{figure*}[h] \centering \centerline{\includegraphics[width=13cm]{generator.eps}} \caption{Illustration of the synthetic semantic feature generation for unseen classes.} \label{fig:generator} \end{figure*} To synthesize the semantic feature samples for unseen classes, we first generate image features from the attributes of unseen classes and then extract the semantic features from the synthetic image features using the semantic encoder (see Fig.~\ref{fig:generator}). In synthesizing the image feature, we employ WGAN that mitigates the unstable training issue of GAN by exploiting a Wasserstein distance-based loss function~\cite{WGAN}. The main component in WGAN is a generator $G$ synthesizing the image feature $\widetilde{\mathbf{x}}_{c}$ from a random noise vector $\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})$ and the image attribute $\mathbf{a}_{c}$ (i.e., $\widetilde{\mathbf{x}}_{c} = G(\boldsymbol{\epsilon}, \mathbf{a}_{c})$). Conventionally, WGAN is trained to minimize the Wasserstein distance between the distributions of real image feature $\mathbf{x}_{c}$ and generated image feature $\widetilde{\mathbf{x}}_{c}$ given by \begin{align} \lefteqn{\hspace{-.2cm} \mathcal{L}_{G, \text{WGAN}}} \nonumber \\ &\hspace{-.3cm}= \max_{D} \hspace{-.5mm} \bigg ( \mathbb{E}_{p(\mathbf{x}_{c} | \mathbf{a}_{c})} [ D(\mathbf{x}_{c}, \mathbf{a}_{c}) ] - \mathbb{E}_{p(\widetilde{\mathbf{x}}_{c} | \mathbf{a}_{c})} [ D(\widetilde{\mathbf{x}}_{c}, \mathbf{a}_{c}) ] \nonumber \\ &\hspace{-.3cm}~~~~~~~~~~~~~~ -\lambda_{\text{gp}} \mathbb{E}_{p(\widehat{\mathbf{x}}_{c} | \mathbf{a}_{c})} \hspace{-.8mm} \left [ \left ( \| \nabla_{\widehat{\mathbf{x}}_{c}} D(\widehat{\mathbf{x}}_{c}, \mathbf{a}_{c}) \|_{2} - 1 \right )^{2} \right ] \hspace{-.8mm} \bigg ), \label{eq:generator_WGAN loss} \end{align} where $D$ is an auxiliary network (called critic), $\widehat{\mathbf{x}}_{c} = \alpha \mathbf{x}_{c} + (1 - \alpha) \widetilde{\mathbf{x}}_{c}~(\alpha \sim \mathcal{U}(0, 1))$, and $\lambda_{\text{gp}}$ is the regularization coefficient (a.k.a., gradient penalty coefficient)~\cite{WGAN-GP}. In our scheme, to make sure that the semantic feature $\widetilde{\mathbf{z}}_{c, s}$ obtained from $\widetilde{\mathbf{x}}_{c}$ is similar to the real semantic feature $\mathbf{z}_{c, s}$, we additionally use the following losses in the WGAN training: \begin{align} \mathcal{L}_{G, \text{MI}} &= -I_{\text{InfoNCE}}(\widetilde{\mathbf{z}}_{c, s}, \mathbf{a}_{c}), \label{eq:generator_InfoNCE loss} \\ \mathcal{L}_{G, \text{sim}} &= -\mathbb{E}_{p(\widetilde{\mathbf{z}}_{c, s})} \hspace{-1mm} \left [ \log \frac{\underset{i=1}{\overset{N_{c}}{\sum}} \exp ( \operatornamewithlimits{sim} (\widetilde{\mathbf{z}}_{c, s}, \mathbf{z}_{c, s}^{(i)}) )} {\underset{c^{\prime}=1}{\overset{S}{\sum}} \underset{i=1}{\overset{N_{c^{\prime}}}{\sum}} \exp ( \operatornamewithlimits{sim} (\widetilde{\mathbf{z}}_{c, s}, \mathbf{z}_{c^{\prime}, s}^{(i)}) )} \right ]. \label{eq:generator_similarity loss} \end{align} We note that these losses are analogous to the losses with respect to the real semantic feature $\mathbf{z}_{c, s}$ in~\eqref{eq:separation loss_expectation form} and~\eqref{eq:similarity loss}, respectively. By combining~\eqref{eq:generator_WGAN loss},~\eqref{eq:generator_InfoNCE loss}, and~\eqref{eq:generator_similarity loss}, we obtain the overall loss function as \begin{align} \mathcal{L}_{G} &= \mathcal{L}_{G, \text{WGAN}} + \lambda_{G, \text{MI}} \mathcal{L}_{G, \text{MI}} + \lambda_{G, \text{sim}} \mathcal{L}_{G, \text{sim}}, \label{eq:generator loss} \end{align} where $\lambda_{G, \text{MI}}$ and $\lambda_{G, \text{sim}}$ are weighting coefficients. After the WGAN training, we use the generator $G$ and the semantic encoder $E_{s}$ in synthesizing semantic feature samples of unseen classes. Specifically, for each unseen class $u \in \mathcal{Y}_{u}$, we generate the semantic feature $\widetilde{\mathbf{z}}_{u, s}$ by synthesizing the image feature $\widetilde{\mathbf{x}}_{u} = G(\boldsymbol{\epsilon}, \mathbf{a}_{u})$ using the generator and then exploiting it as an input to the semantic encoder (see Fig.~\ref{fig:generator}): \begin{align} \widetilde{\mathbf{z}}_{u, s} = E_{s}(\widetilde{\mathbf{x}}_{u}) = E_{s}(G(\boldsymbol{\epsilon}, \mathbf{a}_{u})). \end{align} By resampling the noise vector $\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})$, a sufficient number of synthetic semantic features can be generated. \paragraph{Semantic Feature-based Classification} After generating synthetic semantic feature samples for all unseen classes, we train the semantic feature classifier using a supervised learning model (e.g., softmax classifier, support vector machine, and nearest neighbor). Suppose, for example, that the softmax classifier is used as a classification model. Let $\{ \widetilde{\mathbf{z}}_{u, s}^{(i)} \}_{i=1}^{N_{u}}$ be the set of synthetic semantic feature samples for the unseen class $u$, then the semantic feature classifier is trained to minimize the cross entropy loss\footnote{We recall that $\{ \mathbf{z}_{c, s}^{(i)} \}_{i=1}^{N_{c}}$ is the set of semantic features for the seen class $c \in \mathcal{Y}_{s}$.} \begin{align} \mathcal{L}_{\text{CE}} &= -\sum_{c \in \mathcal{Y}_{s}} \sum_{i=1}^{N_{c}} \log P( c | \mathbf{z}_{c, s}^{(i)} ) - \sum_{u \in \mathcal{Y}_{u}} \sum_{i=1}^{N_{u}} \log P( u | \widetilde{\mathbf{z}}_{u, s}^{(i)} ), \end{align} where \begin{align} P(y|\mathbf{z}) &= \frac{\exp (\mathbf{w}_{y}^{T} \mathbf{z} + b_{y})}{ \sum_{y^{\prime} \in \mathcal{Y}_{s} \cup \mathcal{Y}_{u}} \exp (\mathbf{w}_{y^{\prime}}^{T} \mathbf{z} + b_{y^{\prime}})} \end{align} and $\mathbf{w}_{y}$ and $b_{y}$ are weight and bias parameters of the softmax classifier to be learned. \subsection{Comparison with Conventional Approaches} There have been previous efforts to extract the semantic feature from the image feature~\cite{DLFZRL, RFF-GZSL, Disentangled-VAE, SDGZSL}. While our approach seems to be a bit similar to~\cite{Disentangled-VAE} and~\cite{SDGZSL} in the sense that the autoencoder-based image feature decomposition method is used for the semantic feature extraction, our work is dearly distinct from those works in two respects. First, we use different training strategy in capturing the attribute-related information. In our approach, to make sure that the semantic encoder output contains all the attribute-related information, we use two complementary loss terms: 1) the loss term to encourage the semantic encoder to capture the attribute-related information and 2) the loss term to discourage the residual encoder to capture any attribute-related information (see~\eqref{eq:separation loss_MI form}). Whereas, the training loss used to remove the attribute-related information from the residual encoder output has not been used in~\cite{Disentangled-VAE, SDGZSL}. Also, we employ a new training loss $\mathcal{L}_{\text{sim}}$ to remove the attribute-irrelevant information from the semantic encoder output (see~\eqref{eq:similarity loss}), for which there is no counterpart in~\cite{Disentangled-VAE, SDGZSL}. \section{Experiments} \begin{table}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c | c | c | c } \toprule Classifier input & AwA1 & AwA2 & CUB & SUN \\ \midrule Image feature & 90.9 & 92.8 & 73.8 & 47.1 \\ Semantic feature & \textbf{91.9} & \textbf{93.4} & \textbf{76.1} & \textbf{49.3} \\ \bottomrule \end{tabular} }} \caption{Top-1 accuracy of image feature-based and semantic feature-based image classifiers.} \label{tab:result_effect of attribute-related feature extraction} \end{table} \begin{figure*}[!t] \begin{minipage}[b]{0.33 \linewidth} \centering \centerline{\includegraphics[width=6cm]{tsne_semantic.png}} \centerline{(a) Semantic features} \end{minipage} \hfill \begin{minipage}[b]{0.33 \linewidth} \centering \centerline{\includegraphics[width=6cm]{tsne_visual.png}} \centerline{(b) Image features} \end{minipage} \hfill \begin{minipage}[b]{0.33 \linewidth} \centering \centerline{\includegraphics[width=6cm]{tsne_residual.png}} \centerline{(c) Residual features} \end{minipage} \caption{t-SNE visualization of (a) semantic features, (b) image features, and (c) residual features. Samples for the same class are indicated in the same color.} \label{fig:t-SNE} \end{figure*} \begin{table*}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c | c c c | c c c | c c c | c c c} \toprule \multirow{2}{2.2cm}{\centering Method} & \multirow{2}{2.2cm}{\centering Feature Type} & \multicolumn{3}{c|}{AwA1} & \multicolumn{3}{c|}{AwA2} & \multicolumn{3}{c|}{CUB} & \multicolumn{3}{c}{SUN} \\ \cline{3-14} & & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ \\ \toprule CVAE-GZSL & \multirow{9}{2.2cm}{\centering ResNet} & - & - & 47.2 & - & - & 51.2 & - & - & 34.5 & - & - & 26.7 \\ f-CLSWGAN & & 61.4 & 57.9 & 59.6 & - & - & - & 57.7 & 43.7 & 49.7 & 36.6 & 42.6 & 39.4 \\ cycle-CLSWGAN & & 64.0 & 56.9 & 60.2 & - & - & - & 61.0 & 45.7 & 52.3 & 33.6 & 49.4 & 40.0 \\ f-VAEGAN-D2 & & - & - & - & 70.6 & 57.6 & 63.5 & 60.1 & 48.4 & 53.6 & 38.0 & 45.1 & 41.3 \\ LisGAN & & 76.3 & 52.6 & 62.3 & - & - & - & 57.9 & 46.5 & 51.6 & 37.8 & 42.9 & 40.2 \\ CADA-VAE & & 72.8 & 57.3 & 64.1 & 75.0 & 55.8 & 63.9 & 53.5 & 51.6 & 52.4 & 35.7 & 47.2 & 40.6 \\ DASCN & & 68.0 & 59.3 & 63.4 & - & - & - & 59.0 & 45.9 & 51.6 & 38.5 & 42.4 & 40.3 \\ LsrGAN & & 74.6 & 54.6 & 63.0 & - & - & - & 59.1 & 48.1 & 53.0 & 37.7 & 44.8 & 40.9 \\ Zero-VAE-GAN & & 66.8 & 58.2 & 62.3 & 70.9 & 57.1 & 62.5 & 47.9 & 43.6 & 45.5 & 30.2 & 45.2 & 36.3 \\ \midrule DLFZRL & \multirow{3}{2.2cm}{\centering Semantic} & - & - & 61.2 & - & - & 60.9 & - & - & 51.9 & - & - & {\underline{42.5}} \\ RFF-GZSL & & 75.1 & 59.8 & {\underline{66.5}} & - & - & - & 56.6 & 52.6 & {\underline{54.6}} & 38.6 & 45.7 & 41.9 \\ Disentangled-VAE & & 72.9 & 60.7 & 66.2 & 80.2 & 56.9 & {\underline{66.6}} & 58.2 & 51.1 & 54.4 & 36.6 & 47.6 & 41.4 \\ \midrule {\bf{SE-GZSL}} & Semantic & 76.7 & 61.3 & {\bf{68.1}} & 80.7 & 59.9 & {\bf{68.8}} & 60.3 & 53.1 & {\bf{56.4}} & 40.7 & 45.8 & {\bf{43.1}} \\ \bottomrule \end{tabular} }} \caption{GZSL classification performance of the proposed SE-GZSL technique and conventional approaches. `-' means that the result is not reported in the references. The best results are in bold, and the second best results are underlined.} \label{tab:result_GZSL performance} \end{table*} \begin{table*}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c c c | c c c | c c c | c c c} \toprule \multirow{2}{2.2cm}{\centering Loss}& \multicolumn{3}{c|}{AwA1} & \multicolumn{3}{c|}{AwA2} & \multicolumn{3}{c|}{CUB} & \multicolumn{3}{c}{SUN} \\ \cline{2-13} & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ & $acc_{s}$ & $acc_{u}$ & $acc_{h}$ \\ \toprule $\mathcal{L}_{\text{recon}}$ & 64.6 & 53.1 & 58.3 & 68.9 & 55.7 & 61.6 & 54.5 & 46.1 & 49.9 & 38.4 & 40.6 & 39.4 \\ $\mathcal{L}_{\text{recon}}$ + $\mathcal{L}_{\text{MI}}$ & 75.0 & 57.9 & 65.4 & 74.2 & 58.6 & 65.5 & 59.4 & 51.5 & 55.1 & 37.1 & 46.5 & 41.3 \\ $\mathcal{L}_{\text{recon}}$ + $\mathcal{L}_{\text{MI}}$ + $\mathcal{L}_{\text{sim}}$ & 76.7 & 61.3 & \textbf{68.1} & 80.7 & 59.9 & \textbf{68.8} & 60.3 & 53.1 & \textbf{56.4} & 40.7 & 45.8 & \textbf{43.1} \\ \bottomrule \end{tabular} }} \caption{Ablation study on the performance of SE-GZSL.} \label{tab:result_ablation study} \end{table*} \subsection{Experimental Setup} \paragraph{Datasets} In our experiments, we evaluate the performance of our model using four benchmark datasets: AwA1, AwA2, CUB, and SUN. The AwA1 and AwA2 datasets contain 50 classes of animal images annotated with 85 attributes~\cite{zsl_proposal, AwA2}. The CUB dataset contains 200 species of bird images annotated with 312 attributes~\cite{CUB}. The SUN dataset contains 717 classes of scene images annotated with 102 attributes~\cite{SUN}. In dividing the total classes into seen and unseen classes, we adopt the conventional dataset split presented in~\cite{AwA2}. \paragraph{Implementation Details} As in~\cite{CLSWGAN, CADA-VAE}, we use ResNet-101~\cite{ResNet} as a pre-trained classification network and fix it in our training process. We implement all the networks in SE-GZSL (semantic encoder, residual encoder, and decoder in the image feature decomposition network, and generator and critic in WGAN) using the multilayer perceptron (MLP) with one hidden layer as in~\cite{CLSWGAN, f-vaegan-d2}. We set the number of hidden units to 4096 and use LeakyReLU with a negative slope of 0.02 as a nonlinear activation function. For the output layer of the generator, the ReLU activation is used since the image feature extracted by ResNet is non-negative. As in~\cite{InfoNCE}, we define the score function $f$ in~\eqref{eq:separation loss_expectation form} as $f(\mathbf{z}_{s}, \mathbf{a}) = \mathbf{z}_{s}^{T} \mathbf{W} \mathbf{a}$ where $\mathbf{W}$ is a weight matrix to be learned. Also, as in~\cite{CLUB}, we approximate the conditional PDF $p(\mathbf{a} | \mathbf{z}_{r})$ in~\eqref{eq:separation loss_expectation form} using a variational encoder consisting of two hidden layers. The gradient penalty coefficient in the WGAN loss $\mathcal{L}_{G, \text{WGAN}}$ is set to $\lambda_{\text{gp}} = 10$ as suggested in the original WGAN paper~\cite{WGAN-GP}. We set the weighting coefficients in~\eqref{eq:separation loss}, ~\eqref{eq:decomposition loss}, and~\eqref{eq:generator loss} to $\lambda_{s}=20, \lambda_{r}=50, \lambda_{\text{sim}}=1, \lambda_{G, \text{MI}}=1, \lambda_{G, \text{sim}} = 0.025$. \subsection{Semantic Feature-based Image Classification} We first investigate whether the image classification performance can be improved by exploiting the semantic feature. To this end, we train two image classifiers: the classifier exploiting the image feature and the classifier utilizing the semantic feature extracted by the semantic encoder. To compare the semantic feature directly with the image feature, we use the simple softmax classifier as a classification model. In Table~\ref{tab:result_effect of attribute-related feature extraction}, we summarize the top-1 classification accuracy of each classifier on test image samples for seen classes. We observe that the semantic feature-based classifier outperforms the image feature-based classifier for all datasets. In particular, for the SUN and CUB datasets, the semantic feature-based classifier achieves about $2\%$ improvement in the top-1 classification accuracy over the image feature-based classifier, which demonstrates that the image classification performance can be enhanced by removing the attribute-irrelevant information in the image feature. \subsection{Visualization of Semantic Features} In Fig.~\ref{fig:t-SNE}, we visualize semantic feature samples obtained from the CUB dataset using a t-distributed stochastic neighbor embedding (t-SNE), a tool to visualize high-dimensional data in a two-dimensional plane~\cite{t-SNE}. For comparison, we also visualize image feature samples and residual feature samples extracted by the residual encoder. We observe that semantic feature samples containing only attribute-related information are well-clustered, that is, samples of the same class are grouped and samples of different classes are separated (see Fig.~\ref{fig:t-SNE}(a)). Whereas, image feature samples of different classes are not separated sufficiently (see Fig.~\ref{fig:t-SNE}(b)) and residual feature samples are scattered randomly (see Fig.~\ref{fig:t-SNE}(c)). \subsection{Comparison with State-of-the-art} We next evaluate the GZSL classification performance of the proposed approach using the standard evaluation protocol presented in~\cite{AwA2}. Specifically, we measure the average top-1 classification accuracies $acc_{s}$ and $acc_{u}$ on seen and unseen classes, respectively, and then use their harmonic mean $acc_{h}$ as a metric to evaluate the performance. In Table~\ref{tab:result_GZSL performance}, we summarize the performance of SE-GZSL on different datasets. For comparison, we also summarize the performance of conventional methods among which DLFZRL, RFF-GZSL, and Disentangled-VAE are semantic feature-based approaches~\cite{DLFZRL, RFF-GZSL, Disentangled-VAE} and other methods are image feature-based approaches~\cite{CVAE-GZSL, CLSWGAN, cycle-WGAN, f-vaegan-d2, LisGAN, CADA-VAE, DASCN, LsrGAN, Zero-VAE-GAN}. From the results, we observe that the proposed SE-GZSL outperforms conventional image feature-based approaches by a large margin. For example, for the AwA2 dataset, SE-GZSL achieves about 5\% improvement in the harmonic mean accuracy over image feature-based approaches. We also observe that SE-GZSL outperforms existing semantic feature-based approaches for all datasets. For example, for the AwA1, AwA2, and CUB datasets, our model achieves about 2\% improvement in the harmonic mean accuracy over the state-of-the-art approaches. \subsection{Ablation Study} \paragraph{Effectiveness of Loss Functions} In training the semantic feature extractor, we have used the MI-based loss $\mathcal{L}_{\text{MI}}$ and the similarity-based loss $\mathcal{L}_{\text{sim}}$. To examine the impact of each loss function, we measure the performance of three different versions of SE-GZSL: 1) SE-GZSL trained only with the reconstruction loss $\mathcal{L}_{\text{recon}}$, 2) SE-GZSL trained with $\mathcal{L}_{\text{recon}}$ and $\mathcal{L}_{\text{MI}}$, and 3) SE-GZSL trained with $\mathcal{L}_{\text{recon}}$, $\mathcal{L}_{\text{MI}}$, and $\mathcal{L}_{\text{sim}}$. From the results in Table~\ref{tab:result_ablation study}, we observe that the performance of SE-GZSL can be enhanced greatly by exploiting the MI-based loss $\mathcal{L}_{\text{MI}}$. In particular, for the AwA1 and CUB datasets, we achieve more than $5\%$ improvement in the harmonic mean accuracy by utilizing $\mathcal{L}_{\text{MI}}$. Also, for the AwA2 dataset, we achieve about $4\%$ improvement of the accuracy. One might notice that when $\mathcal{L}_{\text{MI}}$ is not used, SE-GZSL performs worse than conventional image feature-based methods (see Table~\ref{tab:result_GZSL performance}). This is because the semantic encoder cannot capture all the attribute-related information without $\mathcal{L}_{\text{MI}}$, and thus using the semantic encoder output in the classification incurs the loss of the attribute-related information. We also observe that the performance of SE-GZSL can be improved further by exploiting the similarity-based loss $\mathcal{L}_{\text{sim}}$. For example, for the AwA2 dataset, more than $3\%$ improvement in the harmonic mean accuracy can be achieved by utilizing $\mathcal{L}_{\text{sim}}$. \paragraph{Importance of Residual Encoder} \begin{table}[t] \centering {\resizebox{1.0\linewidth}{!}{ \begin{tabular}{c | c | c | c | c} \toprule Method & AwA1 & AwA2 & CUB & SUN \\ \toprule SE-GZSL w/o residual encoder & 66.7 & 67.5 & 55.1 & 42.1 \\ \midrule SE-GZSL w/ residual encoder & {\bf{68.1}} & {\bf{68.8}} & {\bf{56.4}} & {\bf{43.1}} \\ \bottomrule \end{tabular} }} \caption{Harmonic mean accuracy of SE-GZSL with and without the residual encoder.} \label{tab:rebuttal_residual encoder} \end{table} For the semantic feature extraction, we have decomposed the image feature into the attribute-related feature and the attribute-irrelevant feature using the semantic and residual encoders. An astute reader might ask why the residual encoder is needed to extract the semantic feature. To answer this question, we measure the performance of SE-GZSL without using the residual encoder. From the results in Table~\ref{tab:rebuttal_residual encoder}, we can observe that the GZSL performance of SE-GZSL is degraded when the residual encoder is not used. This is because if the residual encoder is removed, then the attribute-irrelevant information, required for the reconstruction of the image feature, would be contained in the semantic encoder output and therefore mess up the process to learn the relationship between the image feature and the attribute. \section{Conclusion} In this paper, we presented a new GZSL technique called SE-GZSL. Key idea of the proposed SE-GZSL is to exploit the semantic feature in learning the relationship between the image and the attribute, removing the interference caused by the attribute-irrelevant information. To extract the semantic feature, we presented the autoencoder-based image feature decomposition network consisting of semantic and residual encoders. In a nutshell, the semantic and residual encoders capture the attribute-related information and the attribute-irrelevant information, respectively. In training the image feature decomposition network, we used MI-based loss to encourage the semantic encoder to capture all the attribute-related information and similarity-based loss to discourage the semantic encoder to capture any attribute-irrelevant information. Our experiments on various datasets demonstrated that the proposed SE-GZSL outperforms conventional GZSL approaches by a large margin. \section{Acknowledgements} This work was supported in part by the Samsung Research Funding \& Incubation Center for Future Technology of Samsung Electronics under Grant SRFC-IT1901-17 and in part by the National Research Foundation of Korea (NRF) grant funded by the Korea government (MSIT) under Grant 2020R1A2C2102198. {\small
{'timestamp': '2021-12-30T02:24:07', 'yymm': '2112', 'arxiv_id': '2112.14478', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14478'}
arxiv
\section{Three Main Project Modules} The overall architecture of our project is composed of three fundamental modules, namely~\emph{LEarning TO Rank (LETOR)}, ~\emph{Cloud Search}, and ~\emph{Query Expansion \& Suggestion}. Note that the overall system was inspired by the Yahoo search team article that comprehensively describes not only successes but also struggles with possible solutions in increasing Yahoo search engine's retrieval performance. The article is well-written best paper award-winner that is a good reference to understand all aspects of an end-to-end search engine. Hence, we established an overall structure of our search system using this paper as a reference~\cite{yin2016ranking}. One can find the project module details with the referenced papers that are elaborately discussed below. \subsection{LEarning TO Rank (LETOR)} The first module of the overall system utilizes and improves the state-of-the-art solutions in the literature to establish a successful search platform. In IR, the performance of a search engine is evaluated by measuring the retrieval performance i.e., retrieving most relevant documents at higher positions in search results. It has been achieved by employing traditional machine learning approaches and recently, also deep learning-based techniques has become part of this research area that is called LETOR. In the scope of the LETOR module, we explore the feature space by looking for the most useful features in document retrieval task. In our feature set, while some of the features exploit the textual content, others may convey the click information in order to represent the given dataset (training data) well enough for better learning. In the~\emph{Elasticsearch Plug-in Based Ranking} submodule, we explored textual features whereas in the ~\emph{Click Graph Based Ranking}, we delved into click-through analysis and integrated suitable features for that analysis to our feature set. In addition to these two submodules in ~\emph{Deep Learning Based Ranking}, it seems that we will not need to fullfill any feature engineering work, rather we allow the end-to-end deep learning system to extract features and learn model from the training dataset simultaneously. More details about the submodules can be found in the corresponding sections below. Furthermore in the ~\emph{Click Graph Based Ranking} which is the last submodule of LETOR, our main aim is to learn the semantic vector representations of query-document pairs without using deep learning techniques, rather a graph approach on the training dataset. \subsubsection{Dataset} The training dataset is composed of query-document pairs with click information as well as the relevance grades of the documents for the given queries. For each query-document pair, we have query, document title and click information. Moreover, there exists document url information that can be used (if needed) to fetch the whole document from the website for further analysis i.e., analysing snippet, keywords (if any) or important sections in the document. In addition to these, to evaluate our search platform we need to have relevance grades of the documents for their query pairs in the dataset. However, relevance information (ground truth) may not be available all the time and in that case we would encounter a very common problem of supervised approaches, namely the difficulty of having labelled data. Manual labelling is a costly process, therefore we may need alternative approaches such as transforming click information into relevance labels as in~\cite{joachims2002optimizing, carterette2007evaluating}. The detailed step-by-step transformation procedure can be found in our second-term progress report. \subsubsection{Elasticsearch Plug-in Based Ranking} In this module, initially we obtain Elasticsearch~\cite{gormley2015elasticsearch} features about query-document pairs in the click-logs. On top of this, we compute rather more complex features that are commonly used in IR systems such as tf, matched terms count, BM25, and related features that show the similarity of queries and corresponding documents in the logs. With the help of these additional features, our aim is to exploit query-document pairs more, in this way we can obtain more information and feed the system with this enriched input for training. Hopefully, the system will be able to learn better in comparison to only Elasticsearch features case, from the click-logs (training data) and a higher accuracy for document retrieval task will be achieved. The procedure of this submodule is as follows, each query-document pair is initially denoted as a feature vector and model is learned from the feature file by using a ranking algorithm from RankLib~\cite{dang2013lemur}. In this part of the overall system, our contribution is to propose more complex text-similarity features in addition to the relatively simple Elasticsearch features, hoping to increase the retrieval performance of our search platform. \subsubsection{Deep Learning-Based Ranking} Deep learning methods have become quite popular in recent years. Researchers have obtained the best accuracies so far with deep learning models in various research areas such as computer vision and NLP. Some of these computer vision and NLP tasks, on which DL-based approaches outperform traditional methods, are object detection, word embeddings, part-of-speech-tagging, finding dependencies in a given sentence as well as relatively more complex tasks like sentiment analysis and image captioning. Owing to the big achievements of deep learning on a broad range of problems, big technology companies like Google, Facebook, Amazon and Yahoo has invested in it continuously. Additionally, deep learning methods also have been applied to increase the retrieval performance of search engines. Yahoo~\cite{yin2016ranking} and Microsoft~\cite{shen2014latent} established more successful search platforms with deep learning models in comparison to state-of-the traditional approaches. In these published works, semantic queries are supported instead of simple keyword matching by taking into account of query context, along with user intent. You can find a list of pioneering studies that employ deep learning approaches to build a search engine with high retrieval performance in more detail below. Note that all of these works utilize supervised deep learning models and in this framework, click-logs is the training set in which queries are inputs and corresponding clicked documents are seen as outputs to train the chosen deep learning architecture. \paragraph{Paper Review: Learning Semantic Representations Using Convolutional Neural Networks for Web Search~\cite{shen2014learning}} \paragraph{Motivation: } Improving the modeling contextual information in click-log queries/documents and capturing it in a fine-grained manner. \paragraph{Method: } The paper proposes a series of new latent semantic models based on a ~\emph{convolutional neural network} to learn semantic word embeddings for search queries and Web documents. Initially, local contextual information at the word n-gram level is modeled by applying the convolution-max pooling operation. Subsequently, in order to constitute a global feature vector, salient local features in a word sequence are combined. As a final step, the high-level semantic feature vector of the input word sequence is extracted to form a global vector representation. To train the architecture, the proposed models are trained on click-through data by maximizing the conditional likelihood of clicked documents given a query, applying stochastic gradient ascent. \\ The closest work is DSSM~\cite{huang2013learning}, which is declared to outperform significantly semantic hashing and other traditional semantic models. Compared with DSSM, C-DSSM has a convolutional layer in which each word is projected within a context window to a local contextual feature vector. \begin{figure}[!t] \centering {\includegraphics[scale = 0.85]{Table1.PNG}} \caption{Superscripts $\alpha, \beta$, and $\gamma$ indicate statistically significant improvements ($p < 0.05$) over $BM25$, $PTM$, and $DSSM$, respectively.} \label{fig:table1} \end{figure} \paragraph{Experimental Results: } The retrieval model has been evaluated on a large-scale real world data set that contains 12,071 English queries sampled from one-year period of query log files. The evaluation metric is Normalized Discounted Cumulative Gain (NDCG) and only document titles were used for ranking. In the experiments, the click-through data used in training include 30 million of query/clicked document title pairs. \\ The proposed C-DSSM was compared with a set of baseline models, including BM25, the unigram language model (ULM), phrase-based translation model (PTR), word-based translation model (WTM), and the closest work to the current architecture, DSSM. As shown in Figure~\ref{fig:table1}, the C-DSSM outperforms all the state-of-the-art approaches with a significant margin. \paragraph{Paper Review: A Latent Semantic Model with Convolutional-Pooling Structure for Information Retrieval~\cite{shen2014latent}} \paragraph{Motivation: } In spite of the notable achievements obtained in recent studies, still all the prior latent semantic models treat a query (or a document) as a BoWs. Therefore, they are not effective in detecting contextual structures of a query (or a document). \begin{figure}[!h] \centering \includegraphics[scale = 0.85]{Fig1.PNG} \caption{Sample document titles. The text is lower-cased and punctuation removed. The same word, e.g., "office", has different meanings depending on its contexts.} \label{fig:fig1} \end{figure} As shown in Figure~\ref{fig:fig1} with several examples of document titles, the contextual information is very valuable in the task of semantic search and without this information, it seems that system fails to achieve high retrieval performance. \begin{figure}[!h] \centering \includegraphics[scale = 0.85]{Fig3.PNG} \caption{The CLSM maps a variable-length word sequence to a low-dimensional vector in a latent semantic space. A word contextual window size (i.e. the receptive field) of three is used in the illustration. Convolution over word sequence via learned matrix $W_c$ performed implicitly via the earlier layer's mapping with a local receptive field. The dimensionalities of the convolutional layer and the semantic layer are set to 300 and 128 in the illustration, respectively. The max operation across the sequence is applied for each of 300 feature dimensions separately. (Only the first dimension is shown to avoid figure clutter.)} \label{fig:fig3} \end{figure} \begin{figure}[!h] \centering \includegraphics[scale = 0.85]{Fig4.PNG} \caption{Comparative results with the previous state of the art approaches. BLTM, WTM, PTM, DSSM, and CLSM use the same click-through data for learning. Superscripts $\alpha$, $\beta$, and $\gamma$ indicate statistically significant improvements ($p < 0.05$) over $BM25$, $PTM$, and $DSSM (J = 50)$, respectively. (Models of \#1, \#2, \#11, \#12, and \#13 have been also used in the previous C-DSSM paper for comparison.)} \label{fig:fig4} \end{figure} \paragraph{Method: } In this study, a new latent semantic model that incorporates a convolutional-pooling structure over word sequences to learn low-dimensional, semantic vector representations for search queries/documents in the click-log. In order to detect the rich contextual structures, the procedure starts with each word within a sliding window (temporal context window) in a word sequence to directly capture contextual features at the word n-gram level. \\ In order to use the CLSM for IR, given a query and corresponding Web documents to be ranked, firstly the semantic vector representations for the query and all the documents using the architecture as described above. Then, a semantic relevance score is computed by measuring the cosine similarity between the semantic vectors of the query Q and each document D in the click-log which is used for training. In this work, the underlying assumption is that a query is relevant to the documents that are clicked on for that query, and train the CLSM on the click-through data accordingly. The high-level C-DSSM architecture is depicted in Figure~\ref{fig:fig3}. \paragraph{Experimental Results: } The evaluation is done on a Web document ranking task using a large-scale, real-world data set that contains. 12,071 English queries sampled from one-year query log files. Each query-document pair has a relevance label manually annotated on a 5-level relevance scale: $bad$, $fair$, $good$, $excellent$, and $perfect$, corresponding to 0 ($bad$) to 4 ($perfect$). \\ Results demonstrate that in retrieval performance, the proposed model significantly outperforms other state-of-the-art semantic models, which were prior to this work. BM25 and ULM are used as baselines and both use term vector representation. PLSA~\cite{hofmann1999probabilistic} was trained on documents only using MAP estimation with different number of topics, T. BLTM is the best performer bilingual topic model in~\cite{gao2011clickthrough}. MRF models the term dependency proposed in~\cite{metzler2005markov}. LCE is a latent concept expansion model as described in~\cite{metzler2007latent} that leverages the term-dependent information. WTM, a word-based translation model and PTM, phrase-based translation model were implemented as described in~\cite{gao2010clickthrough}. Lastly DSSM, which is the best variant of DSSM proposed in~\cite{huang2013learning}, is used for comparison by changing the number of negative samples J. Overall comparative results can be found in Figure~\ref{fig:fig4}. \begin{figure}[!h] \centering \includegraphics[scale = 0.85]{Fig5.PNG} \caption{Two types of deep matching models: (a) Representation-focused models employ a Siamese (symmetric) architecture over the text inputs; (b) Interaction-focused models employ a hierarchical deep architecture over the local interaction matrix.} \label{fig:fig5} \end{figure} \paragraph{Paper Review: A Deep Relevance Matching Model for Ad-hoc Retrieval~\cite{guo2016deep}} \paragraph{Motivation: } Although in recent years, deep neural networks have achieved successful results in distinct research areas such as computer vision, and natural language processing (NLP) tasks as mentioned above, few positive results have been reported in ad-hoc retrieval tasks. One of the main reasons behind this may be stemmed from the fact that many essential characteristics of the ad-hoc retrieval task have not yet been well addressed in deep models. The ad-hoc retrieval task is commonly formalized as a matching problem between textual contents of query and document in prior works using deep learning, and viewed in a similar way to many NLP asks such as paraphrase identification, question answering and automatic conversation. \\ However, researchers defend that the ad-hoc retrieval task is essentially about relevance matching while most NLP matching tasks solve semantic matching problem, and there exist some major differences between these matching tasks. Achieving high performance in relevance matching requires proper handling of the~\textbf{exact matching signals, query term importance and diverse matching requirements}. \paragraph{Method: } In this paper, a novel deep relevance matching model (DRMM) for ad-hoc retrieval has been proposed. Specifically, in the proposed model, a joint deep architecture at the query term level is employed for relevance matching. By applying matching histogram mapping, a feed forward matching network, and a term gating network, the researchers can effectively incorporate the three relevance matching factors mentioned above. \\ So far, to solve the matching problem and treat ad-hoc retrieval as an NLP task, different deep matching models have been presented. These deep learning architectures can be mainly categorized into two types based on their model architecture: a) representation-focused models, and b) interaction-focused models as depicted in Figure~\ref{fig:fig5}. \\ The first type of models, the representation-focused model, tries to build a good representation for a single text with a deep neural network, and then carries out matching between the compositional and abstract text representations. For instance, DSSM~\cite{huang2013learning} and C-DSSM~\cite{shen2014learning} can be categorized as the representation-focused models. The other is the interaction-focused model and in this type of model, local interactions between two pieces of text are formed, and then uses deep neural networks to detect hierarchical interaction patterns for matching. Deep Match~\cite{guo2016deep} is an example for interaction-focused models and the Deep Relevance Matching Model (DRMM) proposed in this work can also be put in this category. \\ In this study, the underlying hypothesis is that semantic matching and relevance matching are not the same thing. In fact, they are quite different problems and specifically, researchers point out three fundamental differences between these two concepts. In many NLP tasks such as paraphrase identification, question answering and automatic conversation, the matching is mainly related to~\emph{semantic matching}, i.e. identifying the semantic meaning and inferring the semantic relations between two pieces of text. The matching in ad-hoc retrieval task, on the other hand, is essentially about ~\emph{relevance matching}, i.e. identifying whether a document is relevant to a given query. These two different matching problems emphasize three distinct elements to find out solutions for NLP (semantic matching) and ad-hoc retrieval (relevance matching) respectively. In discussing these three factors, our aim is to show why we need to differentiate ~\emph{relevance matching} from~\emph{semantic matching}. \begin{enumerate} \item \textbf{Similarity matching signals vs. Exact matching signals:} In our ad-hoc retrieval task, although more complex metrics have also been proposed, the exact matching of query terms in documents is still the most important signal. Unlikely, NLP tasks need to detect semantically related words which can convey the same meaning even if they do not share any common word or phrases. This also clarifies why some traditional IR models, which are simply based on exact matching, e.g., BM25, can work fairly well for ad-hoc retrieval while other traditional NLP models cannot show a similar performance for NLP-related tasks. \item \textbf{Compositional meanings vs. Query term importance:} In the scope of NLP, it is useful to extract grammatical structures to capture compositional meaning rather than seeing sentences as a BoWs in the given text. On the other hand, in ad-hoc retrieval, queries are composed of mainly short and keyword based phrases without complex grammatical structures. Therefore, in our case it is crucial to take into account of term importance instead of grammatical structures. \item \textbf{Global matching requirements vs. Diverse matching requirements:} In the literature, there are various hypotheses about document length such as Verbosity Hypothesis and Scope Hypothesis. The Verbosity Hypothesis follows an assumption that a long document covers similar content but with more words. Conversely, the Scope Hypothesis considers a long document is composed of a number of unrelated appended short documents. Hence, in terms of the Verbosity Hypothesis, relevance matching might be global for the assumption that short documents have a concentrated topic, whereas based on the Scope Hypothesis, partial relevance, the relevance of different parts of the document to a query is necessary. On the other hand, semantic matching mostly requires global matching with the aim of inferring the semantic relations from the whole text. \\ Based on these important differences between relevance matching in ad-hoc retrieval and semantic matching in many NLP tasks, it is clear that we need to establish a deep model architecture which incorporates these differences into the model properly. Herein, previously proposed architectures seem to be deficient; thus a novel deep learning architecture specifically designed for relevance matching in ad-hoc retrieval, namely deep relevance matching model (DRRM), has been suggested. Note that the introduced architecture is akin to interaction-focused rather than representation-focused models since detailed matching signals are very crucial and they are inevitably lost in the latter group of models. \end{enumerate} \begin{figure}[!t] \centering \includegraphics[scale = 0.80]{Fig6.PNG} \caption{Architecture of DRMM} \label{fig:fig6} \end{figure} \underline{The Proposed Architecture:} The introduced model applies a joint deep architecture at the query term level over the local interactions between query and document terms for relevance matching. In this way, query term importance can be modelled and in the following steps, the contribution of each query term to the relevance score can be measured, hence different weights can be assigned to these terms, accordingly. Note that employing a joint deep architecture at the query term level is one important difference of the introduced model from existing interaction-focused models. Initially, based on term embeddings, local interactions between each query-document pair of terms are established. Then, for each query term, the variable-length local interactions are transformed into a fixed-length matching histogram. As a subsequent step based on the matching histogram, a feed forward matching network is employed to learn hierarchical matching patterns and a matching score is generated for each query term. Finally, the overall matching score is produced by aggregating the scores from each single query term with a term gating network in which the aggregation weights are computed. The proposed model architecture, DRMM is depicted in Figure~\ref{fig:fig6}. \paragraph{Experimental Results: } In this work, given the limited number of queries for each collection, 5-fold cross validation is conducted to avoid over-fitting. Mean Average Precision (MAP) is used for parameter optimization. For evaluation, the top-ranked 1,000 documents are compared using the three commonly used IR metrics, namely MAP, normalized discounted cumulative gain at rank 20 (nDCG@$20$), and precision at rank 20 (P@$20$). Statistical differences between state-of- the-art models are computed using the Fisher randomization test~\cite{smucker2007comparison}.\\ \begin{figure}[!t] \centering \includegraphics[scale = 0.83]{Table3.PNG} \caption{Comparison of different retrieval models over the Robust-04 collection. Significant improvement or degradation wrt QL is indicated (+/-) ($p-value < 0.05$).} \label{fig:fig7} \end{figure} In the evaluation part, two TREC collections are used for evaluation. However, we report the experimental results only for one of these datasets, namely Robust-04 collection in this report. In the scope of traditional retrieval baselines, we already mentioned BM25 and QL refers to query likelihood model based on Dirichlet smoothing~\cite{zhai2004study} which is one of the best performing language models. Results are displayed in Table~\ref{fig:fig7}. It can be concluded that all the representation-focused models perform significantly worse than the traditional retrieval models which demonstrates the unsuitability of these models for relevance matching. This is a very striking result that supports the paper's claim on the relevance/semantic matching difference. Please refer to the paper itself for comprehensive results and the related discussion. \begin{figure}[!t] \centering \includegraphics[scale = 0.83]{Fig7.PNG} \caption{Architecture of DeepRank} \label{fig:fig8} \end{figure} \begin{figure}[!t] \centering \includegraphics[scale = 0.83]{Table4.PNG} \caption{Performance comparison of different models on MQ2007. Significant improvement or degradation wrt DeepRank-CNN is denoted as (-) ($p-value < 0.05$).} \label{fig:fig9} \end{figure} \paragraph{Paper Review: DeepRank: A New Deep Architecture for Relevance Ranking in Information Retrieval~\cite{pang2017deeprank}} \paragraph{Motivation: } Existing deep IR models such as DSSM~\cite{huang2013learning} and C-DSSM~\cite{shen2014learning} generate ranking scores by directly applying neural networks, without a proper understanding of the relevance (i.e. differentiating semantic matching and relevance matching. Although the previous architecture, DRMM semantic matching has capability of distinguishing these two different matching problems, it does not explicitly model the relevance generation process and fails to capture important IR features such as passage retrieval intrinsic and proximity heuristics. \\ \paragraph{Method: } The proposed model aims to mimic relevance label generation steps applied by the human judgement process. According to this process, the relevance label generation comprises three steps: i) relevant locations are determined, ii) local relevances are determined, iii) local relevances are aggregated to output the relevance label. Initially, to extract the relevant contexts, a detection procedure is devised. Then, to detect the local relevances by using a convolutional neural network (CNN) or two-dimensional gated recurrent units (2D-GRU) as a measure network. Finally, an aggregation network with sequential integration and term gating mechanism is applied to produce a global relevance score. \\ Note that DeepRank as illustrated in Figure~\ref{fig:fig8}, was proposed by the same lab to alleviate the weaknesses of their previous model, DRMM. It seems that DeepRank well captures significant IR (relevance matching) characteristics that distinguish relevance matching from semantic matching, including exact/semantic matching signals, proximity heuristics, query term importance, and diverse relevance requirement. \paragraph{Experimental Results: } Extensive experiments are conducted to evaluate DeepRank against state-of-the-art models such as learning to rank methods, and existing deep learning models. For evaluation NDCG, Precision, and MAP metrics are used. \\ Experiments show that LETOR4.0 (MQ2007, MQ2008) benchmark and a large scale click-through data show that DeepRank can significantly outperform all the baseline methods. More specifically, in making comparison to learning to rank methods, DeepRank performs even better than these models, whereas other existing deep learning methods show much worse performance. Comparison results on one of the LETOR4.0 benchmark dataset, MQ2007 are displayed in Table~\ref{fig:fig9}. For comprehensive results, please refer to the evaluation part of the paper. \subsubsection{Click Graph Based Ranking} For LTR, in our last submodule we utilize click graph idea to obtain more and different type of information (if feasible) from the click-through logs. Note that in this submodule, we only refer to one main paper since it is the most recent and successful work in this area. \paragraph{Paper Review: Learning Query and Document Relevance from a Web-scale Click Graph~\cite{jiang2016learning}} \paragraph{Motivation: } Click-through logs contain rich and valuable information. However, the click information is sometimes noisy and its coverage is limited since there is a huge number of all possible relevant query-document pairs which leads to sparsity for the click-based features. The sparsity and noise problems affect the overall click-based feature quality negatively, especially for less popular (e.g. tail queries) queries. To overcome these problems, an effective way is to use click and content information simultaneously. For this reason, learning a vector representation for both queries and documents in the same semantic space is needed. \\ Previous state-of-the-art approaches represent queries/documents in the same space such as traditional methods, which learn low-rank vectors, or direct text matching methods like BM25 and the language models. However, prior methods have its own advantages, it has also some weaknesses. For instance, low rank embedding hurts interpretability and debuggability of the ranking function because individual dimension in the latent space is hard to interpret and direct text matching methods suffer from the lexical gap between queries and documents. Moreover, we need an approach for click-absent queries, i.e. queries which have never been observed in the search logs. \begin{figure}[!t] \centering \includegraphics[scale = 0.83]{Fig8.PNG} \caption{An example of click-through bipartite graph} \label{fig:fig10} \end{figure} \paragraph{Method: } To overcome all these challenges, the paper proposes a propagation approach to learn vector representation by using both content and click information. These vector representations can directly improve the retrieval performance for queries and documents that exist in the click logs, i.e. click-existing queries. A sample click graph is shown in Figure~\ref{fig:fig10}. \\ Furthermore, for click-absent queries and documents, a two-step vector estimation algorithm is proposed which utilizes partial information of the vectors in the bipartite graph that is already created by propagation. In this way, researchers aim to significantly improve the coverage of the vectors, which is specifically critical for long-tail queries in web-search, i.e. the queries containing keywords that are more specific and less common than other keywords. \begin{figure}[!t] \centering \includegraphics[scale = 0.83]{Fig9.PNG} \caption{An example of unit vector generation. (The black thin lines are the edge of the click graph, while the edges represented by the gray thick lines indicate the pseudo clicks between units and documents.)} \label{fig:fig11} \end{figure} \paragraph{Vector Propagation Algorithm: } The goal of this propagation algorithm is to learn the vector representation of queries and documents in the same semantic space (either the query or the document space). The algorithm starts from one side (query or document) and the vectors (query or document) are initialized with the content information and the vectors are propagated to their corresponding connected nodes on the side of the click graph. \\ Using bag-of-words model to generate the vector representations using query words to represent queries, and document titles to represent documents is a more intuitive way for vector generation. However, this procedure leads to the lexical gap between queries and documents. Thus, in the paper, researchers prefer to represent queries in query semantic space and documents in document semantic space. Note that co-clicks between queries and documents show the importance level of the propagating terms by weighting the vector representations. In this way, significant terms become more prominent while less informative terms are eventually filtered out. \\ Apart from these, in order to incorporate click-absent queries to the already established graph, the paper uses a unit vector generation algorithm that is shown in Figure~\ref{fig:fig11}. In this procedure, firstly queries and documents titles are broken down into different units (e.g., ngrams) and vector representations for each unit are learned by using the vectors that have been already learned from the click-existing queries/documents in the graph. Then, a weight score is learned for each unit by a regression model, and finally the vectors are estimated for the click-absent queries/documents by a linear combination of the unit vectors. Owing to this procedure, the click-absent queries/documents will be connected to the click graph through the unit vectors by utilizing the partial information in the already established click graph, even if the complete version of queries do not exist in the click-logs. In this way, high-quality representations are generated also for click-absent query/documents which substantially affects the retrieval performance of search engines in practice. \begin{figure}[!t] \centering \includegraphics{Table5.PNG} \caption{As an individual ranking model (Two-tailed t-test is done for paired data where each pair is VPCG \& VG QUERY and any of the other methods, and * indicates $p-value < 0.01$ for all tests.))} \label{fig:fig12} \end{figure} \begin{figure}[!t] \centering \includegraphics{Table6.PNG} \caption{As a feature (Two-tailed t-test is done for paired data where each pair is "Base + VPCG \& VG" and any of the other methods, and * indicates $p-value < 0.01$ for all tests.)))} \label{fig:fig13} \end{figure} \paragraph{Experimental Results: } Researchers establish the click-through from a major commercial search engine's search log. There are approximately 25 billion co-clicked query-document pairs, containing about 8 billion unique queries and 3 billion unique documents. This dataset was used as training set to build the graph. Then, for evaluation (i.e. for investigating if the relevance score learned by the proposed algorithm can help to improve ranking in a learning-to-rank framework), another dataset was used which is composed of 63k queries and 775k query-document pairs as training instances and 16k queries with 243k query-document pairs as test set. \\ The relevance score of each pair (``perfect", ``excellent", ``good", ``fair", ``bad") is annotated by human annotators. The evaluation is done in two distinct ways: i) the learned relevance score can be either used directly to rank documents, or ii) added to the feature vector in a learning-to-rank framework. You can find the results in Table~\ref{fig:fig12} and~\ref{fig:fig13} below. Results show that the proposed method helps to improve ranking results in both cases. \begin{figure}[!t] \centering \includegraphics{Fig10.PNG} \caption{Framework of the search over encrypted cloud data.} \label{fig:fig14} \end{figure} \subsection{Cloud Search} Our second module is Cloud Search and for this module, we also chose a comprehensive article for reference. However, this part of our project is the module which requires the least research effort in comparison to other project modules. Therefore, we have one referenced paper for the cloud module and only give an overview of the paper without mentioning any details of the approach. \paragraph{Paper Review: Achieving Efficient Cloud Search Services: Multi-Keyword Ranked Search over Encrypted Cloud Data Supporting Parallel Computing~\cite{fu2015achieving}} \paragraph{Overview: } Nowadays, cloud computing has become quite popular. A large amount of data outsourced to the cloud by data owners for the purpose of accessing the large-scale computing resources and economic savings. \\ For data protection, the sensitive data should be encrypted by the data owner before outsourcing and this leads to the fact that traditional and efficient plain-text keyword search technique be- comes useless. Therefore, researchers investigate how to design an efficient and effective searchable encryption scheme on cloud. You can see the overall framework in Figure~\ref{fig:fig14}. \subsection{Query Expansion \& Suggestion} ~\emph{Lexical chasm} between queries and document titles is the main obstacle for improving base relevance of a search engine. This is substantially rooted from two things: i) authors of queries and documents are different (e.g. diverse vocabulary usage), ii) insufficient knowledge of technical terms in the corresponding domain. On the light of these, we consider to alleviate the~\emph{semantic gap} problem in the~\emph{Query Expansion} sub-module to improve the retrieval performance even more, in addition to the core methods utilized in our first module, LTR. \subsubsection{Query Expansion} In this sub-module, we aim to expand a given query with a selected set of terms to increase the coverage of the query. In selecting the terms, we can use three proposed methods which utilize three different word embeddings, word2vec~\cite{mikolov2013efficient}, FastText~\cite{joulin2016bag}, and GloVe~\cite{pennington2014glove}. We can combine the outputs of these three methods by ensemble learning (e.g. majority voting), for instance. \paragraph{Paper Review: Query Expansion Using Word Embeddings~\cite{kuzi2016query}} \paragraph{Motivation: } Query expansion may help on improving retrieval performance of a search engine. For this, suitable terms should be selected to employ query expansion in a proper way, otherwise, it may deteriorate the retrieval performance by including irrelevant documents in returning document set. \paragraph{Method: } In this paper, researchers propose two term scoring methods for term selection. The main idea is to choose terms that are semantically related to the query by using word2vec's cbow em- bedding approach applied over the entire search corpus. After computing scores and candidate terms are determined, the v terms assigned the highest score by a method M are used for query expansion. Brief description of these M scoring methods are as follows. \begin{itemize} \item \underline{The centroid method:} In this approach, researchers leverage the observation of adding word2vec vectors representing terms that constitute an expression often yields a vector that semantically corresponds to the expression. Therefore, selecting procedure is employed by comparing cosine-similarity of a specific term's word2vec score in the collection and the corresponding query as a whole. \item \underline{Fusion-based methods:} Differently from the Cent method, in this approach, for each query term, $q_i$, a list $L{q_i}$ of its n most similar terms t in the corpus according to cos($q_i$; t). Then, cosine-similarity scores are used to compute softmax-normalized probabilities. After that, the resulting term lists are fused using Comb-SUM, CombMNZ and CombMAX~\cite{fox1994combination}. \end{itemize} \paragraph{Experimental Results: } In evaluation, several TREC datasets are used as benchmark datasets. Results show statistically significant results, thus the proposed idea can be used to improve the retrieval performance of a search engine by integrating also with other word embedding methods. \\ \paragraph{Paper Review: Using Word Embeddings for Automatic Query Expansion~\cite{roy2016using}} \paragraph{Motivation: } The main goal of this work is again to find suitable terms to expand a query, i.e., increasing the coverage of the query without including irrelevant terms. \paragraph{Method: } For selecting terms, researchers devise a query expansion technique, where related terms to a query are picked using K-nearest neighbour approach. More specifically, in the paper, three kNN-based term selection methods are proposed as pre-retrieval kNN, post-retrieval kNN, pre-retrieval incremental kNN approaches. For an elaborate explanation of these methods, please refer to the paper. \paragraph{Experimental Results: } In the experimental results, the proposed method is evaluated on the standard ad-hoc task using both TREC collection and TREC web collection. The results indicate that, as an expansion method, the incremental method is generally safe; it produces performance improvements for most of the queries and for only a few queries, it affects the performance badly. Therefore, this method can be integrated to our query expansion scheme, as well.\\ \paragraph{Paper Review: Query Expansion with Locally-Trained Word Embeddings~\cite{diaz2016query}} \paragraph{Motivation: } Commonly used word embeddings, word2vec and GloVe, when trained globally underperform corpus and query-specific embeddings in the context of query expansion and retrieval tasks. Hence, in this paper researchers investigate the effect of local embeddings on query expansion. \paragraph{Method: } In order to generate local word embeddings, learning embeddings on topically-constrained corpora, instead of large topically-unconstrained corpora to utilize domain-specific information. For this purpose, in this work, a language modelling approach is adopted to produce a query-specific set of topical documents. \paragraph{Experimental Results: } In the evaluation part, TREC datasets and ClueWeb 2009 corpora are used and the evaluatin metric is chosen as NDCG@$10$. The comparison is done with the baseline method of query-likelihood and results show that the proposed query expansion approach by using local word embeddings outperform the baseline on benchmark datasets. Based on this, in our query expansion scheme, we may give a try to local word embeddings, if feasible.\\ \subsubsection{Query Suggestion} The main goal of this submodule is to improve user experience, i.e., enabling users to reach their searching information in a more accurate and quicker way. In the context of query suggestion, there are two papers that can be utilized in our searching platform. These two articles~\cite{liu2017query, mei2008query} differ only in small details, therefore we will only mention about the first paper that contains the core idea. \paragraph{Query Suggestion Using Hitting Time~\cite{mei2008query}} \paragraph{Motivation: } This paper aims to generate query suggestions while ensuring semantic consistency with the original query not to lose context information. \paragraph{Method: } In this work, finding query suggestion procedure is mainly as follows. Initially, a bipartite graph is established on click-logs and it is used for query expansion. Then on the graph, hitting time from a given query to other queries are modelled by random walking for finding candidate query suggestions. \paragraph{Experimental Results: } Results show that this technique is beneficial for query suggestion and can be incorporated to our platform to improve user search experience. We selected this work for query suggestion, because of two reasons: i) it is one of the most comprehensive and successful method in this area, and ii) for efficiency purposes, since we already construct a bipartite-graph on click-through logs and we can use the same graph also for query suggestion.\\ \section{Patents} \subsection{US20160004776 A1, 2016~\cite{cloud2016}} In this patent, cascading searching is used to locate a desired person in a social media ecosystem. The social media search system is provided on cloud and we utilize this patent to scale our search service on a cloud platform. \subsection{US7689520B2, 2010~\cite{burges2010machine}} This patent proposes a machine learning system to rank a set of documents by using differentiable parameters. The ranking will be optimized according to a cost module that computes cost scores on a pair of examples. This patent helps on generating letor-based ranking models to improve our system.
{'timestamp': '2021-12-30T02:23:06', 'yymm': '2112', 'arxiv_id': '2112.14444', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14444'}
arxiv
\section{Introduction} \vspace{-2mm} \label{sec:intro} Generative Adversarial Networks (GANs) \citep{goodfellow2014generative} are an extremely popular class of generative models used for text and image generation in various fields of science and engineering, including biomedical imaging~\citep{yi2019generative,nie2018medical,wolterink2017generative}, autonomous driving~\citep{hoffman2018cycada,zhang2018deeproad}, and robotics~\citep{rao2020rl,bousmalis2018using}. However, GANs are widely known to be prone to \textit{mode collapse}, which refers to a situation where the generator only samples a few modes of the real data, failing to faithfully capture other more complex or less frequent categories. While the mode collapse problem is often overlooked in text and image generation tasks, and even traded off for higher realism of individual samples~\citep{karras2019style,brock2018large}, dropping infrequent classes may cause serious problems in real-world problems, in which the infrequent classes represent important anomalies. For example, a collapsed GAN can produce racial/gender biased images~\citep{Menon_2020_CVPR}.\blfootnote{* Equal technical contribution. $\dagger$ Work done during internship.} Moreover, mode collapse causes instability in optimization, which can damage both diversity and the realism of individual samples of the final results. As an example, we visualized the training progression of the vanilla GAN~\citep{goodfellow2014generative} for a simple bimodal distribution in the top row of Figure~\ref{fig:oscillation}. At collapse, the discriminator conveniently assigns high realism to the region unoccupied by the generator, regardless of the true density of real data. This produces a strong gradient for the generator to move its samples toward the dropped mode, swaying mode collapse to the other side. So, the discriminator loses its ability to detect fake samples it was previously able to, such as point \textbf{X}\tikz\draw[red,fill=red] (0,5) circle (.3ex);. The oscillation continues without convergence. We observe that the mode collapse problem is closely related to Catastrophic Forgetting~\citep{mccloskey1989catastrophic, mcclelland1995there, ratcliff1990connectionist} in continual learning. A promising line of works~\citep{sidetuning2019, NIPS2019_9429, rusu2016progressive, fernando2017pathnet} tackle the problem in the supervised learning setting by instantiating multiple predictors, each of which takes charge in a particular subset of the whole distribution. We also tackle the problem of mode collapse in GAN by tracking the severity of Catastrophic Forgetting by storing a few exemplar data during training, spawning an additional discriminator if forgetting is detected, Figure~\ref{fig:oscillation}. The key idea is that the added discriminator is left intact unless the generator recovers from mode dropping of that sample, essentially sidestepping catastrophic forgetting. We show that our proposed approach based on adaptive addition of discriminators can be added to any of the existing GAN frameworks, and is most effective in preventing mode collapse. Furthermore, the improved stability of training boosts the standard metrics on popular GAN frameworks. To summarize, our contributions are: \emph{First}, we propose a novel GAN framework, named Adaptive Multi Adversarial Training (AMAT), that effectively prevents Catastrophic Forgetting in GANs by spawning additional discriminators during training. \emph{Second}, we also propose a computationally efficient synthetic data generation procedure for studying mode collapse in GANs that allows visualizing high dimensional data using normalizing flows. We show that mode collapse occurs even in the recent robust GAN formulations. \emph{Third}, our method can be plugged into any state-of-the-art GAN frameworks and still improve the quality and coverage of the generated samples. \begin{figure*} \centering \includegraphics[trim={0 0 0 10},clip,width=0.90\textwidth]{figs/totalcomb2.png} \vspace{3mm} \caption{\textbf{Visualizing training trajectories}: Distribution of real (green dots) and fake (blue dots) over the course of vanilla GAN (top row) and our method (the second row and below). The background color indicates the prediction heatmap of the discriminator with blue being fake and warm yellow being real. Once the vanilla GAN falls into mode collapse (top row), it ends up oscillating between the two modes without convergence. Also, the discriminator's prediction at point X oscillates, indicating catastrophic forgetting in the discriminator. AMAT algorithm adapts to the need, and a new discriminator is spawned during training which effectively learns the forgotten mode, guiding the GAN optimization toward convergence. } \label{fig:oscillation} \vspace{-3mm} \end{figure*} \vspace{-5mm} \section{Related Works} \vspace{-2mm} \label{sec:related} Previous works have focused on independently solving either catastrophic forgetting in supervised learning or mode collapse during GAN training. In this section we review these works in detail and discuss our commonalities and differences. \vspace{-2mm} \subsection{Mitigating Mode Collapse in GANs} Along with advancement in the perceptual quality of images generated by GAN~\citep{miyato2018spectral,karras2019style,brock2018large,karras2020analyzing}, a large number of papers~\citep{durugkar2016generative,metz2016unrolled,arjovsky2017wasserstein,srivastava2017veegan,nguyen2017dual,lin2018pacgan,MeschederICML2018,karras2019style} identify the problem of mode collapse in GANs and aim to mitigate it. However mode collapse was seen as a secondary symptom that would be naturally solved as the stability of GAN optimization progresses~\citep{arjovsky2017wasserstein,MeschederICML2018,bau2019seeing}. To explicitly address mode collapse, Unrolled GAN~\citep{metz2016unrolled} proposes an unrolled optimization of the discriminator to optimally match the generator objective, thus preventing mode collapse. VEEGAN~\citep{srivastava2017veegan} utilizes the reconstruction loss on the latent space. PacGAN~\citep{lin2018pacgan} feeds multiple samples of the same class to the discriminator when making the decisions about real/fake. In contrast, our approach can be plugged into existing state-of-the-art GAN frameworks to yield additional performance boost. \vspace{-4mm} \subsection{Multi-adversarial Approaches} \vspace{-1mm} The idea of employing more than one adversarial network in GANs to improve results has been explored by several previous works independent of the connection to continual learning and catastrophic forgetting. MGAN~\citep{hoang2018mgan} uses multiple generators, while D2GAN~\citep{nguyen2017dual} uses two discriminators, and GMAN~\citep{durugkar2016generative} and MicrobatchGAN~\citep{mordido2020microbatchgan} proposed a method with more than two discriminators that can be specified as a training hyperparameter beforehand. However, all previous works require the number of discriminators to be fixed beforehand, which is a major drawback since it depends on several intricate factors such as training dynamics, data distribution complexity, model architecture, initialization hyper-parameters etc. and is expensive and difficult to approximate even with several runs of the algorithm. In contrast, noting by the connection of multi-adversarial training to parameter expansion approaches to catastrophic forgetting, we propose an \textit{adaptive} method that can add discriminators incrementally during training thus achieving superior performance than existing works both on data quality metrics as well as overall computational effort. \begin{table*}[t] \resizebox{\textwidth}{!}{ \begin{tabular}{c|c|c|c|c|c||c} \begin{tabular}{c} $g(\mathbf{z}) = $ \end{tabular} & ${1}$ & \begin{tabular}[c]{@{}c@{}} $\mathbf{A}_{392 \times 2}$ \\ \end{tabular} & \begin{tabular}[c]{@{}c@{}} $\mathbf{z}$ \end{tabular} & \begin{tabular}[c]{@{}c@{}} MLP \end{tabular} & \begin{tabular}[c]{@{}c@{}} MLP, $\mathbf{A}_{392 \times 2}$ \end{tabular} & \begin{tabular}{@{}c@{}} \small{MNIST} \end{tabular} \\[1ex] \hline \begin{tabular}[c]{@{}c@{}} Label\\ \end{tabular} & {\fontfamily{lmtt}\selectfont Level I} & {\fontfamily{lmtt}\selectfont Level II} & {\fontfamily{lmtt}\selectfont Level III} & {\fontfamily{lmtt}\selectfont Level IV} & {\fontfamily{lmtt}\selectfont Level V} & - \\ \hline \begin{tabular}[c]{@{}c@{}} \small{GAN-NS \citep{goodfellow2014generative}}\\ \end{tabular} & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \cmark & \cmark \enskip \big\vert \enskip \cmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{WGAN} \citep{arjovsky2017wasserstein} \\ \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \cmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{Unrolled GAN} \citep{metz2016unrolled} \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{D2GAN} \citep{nguyen2017dual} \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{GAN-NS + AMAT} \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \hline \end{tabular} } \vspace{2mm} \caption{\xmark \hspace{0.1mm} indicates that the generator could effectively learn all the data modes, while \cmark \hspace{0.1mm} means \textit{despite best efforts with tuning} the training suffers from mode collapse (more than a quarter of data modes dropped). We show results with the SGD (left) \& ADAM (right) optimizers. MNIST results with ADAM optimizer are provided for reference. We observe that MNIST is a relatively easy dataset, falling between {\fontfamily{lmtt}\selectfont Level I} and {\fontfamily{lmtt}\selectfont II} in terms of complexity.} \label{tab:synthetic} \vspace{-4mm} \end{table*} \vspace{-4mm} \subsection{Overcoming Catastrophic Forgetting in GAN} \vspace{-1mm} Methods to mitigate catastrophic forgetting can be categorized into three groups: a) regularization based methods~\citep{kirkpatrick2017overcoming} b) memory replay based methods~\citep{rebuffi2017icarl} c) network expansion based methods~\citep{zhang2018deeproad, NIPS2019_9429}. Our work is closely related to the third category of methods, which dynamically adds more capacity to the network, when faced with novel tasks. This type of methods, adds \emph{plasticity} to the network from new weights (fast-weights) while keeping the \emph{stability} of the network by freezing the past-weights (slow-weights). Additionally, we enforce stability by letting a discriminator to focus on a few set of classes, not by freezing its weights. The issue of catastrophic forgetting in GANs has been sparsely explored before. \citet{chen2018self} and \citet{tran2019self} propose a self-supervised learning objective to prevent catastrophic forgetting by adding new loss terms. \citet{liang2018generative} proposes an online EWC based solution to tackle catastrophic forgetting in the discriminator. We propose a prominently different approach based on parameter expansion rather than regularization. While the regularization based approaches such as \citet{liang2018generative} attempt to retain the previously learnt knowledge by constrained weight updates, the parameter expansion approaches effectively sidestep catastrophic forgetting by freezing previously encoded knowledge. \citet{thanhcatastrophic} also discuss the possibility of catastrophic forgetting in GAN training but their solution is limited to theoretical analyses with simplistic proposals such as assigning larger weights to real samples and optimizing the GAN objective with momentum. Practically, we observed that their method performs worse than a plain vanilla DCGAN on simple real world datasets like CIFAR10. In contrast, our method leverages insights from continual learning and has a direct connections to prevalent parameter expansion approaches in supervised learning. We benchmark extensively on several datasets and state-of-the-art GAN approaches where our method consistently achieves superior results to the existing methods. \vspace{-7mm} \section{Proposed Method} \vspace{-2mm} In this section, we first describe our proposed data generation procedure that we use as a petri dish for studying mode collapse in GANs. The procedure uses random normalizing flows for simultaneously allowing training on complex high dimensional distributions yet being perfectly amenable to 2D visualizations. Next, we describe our proposed Adaptive Multi Adversarial Training (AMAT) algorithm that effectively detects catastrophic forgetting and spawns a new discriminator to prevent mode collapse. \vspace{-5mm} \subsection{Synthetic Data Generation with Normalizing flows} \vspace{-1mm} Mode dropping in GANs in the context of catastrophic forgetting of the discriminator is a difficult problem to investigate using real datasets. This is because the number of classes in the dataset cannot be easily increased, the classes of fake samples are often ambiguous, and the predictions of the discriminator cannot be easily visualized across the whole input space. In this regard, we present a simple yet powerful data synthesis procedure that can generate complex high dimensional multi-modal distributions, yet maintaining perfect 2-D visualization capabilities. Samples from a 2-D Gaussian distribution are augmented with biases and subjected to an invertible normalizing flow~\citep{karami2019invertible} parameterized by well conditioned functions $g_i: \mathbb{R}^{d^0_i} \rightarrow \mathbb{R}^{d^1_i}$. This function can be followed by a linear upsampling transformation parameterized by a $d^1_i \times d^0_{i+1}$ dimensional matrix $A^i$ (Algorithm \ref{algo:synthetic}). The entire transform is deliberately constructed to be a bijective function so that every generated sample in $\hat{y} \in \mathbb{R}^D$ can be analytically mapped to $\mathbb{R}^2$, allowing perfect visualization on 2D space. Furthermore, by evaluating a dense grid of points in $\mathbb{R}^2$, we can understand discriminator's learned probability distribution on $\mathbf{z}$ manifold as a heatmap on the 2D plane. This synthetic data generation procedure enables studying mode collapse in a controlled setting. This also gives practitioners the capability to train models on a chosen data complexity with clean two-dimensional visualizations of both the generated data and the discriminator's learnt distribution. This tool can be used for debugging new algorithms using insights from the visualizations. In the case of mode collapse, a quick visual inspection would give the details of which modes face mode collapse or get dropped from discriminator's learnt distribution. \vspace{-2mm} \subsection{Adaptive Multi Adversarial Training} \vspace{-1mm} Building upon the insight on relating catastrophic forgetting in discriminator to mode collapse in generator, we propose a multi adversarial generative adversarial network training procedure. The key intuition is that the interplay of catastrophic forgetting in the discriminator with the GAN minimax game, leads to an oscillation generator. Thus, as the generator shifts to a new set of modes the discriminator forgets the learnt features on the previous modes. \begin{minipage}[b]{.46\textwidth} \begin{algorithm}[H] \DontPrintSemicolon \SetNoFillComment \begin{algorithmic} \STATE \textbf{Input:} Mean $\{\mu_i\}_{i=1}^K$ and standard deviation $\{\sigma_i\}_{i=1}^K$ for initialization, $\{g_i\}_{i=1}^{L}$ well conditioned $\mathbb{R}^2 \rightarrow \mathbb{R}^2$ functions \STATE Sample weights ${\bm{w}} \sim \text{Dirichlet}(K)$ \\ \tcc{Sample from 2D gaussian mixture} \STATE $\mathbf{x}_{2D} \sim \Sigma_{i = 1}^N w_i \mathcal{N}( \mu_i, \sigma_i)$ \STATE $\mathbf{x}^0_{2D} = \Big[[x^0_{2D}; {1}], [x^1_{2D}; {1}] \Big] $ \newline \tcc*{Randomly Init Normalizing Flow} \FOR{$k = 1$ to $k = K$} \IF{k is even} \STATE ${\bm{x}}^k = \big[{\bm{x}}^{k}_0, {\bm{x}}^{k}_1 \cdot g_k({\bm{x}}^k_0)\big] $ \ELSE \STATE ${\bm{x}}^k = \big[{\bm{x}}^{k}_0 \cdot g_k({\bm{x}}^k_1), {\bm{x}}^{k}_1 \big] $ \ENDIF \ENDFOR \end{algorithmic} \caption{Synthetic Data Generation} \label{algo:synthetic} \end{algorithm} \vspace{-4mm} \begin{algorithm}[H] \DontPrintSemicolon \SetNoFillComment \caption{DSPAWN: Discriminator \mbox{Spawning} Routine} \label{algo:spawn} \begin{algorithmic} \STATE \textbf{Require:} Exemplar Data $\{{\bm{e}}\}_{i=1}^m$ \STATE \textbf{Input:} Discriminator set $\displaystyle {\mathbb{D}} = \{f_w^{i}\}_{i=1}^K$ \newline \tcc*{Check forgetting on exemplars} \FOR{$i = 1$ to $i = m$} \STATE ${\bm{s}}[k] \leftarrow f_w^{k}({\bm{e}}_i) \ \forall\ k\ \in \{1 \dots K\}$\; \IF{ $K *\max({\bm{s}}) > \alpha_t * \sum_k{\bm{s}}[k]$} \STATE Initialize $f_w^{K+1}$ with random weights $w$ \newline \tcc*{Spawn a new discriminator} \STATE Initialize random weight $w^{K+1}$ \STATE $\displaystyle {\mathbb{D}} \leftarrow \{f_w^{i}\}_{i=1}^K \bigcup f_w^{K+1}$ \STATE \textbf{break} \ENDIF \ENDFOR \STATE \textbf{return} Discriminator Set $\displaystyle {\mathbb{D}}$ \end{algorithmic} \end{algorithm} \end{minipage}\hfill \begin{minipage}[b]{.48\textwidth} \begin{algorithm}[H] \caption{A-MAT: Adaptive Multi-Adversarial Training} \label{algo:multi} \DontPrintSemicolon \begin{algorithmic} \STATE \textbf{Require: }${\bm{w}}^{i}_0$, ${\bm{\theta}}_0$ initial discriminator \& generator params, greediness param $\epsilon$, $\{T_k\}$ spawn warmup iteration schedule \STATE $\displaystyle {\mathbb{D}} \leftarrow \{f_w^{0}\}$\; \WHILE{${\bm{\theta}}$ has not converged} \STATE Sample $\{{\bm{z}}^{(i)}\}_{i=1}^B \sim p(z)$ \STATE Sample $\{{\bm{x}}^{(i)}\}_{i=1}^B \sim \mathbb{P}_r$ \STATE Sample $\{\sigma_1(i)\}_{i=1}^B \sim \text{Uniform}(1, K)$ \STATE Sample $\{\alpha(i)\}_{i=1}^B \sim \text{Bernoulli}(\epsilon)$ \newline \tcc{Loss weights over discriminators} \STATE Sample weights ${\bm{m}} \sim \text{Dirichlet}(K)$ \STATE $\hat{\bm{x}}^{(i)} \leftarrow g_\theta({\bm{z}}^{(i)}) $ \STATE $\sigma_2(i) \leftarrow \argmin_{k}f_w^{k}(\hat{\bm{x}}^{(i)})$ \newline \tcc*{Discriminator responsible for $\hat{x}^{(i)}$} \STATE $\sigma_{z}(i) \leftarrow \alpha(i) \sigma_1(i) + (1 - \alpha(i)) \sigma_2(i)$ \newline \tcc*{Discriminator responsible for $x^{(i)}$} \STATE $\sigma_x(i) \leftarrow \sigma_1(i)$ \newline \tcc*{Training Discriminators} $L_{w} \leftarrow \sum_{i=1}^B [f_w^{\sigma_{x}(i)}({\bm{x}}_i) - 1]^{-} - [f_w^{\sigma_{z}(i)}(\hat{\bm{x}}_i) + 1]^+$ \FOR{$k = 1$ to $k = \vert \displaystyle {\mathbb{D}} \vert$} \STATE $w^k \leftarrow \text{ADAM}(L_{w})$ \ENDFOR \newline \tcc*{Training Generator} \STATE $s[k] \leftarrow \sum_{i=1}^B f_w^{k}(\hat{\bm{x}}^{(i)}) \ \forall\ k\ \in \{1 \dots \vert \displaystyle {\mathbb{D}} \vert\}$\newline \tcc*{Weighed mean over discriminators} \STATE $L_{\theta} \leftarrow \text{sort}({\bm{m}}) \cdot \text{sort}(s) $ \STATE $\theta \leftarrow \text{ADAM}(L_{\theta})$\; \IF{more than $T_t$ warm-up iterations since the last spawn} \STATE $\displaystyle {\mathbb{D}} \leftarrow \text{DSPAWN}(\{f_w^{i}\})$ \ENDIF \ENDWHILE \end{algorithmic} \end{algorithm} \vspace{-3mm} \end{minipage} However if there are multiple discriminators available, each discriminator can implicitly \emph{specialize} on a subset of modes. Thus even if the generator oscillates, each discriminator can remember their own set of modes, and they will not need to move to different set of modes. This way we can effectively \emph{sidestep} forgetting and ensure the networks do not face significant distribution shift. A detailed version of our proposed method is presented in Algorithm \ref{algo:multi}. \newline \newline \textbf{Spawning new discriminators}: We initialize the AMAT training Algorithm~\ref{algo:multi} with a regular GAN using just one discriminator. We also sample a few randomly chosen exemplar data points with a maximum of one real sample per mode, depending on dataset complexity. The exemplar data points are used to detect the presence of catastrophic forgetting in the currently active set of discriminators $\displaystyle {\mathbb{D}}$ and spawn a new discriminator if needed. Specifically (Algorithm \ref{algo:spawn}), we propose that if \emph{any} discriminator among $\displaystyle {\mathbb{D}}$ has an unusually high score over an exemplar data point ${\bm{e}}_i$, this is because the mode corresponding to ${\bm{e}}_i$ has either very poor generated samples or has been entirely dropped. In such a situation, if training were to continue we risk catastrophic forgetting in the active set $\displaystyle {\mathbb{D}}$, if the generator oscillate to near ${\bm{e}}_i$. This is implemented by comparing the $\max$ score over $\displaystyle sD$ at ${\bm{e}}_i$ to the average score over $\displaystyle {\mathbb{D}}$ and spawning a new discriminator when the ratio exceeds $\alpha_t (> 1)$. Further, we propose to have $\alpha_t (> 1)$ a monotonically increasing function of $| \displaystyle {\mathbb{D}}|$, thus successively making it harder to spawn each new discriminator. Additionally, we use a warm-up period $T_t$ after spawning each new discriminator from scratch to let the spawned discriminator train before starting the check over exemplar data-points. \newline \newline \noindent \textbf{Multi-Discriminator Training: } We evaluate all discriminators in $\displaystyle {\mathbb{D}}$ on the fake samples but do not update all of them for all the samples. Instead, we use the discriminator scores to assign responsibility of each data point to only one discriminator. \newline \newline \noindent \textbf{Training over fake samples}: We use an $\epsilon$-greedy approach for fake samples where the discriminator with the lowest output score is assigned responsibility with a probability $1 - \epsilon$ and a random discriminator is chosen with probability $\epsilon$. \newline \newline \noindent \textbf{Training over real samples}: The discriminator is always chosen uniformly randomly thus we slightly prefer to assign the same discriminator to the fake datapoints from around the same mode to ensure that they do not forget the already learnt modes and switch to another mode. The random assignment of real points ensure that the same preferentially treated discriminator also gets updated on real samples. Further for optimization stability, we ensure that the real and fake sample loss incurred by each discriminator is roughly equal in each back-propagation step by dynamically reweighing them by the number of data points the discriminator is responsible for. We only update the discriminator on the losses of the samples they are responsible for. While it may seem that adding multiple discriminators makes the procedure expensive, in practice the total number of added discriminator networks never surpass three for the best results. It is possible to change the hyperparameters to allow a large number of discriminators but that results in sub-optimal results and incomplete training. The optimal hyperparameter selection is explained in the Appendix for each dataset. Further, the additional discriminators get added during later training stages and are not trained from the start, saving compute in comparison to prior multi-adversarial works which train all the networks from the beginning. Also, unlike AdaGAN \citep{tolstikhin2017adagan} and similar Boosted GAN models that need to store multiple Generators post training, the final number of parameters required during inference remains unchanged under AMAT . Thus the inference time remains the same, but with enhanced mode coverage and sample diversity. Unlike \citep{tolstikhin2017adagan}, our discriminator addition is adaptive, i.e. discriminators are added during the training thus being more efficient. \newline \newline \noindent \textbf{Generator Training:} We take a weighted mean over the discriminators scores on the fake datapoints for calculating the generator loss. At each step, the weights each discriminator in $\displaystyle {\mathbb{D}}$ gets is in decreasing order of its score on the fake sample. Hence, the discriminator with the lowest score is given the most weight since it is the one that is currently specializing on the mode the fake sample is related to. In practice, we sample weights randomly from a Dirichlet distribution (and hence implicitly they sum to $1$) and sort according to discriminator scores to achieve this. We choose soft weighing over hard binary weights because since the discriminators are updated in an $\epsilon$ greedy fashion, the discriminators other than the one with the best judgment on the fake sample might also hold useful information. Further, we choose the weights randomly instead of fixing a chosen set to ensure AMAT is more deadset agnostic since the number of discriminator used changes with the dataset complexity so does the number of weights needed. While a suitable function for generating weights can work well on a particular dataset, we found random weights to work as well across different settings. \vspace{-3mm} \section{Results} \vspace{-3mm} \label{sec:results} We test our proposed method on several synthetic and real datasets \& report a consistent increase in performance on GAN evaluation metrics such as Inception Score \citep{salimans2016improved} and Frech\'et Inception Distance \citep{heusel2017gans} with our proposed AMAT. We also showcase our performance in the GAN fine-tuning regime with samples on the CUB200 dataset \citep{WelinderEtal2010} which qualitatively are more colorful and diverse than an identical BigGAN without AMAT (Figure \ref{fig:cub200}). \begin{table*}[t] \resizebox{\textwidth}{!} \begin{tabular}{ccccc|c c} \toprule & GAN & UnrolledGAN & D2GAN & RegGAN & DCGAN & with AMAT \\ \midrule \# Modes covered & $628.0 \pm 140.9$ & $817.4 \pm 37.9$ & $1000 \pm 0.0$ & $ 955.5\pm18.7$ & $849.6\pm 62.7$ & $\mathbf{1000 \pm 0.0}$ \\ KL (samples $\Vert$ data) & $2.58\pm 0.75$ & $1.43 \pm 0.12$ & $0.080 \pm 0.01$ & $0.64 \pm 0.05$ & $0.73\pm0.09$ & $0.078\pm0.01$ \\ \bottomrule \end{tabular} } \vspace{3mm} \caption{\textbf{Quantitative Results on the Stacked MNIST dataset}: Applying our proposed adaptive multi adversarial training (AMAT) procedure to a simple DCGAN achieves perfect mode coverage, better than many existing methods for mode collapse.} \label{tab:stacked} \end{table*} \begin{table*}[t] \smaller \resizebox{\textwidth}{!}{ \begin{tabular}{c| cc|cc|cc} \toprule & & & GAN-NS & AMAT + & & AMAT + \\ Model & D2GAN & MicrobatchGAN & w/ ResNet & GAN-NS & DCGAN & DCGAN \\ \midrule IS & $7.15 \pm 0.07$ & $6.77$ & $6.7 \pm 0.06$ & $\mathbf{8.1 \pm 0.04}$ & $6.03\pm0.05$ & $\mathbf{6.32\pm0.06}$ \\ FID & - & - & $28.91$ & $\mathbf{16.35}$ & $33.42$ & $\mathbf{30.14}$ \\ \midrule & WGAN-GP & AMAT + & &AMAT + & & AMAT + \\ Model & w/ ResNet & WGAN-GP & SN-GAN & SN-GAN & BigGAN & BigGAN \\ \midrule IS & $7.59\pm0.10$ & $\mathbf{7.80\pm0.07}$ &$ 8.22\pm0.05$ &$\mathbf{8.34\pm0.04}$& $9.22$ & $\mathbf{9.51\pm0.06}$ \\ FID & $19.2$ & $\mathbf{17.2}$ &$14.21$ &$\mathbf{13.8}$ & $8.94$ & $\mathbf{6.11}$ \\ \bottomrule \end{tabular} } \vspace{3mm} \centering \caption{\textbf{Quantitative Results on CIFAR10}: We benchmark AMAT against several other multi-adversarial baselines as well as on several GAN architectures across all of which we observe a consistent performance increase.} \label{tab:cifar} \end{table*} \vspace{-3mm} \subsection{Synthetic Data} \vspace{-1mm} We utilize the proposed synthetic data generation procedure with randomly initialized normalizing flows to visualize the training process of a simple DCGAN \citep{radford2015unsupervised}. Figure \ref{fig:oscillation} visualizes such a training process for a simple bimodal distribution. Observing the pattern of generated samples over the training iteration and the shifting discriminator landscape, we note a clear mode oscillation issue present in the generated samples driven by the shifting discriminator output distribution. Focusing on a single fixed real point in space at any of the modes, we see a clear oscillation in the discriminator output probabilities strongly indicating the presence of catastrophic forgetting in the discriminator network. \noindent \textbf{Effect of Data Complexity on Mode Collapse}: We use the flexibility in choosing transformations $g_i$ to generate datasets of various data distribution complexities as presented in Table $\ref{tab:synthetic}$. Choosing $g(z)$ with successively more complicated transformations can produce synthetic datasets of increasing complexity, the first five of which we roughly classify as {\fontfamily{lmtt}\selectfont Levels}. The {\fontfamily{lmtt}\selectfont Levels} are generated by using simple transforms such as identitym constant mapping, small Multi layer perceptrons and well conditioned linear transforms ($\mathbf{A}$). On this benchmark, we investigate mode collapse across different optimizers such as SGD \& ADAM \citep{kingma2014adam} on several popular GAN variants such as the non-saturating GAN Loss (GAN-NS) \citep{goodfellow2014generative}, WGAN \citep{arjovsky2017wasserstein} and also methods targeting mitigating mode collapse specifically such as Unrolled GAN \citep{metz2016unrolled} and D2GAN \citep{nguyen2017dual}. We show results of our proposed AMAT training procedure with a simple GAN-NS, which matches performance with other more complicated mode collapse specific GAN architectures, all of which are robust to mode collapse up to {\fontfamily{lmtt}\selectfont Level IV}. In practice we find all benchmarked methods to collapse at {\fontfamily{lmtt}\selectfont Level V}. Thus, in contrast to other simple datasets like MNIST~\citep{lecun1998mnist}, Gaussian ring, or Stacked MNIST~\citep{metz2016unrolled}, the complexity of our synthetic dataset can be arbitrarily tuned up or down to gain insight into the training and debugging of GAN via visualizations. \begin{table*}[t] \vspace{-2mm} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c| ccccc| c} \toprule Effect & Large $|\displaystyle {\mathbb{D}}|$ & Spawn too late & Greedy $\displaystyle \nabla$D & Random for fake & $\mathbf{1}$-hot weight & Proposed \\ Ablation & Small $\alpha$, Short $T_t$ & Long $T_t$ schedule & $\epsilon = 0$ & $\epsilon$-greedy for real & vector ${\bm{m}}$ & Method \\ \midrule IS & $8.83 \pm 0.04$ & $9.28 \pm 0.08$ & $9.31 \pm 0.06$ & $8.95 \pm 0.04$ & $9.25 \pm 0.05$ & $9.51 \pm 0.06$ \\ FID & $14.23$ & $9.37$ & $8.6$ & $12.5$ & $9.25$ & $6.11$ \\ \bottomrule \end{tabular} } \vspace{3mm} \caption{\textbf{BigGAN + AMAT Ablations on CIFAR10} (A) A spawning condition with small $\alpha$ and short warmup schedule that leads to large number of discriminators (>$7$) (B) Long warm-up schedules that spawn new discriminators late into training (C) A greedy strategy for assigning responsibility of fake samples ($\epsilon = 0$) (D) Flipping the data splitting logic with responsibilities of fake samples being random and of real being $\epsilon$-greedy (E) Choosing the discriminator with lowest score for updating Generator instead of soft random weighting.} \vspace{-2mm} \label{tab:ablations} \end{table*} \begin{figure*} \centering \begin{subfigure \centering \includegraphics[width=0.48\textwidth]{figs/dis_modes.pdf} \end{subfigure} \begin{subfigure \centering \includegraphics[width=0.48\textwidth]{figs/dis_test_acc.pdf} \end{subfigure} \vspace{1mm} \caption{{\textbf{Investigating the forgetting-collapse interplay:} We investigate our hypothesis that catastrophic forgetting is associated with mode collapse. On the left pane, we plot the magnitude of mode collapse by counting the number of modes produced by the generator. On the right pane, we assess the quality of the discriminator features by plotting the accuracy of linear classifier on top of the discriminator features at each epoch. In the original model, the coverage of modes and the quality of discriminator features are both low and decreasing. In particular, the test accuracy from the discriminator's features drops almost to randomly initialized weights (shown as \textit{control}). On the other hand, adding AMAT (\textit{MultiD}) dramatically improves both mode coverage and the discriminator test accuracy. }} \label{fig:classification} \vspace{-4mm} \end{figure*} \vspace{-3mm} \subsection{Stacked MNIST} \vspace{-2mm} We also benchmark several models on the Stacked MNIST dataset following \citep{metz2016unrolled, srivastava2017veegan}. Stacked MNIST is an extension of the popular MNIST dataset~\citep{lecun1998gradient} where each image is expanded in the channel dimension to $28 \times 28 \times 3$ by concatenating $3$ single channel images. The resulting dataset has a $1000$ overall modes. We measure the number of modes covered by the generator as the number of classes that are generated at least once within a pool of $25,600$ sampled images. The class of the generated sample is identified with a pretrained MNIST classifier operating channel wise on the original stacked MNIST image. \newline \newline \noindent \textbf{Understanding the forgetting-collapse interplay}: In Section \ref{sec:intro}, we discuss our motivation for studying catastrophic forgetting for mitigating mode collapse. We also design an investigative experiment to explicitly observe this interplay by comparing the number of modes the generator learns against the quality of features the discriminator learns throughout GAN training on the stacked MNIST dataset. We measure the number of modes captured by the generator through a pre-trained classification network trained in a supervised learning fashion and frozen throughout GAN training. To measure the amount of \emph{`forgetting`} in discriminator, we extract features of real samples from the penultimate layer of the discriminator and train a small classifier on the real features for detecting real data mode. This implicitly indicates the quality and information contained in the the discriminator extracted features. However, the performance of classification network on top of discriminator features is confounded by the capacity of the classification network itself. Hence we do a control experiment, where we train the same classifier on features extracted from a randomly initialized discriminator, hence fixing a lower-bound to the classifier accuracy. \begin{table*}[t] \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c} \toprule Classes & Plane & Car & Bird & Cat & Deer & Dog & Frog & Horse & Ship & Truck & Avg \\ \midrule BigGAN & $24.23$ & $12.32$ & $24.85$ & $21.21$ & $12.81$ & $22.74$ & $17.95$ & $13.16$ & $12.11$ & $18.39$ & $8.94$ \\ $+$ AMAT & $20.50$ & $10.30$ & $23.48$ & $18.48$ & $11.51$ & $19.41$ & $11.50$ & $12.24$ & $10.69$ & $12.94$ & $6.11$ \\ $\Delta \%$ & $18.2$ & $19.6$ & $5.8$ & $14.8$ & $11.3$ & $17.2$ & $\mathbf{56.1}$ & $7.5$ & $11.7$ & $\mathbf{42.1}$ & $\mathbf{46.3}$ \\ \bottomrule \end{tabular} } \vspace{3mm} \caption{\textbf{Per-class FID on CIFAR10}: FID improves consistently across all classes.} \label{tab:classwise} \vspace{-3mm} \end{table*} Referring to Figure \ref{fig:classification}, we observe a clear relation between the number of modes the generator covers at an iteration and the accuracy of the classification network trained on the discriminator features at the same iteration. In the vanilla single discriminator scenario, the classification accuracy drops significantly, indicating a direct degradation of the discriminative features which is followed by a complete collapse of G. In the collapse phase, the discriminator's learnt features are close to random with the classification accuracy being close to that of the control experiment. This indicates the presence of significant catastrophic forgetting in the the discriminator network. In contrast, training the same generator with the proposed AMAT procedure leads to stable training with almost all the modes being covered. The classification accuracy increasing before saturation. Catastrophic forgetting is \textit{effectively sidestepped} by adaptive multi adversarial training which produces stable discriminative features during training that provide a consistent training signal to the generator thereby covering all the modes with little degradation. \vspace{-1mm} \subsection{CIFAR10} \vspace{-1mm} \begin{figure*}[t!] \centering \begin{subfigure \centering \includegraphics[width=0.45\textwidth]{figs/gans.pdf} \end{subfigure} \hfill \begin{subfigure \centering \includegraphics[width=0.45\textwidth]{figs/gans_1d.pdf} \end{subfigure} \caption{\textbf{Sample Diversity on CUB200:} We showcase samples from a BigGAN pretrained on imagenet \& finetuned on CUB200 with the AMAT procedure (left) and from an identical BigGAN finetuned without AMAT (right). Observe that while the sample quality is good for both, the samples generated with AMAT are more colorful \& diverse, with bright reds and yellow against several backgrounds. While the samples from vanilla fine-tuning are restricted to whites/grays \& only a hint of color. } \label{fig:cub200} \vspace{-6mm} \end{figure*} We extensively benchmark AMAT on several GAN variants including unconditional methods such as DCGAN \citep{radford2015unsupervised}, ResNet-WGAN-GP \citep{gulrajani2017improved,he2016deep} \& SNGAN \citep{miyato2018spectral} and also conditional models such as BigGAN \citep{brock2018large}. Table \ref{tab:cifar} shows the performance gain on standard GAN evaluation metrics such as Inception Score and Fr\'echet distance of several architectures when trained with AMAT procedure. The performance gains indicate effective curbing of catastrophic forgetting in the discriminator with multi adversarial training. We use the public evaluation code from SNGAN \citep{miyato2018spectral} for evaluation. Despite having components such as spectral normalization, diversity promoting loss functions, additional R1 losses \& other stable training tricks that might affect catastrophic forgetting to different extents, we observe a consistent increase in performance across all models. Notably the ResNet GAN benefits greatly with AMAT despite a powerful backbone -- with IS improving from $6.7$ to $8.1$, indicating that the mode oscillation problem is not mitigated by simply using a better model. AMAT improves performance by over $35\%$ even on a well performing baseline such as BigGAN (Table \ref{tab:cifar}). We investigate classwise FID scores of a vanilla BigGAN and an identical BigGAN + AMAT on CIFAR10 and report the results in Table $\ref{tab:classwise}$. Performance improves across all classes with previously poor performing classes such as `Frog' \& `Truck' experiencing the most gains. Further, we ablate several key components of AMAT procedure on the BigGAN architecture with results reported in Table \ref{tab:ablations}. We observe all elements to be critical to overall performance. Specifically, having a moderate $\alpha$ schedule to avoid adding too many discriminators is critical. Another viable design choice is to effectively flip the algorithm's logic and instead choose the fake points randomly while being $\epsilon$ greedy on the real points. This strategy performs well on simple datasets but loses performance with BigGAN on CIFAR10 (Table \ref{tab:ablations}). In all experiments, the computational time during inference is the same as the base model, \textit{irrespective of the number of discriminators} added during the training, since only a single generator is trained with AMAT and all the discriminators are discarded. \vspace{-4mm} \section{Conclusion} \vspace{-3mm} In summary, motivated from the observation of catastrophic forgetting in the discriminator, we propose a new adaptive GAN training framework that adds additional discriminators to prevent mode collapse. We show that our method can be added to existing GAN frameworks to prevent mode collapse, generate more diverse samples and improve FID \& IS. In future, we plan to apply AMAT to fight mode collapse in high resolution image generation settings. \vspace{-3mm} \subsubsection*{Acknowledgements} \vspace{-2mm} We thank Jathushan Rajasegaran for his helping with the forgetting-collapse interplay experiments and Taesung Park for feedback and comments on the early drafts of this paper. \clearpage \section*{Appendix} \section*{CIFAR10 Experiments} \label{appendix:cifarexp} \subsection*{BigGAN + AMAT Experiments} For the baseline we use the author's official PyTorch implementation \footnote{\href{https://github.com/ajbrock/BigGAN-PyTorch}{https://github.com/ajbrock/BigGAN-PyTorch}}. For our experiments on AMAT $+$ BigGAN, we kept the optimizer as Adam \citep{kingma2014adam} and used the hyperparameters $\beta_1 = 0.0, \beta_2 = 0.9$. We did not change the model architecture parameters in any way. The best performance was achieved with learning rate $=0.0002$ for both the Generator and all the Discriminators. The batch size for the $G$ and all $D$ is $50$, and the latent dimension is chosen as $128$. The initial value of $T_t = 5$ epochs, and after the first discriminator is added, $T_t$ is increased by 5 epochs every $T_t$ epochs. The initial value of $\alpha_t = 1.5$, and it is increased by a factor of $3.5$ every time a discriminator is added. To check whether to add another discriminator or not, we use 10 exemplar images, 1 from each CIFAR10 class. While assigning datapoints to each discriminator, we use an epsilon greedy approach. We chose $\epsilon = 0.25$, where the datapoint is assigned to a random discriminator with a probability $\epsilon$. The number of discriminator(s) updates per generator update is fixed at $4$. We also use exponential moving average for the generator weights with a decay of $0.9999$. \subsection*{SN-GAN + AMAT Experiments} We used the SN-GAN implementation from \href{https://github.com/GongXinyuu/sngan.pytorch}{https://github.com/GongXinyuu/sngan.pytorch}, which is the PyTorch version of the authors' Chainer implementation \href{https://github.com/pfnet-research/sngan_projection}{https://github.com/pfnet-research/sngan\_projection}. We kept the optimiser as Adam and used the hyperparameters $\beta_1 = 0.0, \beta_2 = 0.9$. The batch size for generator is $128$ and for the discriminators is $64$, and the latent dimension is $128$. The initial learning rate is $0.0002$ for both generator and the discriminators. The number of discriminator(s) updates per generator update is fixed at $7$. The initial value of $T_t = 2$ epochs, and is increased by $1$ epoch after every discriminator is added. $\alpha_t$ is initialized as $1.5$, and is increased by a factor of $1.3$ after a discriminator is added, till $20$ epochs, after which it is increased by a factor of $3.0$. These larger increases in $\alpha_t$ are required to prevent too many discriminators from being added over all iterations. We chose $\epsilon = 0.3$, where the datapoint is assigned to a random discriminator with a probability $\epsilon$. We use 10 exemplar images, 1 from each CIFAR10 class. \textbf{ResNet GAN:} We use the same ResNet architecture as above, but remove the spectral normalization from the model. The optimizer parameters, learning rate and batch sizes remain the same as well. The number of discriminator(s) updates per generator update is fixed at $5$. The initial value of $T_t = 10$ epochs, and is increased by $5$ epochs after every discriminator is added. $\alpha_t$ is initialized as $1.5$, and is increased by a factor of $2.0$ after a discriminator is added. We chose $\epsilon = 0.2$, where the datapoint is assigned to a random discriminator with a probability $\epsilon$. We use 10 exemplar images, 1 from each CIFAR10 class. \textbf{ResNet WGAN-GP:} In the above model, the hinge loss is replaced by the Wasserstein loss with gradient penalty. The optimizer parameters, learning rate and batch sizes remain the same as well.The number of discriminator(s) updates per generator update is fixed at $2$. The initial value of $T_t = 5$ epochs, and is increased by $5$ epochs after a discriminator is added. $\alpha_t$ is initialized as $1.5$, and is increased by a factor of $3.0$ after a discriminator is added. We chose $\epsilon = 0.2$, where the datapoint is assigned to a random discriminator with a probability $\epsilon$. We use 10 exemplar images, 1 from each CIFAR10 class. These images are chosen randomly from each class, and may not be the same as the ones for other CIFAR10 experiments. \subsection*{DCGAN + AMAT Experiments} We used standard CNN models for our DCGAN as shown in Table \ref{tab:dcganArch}. We use Adam optimizer with hyperparameters $\beta_1 = 0.0, \beta_2 = 0.9$. The learning rate for generator was $0.0002$, and the learning rate for the discriminator(s) was $0.0001$. The number of discriminators updates per generator was fixed at 1. The initial value of $T_t = 4$ epochs, and is increased $5$ epochs after a discriminator is added. $\alpha_t $ is initialized as $1.5$ and is increased by a factor of $1.5$ every time a discriminator is added. We chose $\epsilon = 0.3$, where the datapoint is assigned to a random discriminator with a probability $\epsilon$. We use 10 exemplar images, 1 from each CIFAR10 class. \section*{Stacked MNIST Experiments} Stacked MNIST provides us a test-bed to measure mode collapse. A three channel image is generated by stacking randomly sampled MNIST classes, thus creating a data distribution if 1000 modes. We use this dataset to show that, when generator oscillates to a different set of modes, catastrophic forgetting is induced in discriminator and this prevents the generator to recover previous modes. To study this phenomenon, we need to measure the correlation between number of modes the generator covered and the catastrophic forgetting in the discriminator. Measuring the number of modes is straight forward, we can by simply classify each channels of the generated images using a MNIST pretrained classifier to find its corresponding mode. However, to measure catastrophic forgetting in the discriminator, we use a proxy setting, where we take the high-level features of the real images from the discriminator and train a simple classifier on top of that. The discriminative quality of the features taken from the discriminator indirectly measure the ability of the network to remember the modes. Finally, as a control experiment we randomize the weights of the discriminator, and train a classifiers on the feature taken from randomized discriminator. This is to show that, extra parameters in the classifier does not interfere our proxy measure for the catastrophic forgetting. Finally, we train a DCGAN with a single discriminator, and a similar DCGAN architecture with our proposed AMAT procedure, and measure the number of modes covered by the generator and the accuracy of the discriminator. \section*{A Fair comparison on discriminator capacity} Our AMAT approach incrementally adds new discriminators to the GAN frameworks, and its overall capacity increases over time. Therefore, it is not fair to compare a model with AMAT training procedure with its corresponding the single discriminator model. As a fair comparison to our AMAT algorithm, we ran single discriminator model with approximately matching its discriminator capacity to the final AMAT model. For example, SN-GAN with AMAT learning scheme uses 4 discriminators at the end of its training. Therefore we use a discriminator with four times more parameters for the single discriminator SN-GAN model. This is done by increasing the convolutional fillters in the discriminator. Table~\ref{tab:fairD} shows that, even after matching the network capacity, the single discriminator models do not perform well as compared to our AMAT learning. \begin{table*}[!t] \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c|c| ccccc} \toprule & Scores & DCGAN & ResNetGAN & WGAN-GP & SN-GAN & BigGAN \\ \midrule & \#of Param of D & 1.10 M & 3.22 M & 2.06 M & 4.20 M & 8.42 M \\ w/o AMAT & IS & 5.97 $\pm$ 0.08 & 6.59 $\pm$ 0.09 & 7.72 $\pm$ 0.06 & 8.24 $\pm$ 0.05 & 9.14 $\pm$ 0.05 \\ & FID & 34.7 & 36.4 & 19.1 & 14.5 & 10.5 \\ \midrule & \#of Param of D & 1.02 M & 3 $\times$ 1.05 M & 2 $\times$ 1.05 M & 4 $\times$ 1.05 M & 8.50 M \\ + AMAT & IS & 6.32 $\pm$ 0.06 & 8.1 $\pm$ 0.04 & 7.80 $\pm$ 0.07 & 8.34 $\pm$ 0.04 & 9.51 $\pm$ 0.06 \\ & FID & 30.14 & 16.35 & 17.2 & 13.8 & 6.11 \\ \midrule \bottomrule \end{tabular} } \vspace{2mm} \caption{Increasing network capacity alone does not capture more modes. Even after the discriminator capacity is matched, single discriminator GANs do not perform as well as multi-adversarial GANs with AMAT learning} \label{tab:fairD} \end{table*} \section*{Synthetic Data Experiments} \label{appendix:synthetic} We add flow-based non-linearity (Algorithm \ref{algo:synthetic}) to a synthetic 8-Gaussian ring dataset. We chose $K=5$ as our non-linearity depth and chose a randomly initiated 5 layer MLP as our non-linear functions. We use an MLP as our GAN generator and discriminator (Table \ref{tab:mlpArch}). We use the Adam optimizer with hyperparameters $\beta_1 = 0.0, \beta_2 = 0.9$. The learning rate for the generator and discriminator was $0.0002$. The number of discriminator updates per generator update is fixed to 1, and the batch size is kept 64. The initial value of $T_t = 5$ epochs, and is increased by $10$ every time a discriminator is added. $\alpha_t$ is initialized as $1.5$, and is increased by a factor of $1.5$ after a discriminator is added for the first 50 epochs. After that $\alpha_t$ is increased by a factor of $3$. We chose $\epsilon = 0.25$, where the datapoint is assigned to a random discriminator with a probability $\epsilon$. 1 random datapoint from each of the 8 modes is selected as the exemplar image. Figure \ref{fig:eightgaussian} shows the difference in performance of a standard MLP GAN (\ref{tab:mlpArch} and the same MLP GAN with AMAT. The GIF on the lefts shows a cyclic mode collapse due the discriminator suffering from catastrophic forgetting. The same GAN with is able to completely mitigate catastrophic forgetting with just 2 discriminators added during training, on a 728-dimensional synthetic data. \begin{table}[!htb] \parbox{0.45\linewidth}{\centering \begin{tabular}{c} \toprule \midrule $z \in \mathbb{R}^{128} \sim \mathcal{N}(0,I) $\\ \midrule dense $\rightarrow 4 \times 4 \times 512$\\ \midrule $4\times4$, stride$=$2 deconv. BN 256 ReLU\\ \midrule $4\times4$, stride$=$2 deconv. BN 128 ReLU\\ \midrule $4\times4$, stride$=$2 deconv. BN 64 ReLU\\ \midrule $3\times3$, stride$=$1 conv. 3 Tanh\\ \midrule \bottomrule \end{tabular} \vspace{3mm} \caption*{Generator} } \vspace{1mm} \parbox{0.45\linewidth}{\centering \begin{tabular}{c} \toprule \midrule $x \in \mathbb{R}^{32 \times 32 \times 3}$\\ \midrule $3\times3$, stride$=$1 conv. 64 lReLU\\ $4\times4$, stride$=$2 conv. 64 lReLU\\ \midrule $3\times3$, stride$=$1 conv. 128 lReLU\\ $4\times4$, stride$=$2 conv. 128 lReLU\\ \midrule $3\times3$, stride$=$1 conv. 256 lReLU\\ $4\times4$, stride$=$2 conv. 256 lReLU\\ \midrule $3\times3$, stride$=$1 conv. 512 lReLU\\ \midrule dense $\rightarrow 1$\\ \midrule \bottomrule \end{tabular} \vspace{3mm} \caption*{Discriminator} } \vspace{3mm} \caption{DCGAN Architecture for CIFAR10} \label{tab:dcganArch} \end{table} \begin{table*}[!t] \centering \parbox{0.45\linewidth}{\centering \begin{tabular}{c} \toprule \midrule $z \in \mathbb{R}^{25} \sim \mathcal{N}(0,I) $\\ \midrule dense $\rightarrow 128$, BN 128 ReLU\\ \midrule dense $\rightarrow 128$, BN 128 ReLU\\ \midrule dense $\rightarrow 512$, BN 512 ReLU\\ \midrule dense $\rightarrow 1024$, BN 1024 ReLU\\ \midrule dense $\rightarrow 2$, Tanh\\ \midrule \bottomrule \end{tabular} \vspace{2mm} \caption*{Generator} } \parbox{0.45\linewidth}{\centering \begin{tabular}{c} \toprule \midrule $x \in \mathbb{R}^{2}$\\ \midrule dense $\rightarrow 128$ ReLU\\ \midrule dense $\rightarrow 512$ ReLU\\ \midrule dense $\rightarrow 1$ Sigmoid\\ \midrule \bottomrule \end{tabular} \vspace{2mm} \caption*{Discriminator} } \vspace{1mm} \caption{MLP architecture for Synthetic Dataset} \label{tab:mlpArch} \end{table*} \begin{figure*} \begin{subfigure \centering \animategraphics[loop,autoplay,width=0.24\textwidth]{5}{figs/gif0/}{0}{47} \end{subfigure} \begin{subfigure \centering \animategraphics[loop,autoplay,width=0.24\textwidth]{5}{figs/gen/frame_}{1}{48} \end{subfigure} \begin{subfigure \centering \animategraphics[loop,autoplay,width=0.24\textwidth]{5}{figs/d0/frame_}{1}{48} \end{subfigure} \begin{subfigure \centering \animategraphics[loop,autoplay,width=0.24\textwidth]{5}{figs/d1/frame_}{1}{48} \end{subfigure} \caption{ \small{\textbf{GAN training visualization}: (Figure contains animated graphics, better viewed in Adobe Acrobat Reader) Training trajectories of an MLP in table \ref{tab:mlpArch} (leftmost panel) and an MLP trained with our AMAT procedure (Algorithm \ref{algo:multi}) (rest three panels) on a $784$-dimensional synthetic dataset. Green dots represent real samples and the blue dots represent the generated samples. The vanilla GAN samples are overlayed against discriminator's output heatmap where the warm yellow color indicates a high probability of being real and cold violet indicates fake. In the AMAT + GAN panels, the discriminator landscapes are shown separately for both discriminators with the second discriminator being spawned at iteration $4000$ (Algorithm \ref{algo:spawn}). The $2$D visualizations of the $784$D data space is facilitated by our synthetic data generation procedure (Algorithm \ref{algo:synthetic}). }} \label{fig:eightgaussian} \end{figure*} \clearpage \section{Introduction} \label{sec:intro} Generative Adversarial Networks (GANs) \citep{goodfellow2014generative} are an extremely popular class of generative models used for text and image generation in various fields of science and engineering, including biomedical imaging~\citep{yi2019generative,nie2018medical,wolterink2017generative}, autonomous driving~\citep{hoffman2018cycada,zhang2018deeproad}, and robotics~\citep{rao2020rl,bousmalis2018using}. However, GANs are widely known to be prone to \textit{mode collapse}, which refers to a situation where the generator only samples a few modes of the real data, failing to faithfully capture other more complex or less frequent categories. While the mode collapse problem is often overlooked in text and image generation tasks, and even traded off for higher realism of individual samples~\citep{karras2019style,brock2018large}, dropping infrequent classes may cause serious problems in real-world problems, in which the infrequent classes represent important anomalies. For example, a collapsed GAN can produce racial/gender biased images~\citep{Menon_2020_CVPR}. Moreover, mode collapse causes instability in optimization, which can damage not only the diversity but also the realism of individual samples of the final results. As an example, we visualized the training progression of the vanilla GAN~\citep{goodfellow2014generative} for a simple bimodal distribution in the top row of Figure~\ref{fig:oscillation}. At collapse, the discriminator conveniently assigns high realism to the region unoccupied by the generator, regardless of the true density of the real data. This produces a strong gradient for the generator to move its samples toward the dropped mode, swaying mode collapse to the opposite side. In particular, the discriminator loses its ability to detect fake samples it was previously able to, such as point \textbf{X}\tikz\draw[red,fill=red] (0,5) circle (.3ex);. The oscillation continues without convergence. We observe that the mode collapse problem in GAN training is closely related to Catastrophic Forgetting~\citep{mccloskey1989catastrophic, mcclelland1995there, ratcliff1990connectionist} in continual learning. A promising line of works~\citep{sidetuning2019, NIPS2019_9429, rusu2016progressive, fernando2017pathnet} tackle the problem in the supervised learning setting by instantiating multiple predictors, each of which takes charge in a particular subset of the whole distribution. Likewise, we also tackle the problem of mode collapse in GAN by tracking the severity of Catastrophic Forgetting by storing a few exemplar data during training, and spawning an additional discriminator if forgetting is detected, Figure~\ref{fig:oscillation}. The key idea is that the added discriminator is left intact unless the generator recovers from mode dropping of that sample, essentially sidestepping catastrophic forgetting. We show that our proposed approach based on adaptive addition of discriminators can be added to any of the existing GAN frameworks, and is most effective in preventing mode collapse. Furthermore, the improved stability of training boosts the standard metrics on popular GAN frameworks. To summarize, our contributions are: \emph{First}, we propose a novel GAN framework, named Adaptive Multi Adversarial Training (AMAT), that effectively prevents Catastrophic Forgetting in GANs by spawning additional discriminators during training. \emph{Second}, we also propose a computationally efficient synthetic data generation procedure for studying mode collapse in GANs that allows visualizing high dimensional data using normalizing flows. We show that mode collapse occurs even in the recent robust GAN formulations. \emph{Third}, our method can be plugged into any state-of-the-art GAN frameworks and still improve the quality and coverage of the generated samples. \begin{figure*} \centering \includegraphics[trim={0 0 0 10},clip,width=0.90\textwidth]{figs/totalcomb2.png} \vspace{3mm} \caption{\textbf{Visualizing training trajectories}: Distribution of real (green dots) and fake (blue dots) over the course of vanilla GAN (top row) and our method (the second row and below). The background color indicates the prediction heatmap of the discriminator with blue being fake and warm yellow being real. Once the vanilla GAN falls into mode collapse (top row), it ends up oscillating between the two modes without convergence. Also, the discriminator's prediction at point X oscillates, indicating catastrophic forgetting in the discriminator. AMAT algorithm adapts to the need, and a new discriminator is spawned during training which effectively learns the forgotten mode, guiding the GAN optimization toward convergence. } \label{fig:oscillation} \vspace{-3mm} \end{figure*} \vspace{-5mm} \section{Related Works} \vspace{-2mm} \label{sec:related} Previous works have focused on independently solving either catastrophic forgetting in supervised learning or mode collapse during GAN training. In this section we review these works in detail and discuss our commonalities and differences. \vspace{-4mm} \subsection{Mitigating Mode Collapse in GANs} Along with advancement in the perceptual quality of images generated by GAN~\citep{miyato2018spectral,karras2019style,brock2018large,karras2020analyzing}, a large number of papers~\citep{durugkar2016generative,metz2016unrolled,arjovsky2017wasserstein,srivastava2017veegan,nguyen2017dual,lin2018pacgan,MeschederICML2018,karras2019style} identify the problem of mode collapse in GANs and aim to mitigate it. However mode collapse was seen as a secondary symptom that would be naturally solved as the stability of GAN optimization progresses~\citep{arjovsky2017wasserstein,MeschederICML2018,bau2019seeing}. To explicitly address mode collapse, Unrolled GAN~\citep{metz2016unrolled} proposes an unrolled optimization of the discriminator to optimally match the generator objective, thus preventing mode collapse. VEEGAN~\citep{srivastava2017veegan} utilizes the reconstruction loss on the latent space. PacGAN~\citep{lin2018pacgan} feeds multiple samples of the same class to the discriminator when making the decisions about real/fake. In contrast, our approach can be plugged into existing state-of-the-art GAN frameworks to yield additional performance boost. \vspace{-4mm} \subsection{Multi-adversarial Approaches} \vspace{-1mm} The idea of employing more than one adversarial network in GANs to improve results has been explored by several previous works independent of the connection to continual learning and catastrophic forgetting. MGAN~\citep{hoang2018mgan} uses multiple generators, while D2GAN~\citep{nguyen2017dual} uses two discriminators, and GMAN~\citep{durugkar2016generative} and MicrobatchGAN~\citep{mordido2020microbatchgan} proposed a method with more than two discriminators that can be specified as a training hyperparameter beforehand. However, all previous works require the number of discriminators to be fixed beforehand, which is a major drawback since it depends on several intricate factors such as training dynamics, data distribution complexity, model architecture, initialization hyper-parameters etc. and is expensive and difficult to approximate even with several runs of the algorithm. In contrast, noting by the connection of multi-adversarial training to parameter expansion approaches to catastrophic forgetting, we propose an \textit{adaptive} method that can add discriminators incrementally during training thus achieving superior performance than existing works both on data quality metrics as well as overall computational effort. \begin{table*}[t] \resizebox{\textwidth}{!}{ \begin{tabular}{c|c|c|c|c|c||c} \begin{tabular}{c} $g(\mathbf{z}) = $ \end{tabular} & $\mathbbm{1}$ & \begin{tabular}[c]{@{}c@{}} $\mathbf{A}_{392 \times 2}$ \\ \end{tabular} & \begin{tabular}[c]{@{}c@{}} $\mathbf{z}$ \end{tabular} & \begin{tabular}[c]{@{}c@{}} MLP \end{tabular} & \begin{tabular}[c]{@{}c@{}} MLP, $\mathbf{A}_{392 \times 2}$ \end{tabular} & \begin{tabular}{@{}c@{}} \small{MNIST} \end{tabular} \\[1ex] \hline \begin{tabular}[c]{@{}c@{}} Label\\ \end{tabular} & {\fontfamily{lmtt}\selectfont Level I} & {\fontfamily{lmtt}\selectfont Level II} & {\fontfamily{lmtt}\selectfont Level III} & {\fontfamily{lmtt}\selectfont Level IV} & {\fontfamily{lmtt}\selectfont Level V} & - \\ \hline \begin{tabular}[c]{@{}c@{}} \small{GAN-NS \citep{goodfellow2014generative}}\\ \end{tabular} & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \cmark & \cmark \enskip \big\vert \enskip \cmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{WGAN} \citep{arjovsky2017wasserstein} \\ \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \xmark & \cmark \enskip \big\vert \enskip \cmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{Unrolled GAN} \citep{metz2016unrolled} \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{D2GAN} \citep{nguyen2017dual} \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \begin{tabular}[c]{@{}c@{}} \small{GAN-NS + AMAT} \end{tabular} & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \xmark \enskip \big\vert \enskip \xmark & \cmark \quad \big\vert \quad \cmark & \xmark \\ \end{tabular} } \hline \vspace{1mm} \caption{\xmark \hspace{0.1mm} indicates that the generator could effectively learn all the data modes, while \cmark \hspace{0.1mm} means \textit{despite best efforts with tuning} the training suffers from mode collapse (more than a quarter of data modes dropped). We show results with the SGD (left) \& ADAM (right) optimizers. MNIST results with ADAM optimizer are provided for reference. We observe that MNIST is a relatively easy dataset, falling between {\fontfamily{lmtt}\selectfont Level I} and {\fontfamily{lmtt}\selectfont II} in terms of complexity.} \label{tab:synthetic} \vspace{-4mm} \end{table*} \vspace{-4mm} \subsection{Overcoming Catastrophic Forgetting in GAN} \vspace{-1mm} Methods to mitigate catastrophic forgetting can be categorized into three groups: a) regularization based methods~\citep{kirkpatrick2017overcoming} b) memory replay based methods~\citep{rebuffi2017icarl} c) network expansion based methods~\citep{zhang2018deeproad, NIPS2019_9429}. Our work is closely related to the third category of methods, which dynamically adds more capacity to the network, when faced with novel tasks. This type of methods, adds \emph{plasticity} to the network from new weights (fast-weights) while keeping the \emph{stability} of the network by freezing the past-weights (slow-weights). Additionally, we enforce stability by letting a discriminator to focus on a few set of classes, not by freezing its weights. The issue of catastrophic forgetting in GANs has been sparsely explored before. \citet{chen2018self} and \citet{tran2019self} propose a self-supervised learning objective to prevent catastrophic forgetting by adding new loss terms. \citet{liang2018generative} proposes an online EWC based solution to tackle catastrophic forgetting in the discriminator. We propose a prominently different approach based on parameter expansion rather than regularization. While the regularization based approaches such as \citet{liang2018generative} attempt to retain the previously learnt knowledge by constrained weight updates, the parameter expansion approaches effectively sidestep catastrophic forgetting by freezing previously encoded knowledge. \citet{thanhcatastrophic} also discuss the possibility of catastrophic forgetting in GAN training but their solution is limited to theoretical analyses with simplistic proposals such as assigning larger weights to real samples and optimizing the GAN objective with momentum. Practically, we observed that their method performs worse than a plain vanilla DCGAN on simple real world datasets like CIFAR10. In contrast, our method leverages insights from continual learning and has a direct connections to prevalent parameter expansion approaches in supervised learning. We benchmark extensively on several datasets and state-of-the-art GAN approaches where our method consistently achieves superior results to the existing methods. \vspace{-5mm} \section{Proposed Method} \vspace{-2mm} In this section, we first describe our proposed data generation procedure that we use as a petri dish for studying mode collapse in GANs. The procedure uses random normalizing flows for simultaneously allowing training on complex high dimensional distributions yet being perfectly amenable to 2D visualizations. Next, we describe our proposed Adaptive Multi Adversarial Training (AMAT) algorithm that effectively detects catastrophic forgetting and spawns a new discriminator to prevent mode collapse. \vspace{-3mm} \subsection{Synthetic Data Generation with Normalizing flows} Mode dropping in GANs in the context of catastrophic forgetting of the discriminator is a difficult problem to investigate using real datasets. This is because the number of classes in the dataset cannot be easily increased, the classes of fake samples are often ambiguous, and the predictions of the discriminator cannot be easily visualized across the whole input space. In this regard, we present a simple yet powerful data synthesis procedure that can generate complex high dimensional multi-modal distributions, yet maintaining perfect 2-D visualization capabilities. Samples from a 2-D Gaussian distribution are augmented with biases and subjected to an invertible normalizing flow~\citep{karami2019invertible} parameterized by well conditioned functions $g_i: \mathbb{R}^{d^0_i} \rightarrow \mathbb{R}^{d^1_i}$. This function can be followed by a linear upsampling transformation parameterized by a $d^1_i \times d^0_{i+1}$ dimensional matrix $A^i$ (Algorithm \ref{algo:synthetic}). The entire transform is deliberately constructed to be a bijective function so that every generated sample in $\hat{y} \in \mathbb{R}^D$ can be analytically mapped to $\mathbb{R}^2$, allowing perfect visualization on 2D space. Furthermore, by evaluating a dense grid of points in $\mathbb{R}^2$, we can understand discriminator's learned probability distribution on $\mathbf{z}$ manifold as a heatmap on the 2D plane. This synthetic data generation procedure enables studying mode collapse in a controlled setting. This also gives practitioners the capability to train models on a chosen data complexity with clean two-dimensional visualizations of both the generated data and the discriminator's learnt distribution. This tool can be used for debugging new algorithms using insights from the visualizations. In the case of mode collapse, a quick visual inspection would give the details of which modes face mode collapse or get dropped from discriminator's learnt distribution. \vspace{-4mm} \subsection{Adaptive Multi Adversarial Training} Building upon the insight on relating catastrophic forgetting in discriminator to mode collapse in generator, we propose a multi adversarial generative adversarial network training procedure. The key intuition is that the interplay of catastrophic forgetting in the discriminator with the GAN minimax game, leads to an oscillation generator. Thus, as the generator shifts to a new set of modes the discriminator forgets the learnt features on the previous modes. \input{algos} However if there are multiple discriminators available, each discriminator can implicitly \emph{specialize} on a subset of modes. Thus even if the generator oscillates, each discriminator can remember their own set of modes, and they will not need to move to different set of modes. This way we can effectively \emph{sidestep} forgetting and ensure the networks do not face significant distribution shift. A detailed version of our proposed method is presented in Algorithm \ref{algo:multi}. \newline \newline \textbf{Spawning new discriminators}: We initialize the AMAT training Algorithm~\ref{algo:multi} with a regular GAN using just one discriminator. We also sample a few randomly chosen exemplar data points with a maximum of one real sample per mode, depending on dataset complexity. The exemplar data points are used to detect the presence of catastrophic forgetting in the currently active set of discriminators $\displaystyle {\mathbb{D}}$ and spawn a new discriminator if needed. Specifically (Algorithm \ref{algo:spawn}), we propose that if \emph{any} discriminator among $\displaystyle {\mathbb{D}}$ has an unusually high score over an exemplar data point ${\bm{e}}_i$, this is because the mode corresponding to ${\bm{e}}_i$ has either very poor generated samples or has been entirely dropped. In such a situation, if training were to continue we risk catastrophic forgetting in the active set $\displaystyle {\mathbb{D}}$, if the generator oscillate to near ${\bm{e}}_i$. This is implemented by comparing the $\max$ score over $\displaystyle \vD$ at ${\bm{e}}_i$ to the average score over $\displaystyle \vD$ and spawning a new discriminator when the ratio exceeds $\alpha_t (> 1)$. Further, we propose to have $\alpha_t (> 1)$ a monotonically increasing function of $| \displaystyle {\mathbb{D}}|$, thus successively making it harder to spawn each new discriminator. Additionally, we use a warmup period $T_t$ after spawning each new discriminator from scratch to let the spawned discriminator train before starting the check over exemplar data-points. \newline \newline \noindent \textbf{Multi-Discriminator Training: } We evaluate all discriminators in $\displaystyle {\mathbb{D}}$ on the fake samples but do not update all of them for all the samples. Instead, we use the discriminator scores to assign responsibility of each data point to only one discriminator. \newline \newline \noindent \textbf{Training over fake samples}: We use an $\epsilon$-greedy approach for fake samples where the discriminator with the lowest output score is assigned responsibility with a probability $1 - \epsilon$ and a random discriminator is chosen with probability $\epsilon$. \newline \newline \noindent \textbf{Training over real samples}: The discriminator is always chosen uniformly randomly thus we slightly prefer to assign the same discriminator to the fake datapoints from around the same mode to ensure that they do not forget the already learnt modes and switch to another mode. The random assignment of real points ensure that the same preferentially treated discriminator also gets updated on real samples. Further for optimization stability, we ensure that the real and fake sample loss incurred by each discriminator is roughly equal in each back-propagation step by dynamically reweighing them by the number of data points the discriminator is responsible for. We only update the discriminator on the losses of the samples they are responsible for. While it may seem that adding multiple discriminators makes the procedure expensive, in practice the total number of added discriminator networks never surpass three for the best results. It is possible to change the hyperparameters to allow a large number of discriminators but that results in sub-optimal results and incomplete training. The optimal hyperparameter selection is explained in the Appendix for each dataset. Further, the additional discriminators get added during later training stages and are not trained from the start, saving compute in comparison to prior multi-adversarial works which train all the networks from the beginning. Also, unlike AdaGAN \citep{tolstikhin2017adagan} and similar Boosted GAN models that need to store multiple Generators post training, the final number of parameters required during inference remains unchanged under AMAT . Thus the inference time remains the same, but with enhanced mode coverage and sample diversity. Unlike \citep{tolstikhin2017adagan}, our discriminator addition is adaptive, i.e. discriminators are added during the training thus being more efficient. \newline \newline \noindent \textbf{Generator Training:} We take a weighted mean over the discriminators scores on the fake datapoints for calculating the generator loss. At each step, the weights each discriminator in $\displaystyle {\mathbb{D}}$ gets is in decreasing order of its score on the fake sample. Hence, the discriminator with the lowest score is given the most weight since it is the one that is currently specializing on the mode the fake sample is related to. In practice, we sample weights randomly from a Dirichlet distribution (and hence implicitly they sum to $1$) and sort according to discriminator scores to achieve this. We choose soft weighing over hard binary weights because since the discriminators are updated in an $\epsilon$ greedy fashion, the discriminators other than the one with the best judgment on the fake sample might also hold useful information. Further, we choose the weights randomly rather than fixing a chosen set to ensure AMAT is more deadset agnostic since the number of discriminator used changes with the dataset complexity so does the number of weights needed. While a suitably chosen function for generating weights can work well on a particular dataset, we found random weights to work as well across different settings. \vspace{-5mm} \section{Results} \vspace{-3mm} \label{sec:results} We test our proposed method on several synthetic and real datasets \& report a consistent increase in performance on GAN evaluation metrics such as Inception Score \citep{salimans2016improved} and Frech\'et Inception Distance \citep{heusel2017gans} with our proposed AMAT. We also showcase our performance in the GAN fine-tuning regime with samples on the CUB200 dataset \citep{WelinderEtal2010} which qualitatively are more colorful and diverse than an identical BigGAN without AMAT (Figure \ref{fig:cub200}). \begin{table*}[t] \resizebox{\textwidth}{!} \begin{tabular}{ccccc|c c} \toprule & GAN & UnrolledGAN & D2GAN & RegGAN & DCGAN & with AMAT \\ \midrule \# Modes covered & $628.0 \pm 140.9$ & $817.4 \pm 37.9$ & $1000 \pm 0.0$ & $ 955.5\pm18.7$ & $849.6\pm 62.7$ & $\mathbf{1000 \pm 0.0}$ \\ KL (samples $\Vert$ data) & $2.58\pm 0.75$ & $1.43 \pm 0.12$ & $0.080 \pm 0.01$ & $0.64 \pm 0.05$ & $0.73\pm0.09$ & $0.078\pm0.01$ \\ \bottomrule \end{tabular} } \vspace{3mm} \caption{\textbf{Quantitative Results on the Stacked MNIST dataset}: Applying our proposed adaptive multi adversarial training (AMAT) procedure to a simple DCGAN achieves perfect mode coverage, better than many existing methods for mode collapse.} \label{tab:stacked} \end{table*} \begin{table*}[t] \smaller \resizebox{\textwidth}{!}{ \begin{tabular}{c| cc|cc|cc} \toprule & & & GAN-NS & AMAT + & & AMAT + \\ Model & D2GAN & MicrobatchGAN & w/ ResNet & GAN-NS & DCGAN & DCGAN \\ \midrule IS & $7.15 \pm 0.07$ & $6.77$ & $6.7 \pm 0.06$ & $\mathbf{8.1 \pm 0.04}$ & $6.03\pm0.05$ & $\mathbf{6.32\pm0.06}$ \\ FID & - & - & $28.91$ & $\mathbf{16.35}$ & $33.42$ & $\mathbf{30.14}$ \\ \midrule & WGAN-GP & AMAT + & &AMAT + & & AMAT + \\ Model & w/ ResNet & WGAN-GP & SN-GAN & SN-GAN & BigGAN & BigGAN \\ \midrule IS & $7.59\pm0.10$ & $\mathbf{7.80\pm0.07}$ &$ 8.22\pm0.05$ &$\mathbf{8.34\pm0.04}$& $9.22$ & $\mathbf{9.51\pm0.06}$ \\ FID & $19.2$ & $\mathbf{17.2}$ &$14.21$ &$\mathbf{13.8}$ & $8.94$ & $\mathbf{6.11}$ \\ \bottomrule \end{tabular} } \vspace{3mm} \centering \caption{\textbf{Quantitative Results on CIFAR10}: We benchmark AMAT against several other multi-adversarial baselines as well as on several GAN architectures across all of which we observe a consistent performance increase.} \label{tab:cifar} \end{table*} \subsection{Synthetic Data} We utilize the proposed synthetic data generation procedure with randomly initialized normalizing flows to visualize the training process of a simple DCGAN \citep{radford2015unsupervised}. Figure \ref{fig:oscillation} visualizes such a training process for a simple bimodal distribution. Observing the pattern of generated samples over the training iteration and the shifting discriminator landscape, we note a clear mode oscillation issue present in the generated samples driven by the shifting discriminator output distribution. Focusing on a single fixed real point in space at any of the modes, we see a clear oscillation in the discriminator output probabilities strongly indicating the presence of catastrophic forgetting in the discriminator network. \noindent \textbf{Effect of Data Complexity on Mode Collapse}: We use the flexibility in choosing transformations $g_i$ to generate datasets of various data distribution complexities as presented in Table $\ref{tab:synthetic}$. Choosing $g(z)$ with successively more complicated transformations can produce synthetic datasets of increasing complexity, the first five of which we roughly classify as {\fontfamily{lmtt}\selectfont Levels}. The {\fontfamily{lmtt}\selectfont Levels} are generated by using simple transforms such as identitym constant mapping, small Multi layer perceptrons and well conditioned linear transforms ($\mathbf{A}$). On this benchmark, we investigate mode collapse across different optimizers such as SGD \& ADAM \citep{kingma2014adam} on several popular GAN variants such as the non-saturating GAN Loss (GAN-NS) \citep{goodfellow2014generative}, WGAN \citep{arjovsky2017wasserstein} and also methods targeting mitigating mode collapse specifically such as Unrolled GAN \citep{metz2016unrolled} and D2GAN \citep{nguyen2017dual}. We show results of our proposed AMAT training procedure with a simple GAN-NS, which matches performance with other more complicated mode collapse specific GAN architectures, all of which are robust to mode collapse up to {\fontfamily{lmtt}\selectfont Level IV}. In practice we find all benchmarked methods to collapse at {\fontfamily{lmtt}\selectfont Level V}. Thus, in contrast to other simple datasets like MNIST~\citep{lecun1998mnist}, Gaussian ring, or Stacked MNIST~\citep{metz2016unrolled}, the complexity of our synthetic dataset can be arbitrarily tuned up or down to gain insight into the training and debugging of GAN via visualizations. \begin{table*}[t] \vspace{-2mm} \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c| ccccc| c} \toprule Effect & Large $|\displaystyle {\mathbb{D}}|$ & Spawn too late & Greedy $\displaystyle \nabla$D & Random for fake & $\mathbf{1}$-hot weight & Proposed \\ Ablation & Small $\alpha$, Short $T_t$ & Long $T_t$ schedule & $\epsilon = 0$ & $\epsilon$-greedy for real & vector ${\bm{m}}$ & Method \\ \midrule IS & $8.83 \pm 0.04$ & $9.28 \pm 0.08$ & $9.31 \pm 0.06$ & $8.95 \pm 0.04$ & $9.25 \pm 0.05$ & $9.51 \pm 0.06$ \\ FID & $14.23$ & $9.37$ & $8.6$ & $12.5$ & $9.25$ & $6.11$ \\ \bottomrule \end{tabular} } \vspace{3mm} \caption{\textbf{BigGAN + AMAT Ablations on CIFAR10} (A) A spawning condition with small $\alpha$ and short warmup schedule that leads to large number of discriminators (>$7$) (B) Long warm-up schedules that spawn new discriminators late into training (C) A greedy strategy for assigning responsibility of fake samples ($\epsilon = 0$) (D) Flipping the data splitting logic with responsibilities of fake samples being random and of real being $\epsilon$-greedy (E) Choosing the discriminator with lowest score for updating Generator instead of soft random weighting.} \vspace{-2mm} \label{tab:ablations} \end{table*} \begin{figure*} \centering \begin{subfigure \centering \includegraphics[width=0.48\textwidth]{figs/dis_modes.pdf} \end{subfigure} \begin{subfigure \centering \includegraphics[width=0.48\textwidth]{figs/dis_test_acc.pdf} \end{subfigure} \vspace{1mm} \caption{{\textbf{Investigating the forgetting-collapse interplay:} We investigate our hypothesis that catastrophic forgetting is associated with mode collapse. On the left pane, we plot the magnitude of mode collapse by counting the number of modes produced by the generator. On the right pane, we assess the quality of the discriminator features by plotting the accuracy of linear classifier on top of the discriminator features at each epoch. In the original model, the coverage of modes and the quality of discriminator features are both low and decreasing. In particular, the test accuracy from the discriminator's features drops almost to randomly initialized weights (shown as \textit{control}). On the other hand, adding AMAT (\textit{MultiD}) dramatically improves both mode coverage and the discriminator test accuracy. }} \label{fig:classification} \vspace{-4mm} \end{figure*} \vspace{-5mm} \subsection{Stacked MNIST} \vspace{-2mm} We also benchmark several models on the Stacked MNIST dataset following \citep{metz2016unrolled, srivastava2017veegan}. Stacked MNIST is an extension of the popular MNIST dataset~\citep{lecun1998gradient} where each image is expanded in the channel dimension to $28 \times 28 \times 3$ by concatenating $3$ single channel images. The resulting dataset has a $1000$ overall modes. We measure the number of modes covered by the generator as the number of classes that are generated at least once within a pool of $25,600$ sampled images. The class of the generated sample is identified with a pretrained MNIST classifier operating channel wise on the original stacked MNIST image. We also measure the KL divergence between the label distribution predicted by the MNIST classifier in the previous experiment and the expected data distribution. \newline \newline \noindent \textbf{Understanding the forgetting-collapse interplay}: In Section \ref{sec:intro}, we discuss our motivation for studying catastrophic forgetting for mitigating mode collapse. We also design an investigative experiment to explicitly observe this interplay by comparing the number of modes the generator learns against the quality of features the discriminator learns throughout GAN training on the stacked MNIST dataset. We measure the number of modes captured by the generator through a pre-trained classification network trained in a supervised learning fashion and frozen throughout GAN training. To measure the amount of \emph{`forgetting`} in discriminator, we extract features of real samples from the penultimate layer of the discriminator and train a small classifier on the real features for detecting real data mode. This implicitly indicates the quality and information contained in the the discriminator extracted features. However, the performance of classification network on top of discriminator features is confounded by the capacity of the classification network itself. Hence we do a control experiment, where we train the same classifier on features extracted from a randomly initialized discriminator, hence fixing a lower-bound to the classifier accuracy. \begin{table*}[t] \centering \resizebox{\textwidth}{!}{ \begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c} \toprule Classes & Plane & Car & Bird & Cat & Deer & Dog & Frog & Horse & Ship & Truck & Avg \\ \midrule BigGAN & $24.23$ & $12.32$ & $24.85$ & $21.21$ & $12.81$ & $22.74$ & $17.95$ & $13.16$ & $12.11$ & $18.39$ & $8.94$ \\ $+$ AMAT & $20.50$ & $10.30$ & $23.48$ & $18.48$ & $11.51$ & $19.41$ & $11.50$ & $12.24$ & $10.69$ & $12.94$ & $6.11$ \\ $\Delta \%$ & $18.2$ & $19.6$ & $5.8$ & $14.8$ & $11.3$ & $17.2$ & $\mathbf{56.1}$ & $7.5$ & $11.7$ & $\mathbf{42.1}$ & $\mathbf{46.3}$ \\ \bottomrule \end{tabular} } \vspace{3mm} \caption{\textbf{Per-class FID on CIFAR10}: FID improves consistently across all classes.} \label{tab:classwise} \vspace{-3mm} \end{table*} Referring to Figure \ref{fig:classification}, we observe a clear relation between the number of modes the generator covers at an iteration and the accuracy of the classification network trained on the discriminator features at the same iteration. In the vanilla single discriminator scenario, the classification accuracy drops significantly, indicating a direct degradation of the discriminative features which is followed by a complete collapse of G. In the collapse phase, the discriminator's learnt features are close to random with the classification accuracy being close to that of the control experiment. This indicates the presence of significant catastrophic forgetting in the the discriminator network. In contrast, training the same generator with the proposed AMAT procedure leads to stable training with almost all the modes being covered. The classification accuracy increasing before saturation. Catastrophic forgetting is \textit{effectively sidestepped} by adaptive multi adversarial training which produces stable discriminative features during training that provide a consistent training signal to the generator thereby covering all the modes with little degradation. \vspace{-2mm} \subsection{CIFAR10} \begin{figure*}[t!] \centering \begin{subfigure \centering \includegraphics[width=0.45\textwidth]{figs/gans.pdf} \end{subfigure} \hfill \begin{subfigure \centering \includegraphics[width=0.45\textwidth]{figs/gans_1d.pdf} \end{subfigure} \caption{\textbf{Sample Diversity on CUB200:} We showcase samples from a BigGAN pretrained on imagenet \& finetuned on CUB200 with the AMAT procedure (left) and from an identical BigGAN finetuned without AMAT (right). Observe that while the sample quality is good for both, the samples generated with AMAT are more colorful \& diverse, with bright reds and yellow against several backgrounds. While the samples from vanilla fine-tuning are restricted to whites/grays \& only a hint of color. } \label{fig:cub200} \vspace{-6mm} \end{figure*} We extensively benchmark AMAT on several GAN variants including unconditional methods such as DCGAN \citep{radford2015unsupervised}, ResNet-WGAN-GP \citep{gulrajani2017improved,he2016deep} \& SNGAN \citep{miyato2018spectral} and also conditional models such as BigGAN \citep{brock2018large}. Table \ref{tab:cifar} shows the performance gain on standard GAN evaluation metrics such as Inception Score and Fr\'echet distance of several architectures when trained with AMAT procedure. The performance gains indicate effective curbing of catastrophic forgetting in the discriminator with multi adversarial training. We use the public evaluation code from SNGAN \citep{miyato2018spectral} for evaluation. Despite having components such as spectral normalization, diversity promoting loss functions, additional R1 losses \& other stable training tricks that might affect catastrophic forgetting to different extents, we observe a consistent increase in performance across all models. Notably the ResNet GAN benefits greatly with AMAT despite a powerful backbone -- with IS improving from $6.7$ to $8.1$, indicating that the mode oscillation problem is not mitigated by simply using a better model. AMAT improves performance by over $35\%$ even on a well performing baseline such as BigGAN (Table \ref{tab:cifar}). We also investigate the classwise FID scores of a vanilla BigGAN and an identical BigGAN + AMAT on CIFAR10 and report the results in Table $\ref{tab:classwise}$. Performance improves across all classes with previously poor performing classes such as `Frog' \& `Truck' experiencing the most gains. Further, we also ablate several key components of the AMAT procedure on the BigGAN architecture with results reported in Table \ref{tab:ablations}. We observe all elements to be critical to overall performance. Specifically, having a moderate $\alpha$ schedule to avoid adding too many discriminators is critical. Also, another viable design choice is to effectively flip the algorithm's logic and instead choose the fake points randomly while being $\epsilon$ greedy on the real points. This strategy performs well on simple datasets but loses performance with BigGAN on CIFAR10 (Table \ref{tab:ablations}). In all the above experiments, the computational time during inference is the same as the base model, \textit{irrespective of the number of discriminators} added during the training, since only a single generator is trained with AMAT and all the discriminators are discarded. \vspace{-4mm} \section{Conclusion} \vspace{-3mm} In summary, motivated from the observation of catastrophic forgetting in the discriminator, we propose a new adaptive GAN training framework that adds additional discriminators to prevent mode collapse. We show that our method can be added to existing GAN frameworks to prevent mode collapse, generate more diverse samples and improve FID \& IS. In future, we plan to apply AMAT to fight mode collapse in high resolution image generation settings. \nocite{langley00}
{'timestamp': '2021-12-30T02:21:23', 'yymm': '2112', 'arxiv_id': '2112.14406', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14406'}
arxiv
\section{Introduction}\label{sec:introduction}} The use of unmanned aerial vehicles (UAVs) as base stations has emerged as a solution to address the demand for high-speed and reliable wireless communication in various scenarios. UAV base stations can be deployed easily, provide connectivity during emergency situations, and improve coverage and quality of service if needed. One of the challenging problems related to aerial base stations is the placement of the base station. The optimal base station altitude can be defined as the one that maximizes the coverage, which requires the prediction of path loss distribution in the target area. There are various models that can be used to estimate the path loss distribution, including Okumura \cite{sarkar2003survey}, Hata \cite{hata1980empirical} and Walfisch-Ikegami \cite{ChichonKurner1995} models. These models require a general classification of the area, such as "urban," "sub-urban," and "rural." Since such a rough classification of an area may not yield accurate predictions in all cases, there have been efforts to improve the results using additional information, such as the building density between transmitter and receiver \cite{5401041,6169225}. When the 3D model of an area is available, it is possible to apply ray tracing simulation techniques to get accurate results \cite{7913702, 6206329}. In addition to the requirement of a 3D model of the area, simulation based approaches have the disadvantage of high computational cost. There are articles specifically aiming to optimize the altitude of an aerial base station. For example, in \cite{al2014optimal}, air-to-ground channel is modeled as the addition of line-of-sight (LoS) and non-line-of-sight (NLoS) terms, where the probability of LoS depends on three parameters based on the ITU recommendation \cite{data2003prediction}: the ratio of building area to total area, the average number of buildings per unit area, and the height distribution of buildings. The formulation derived in \cite{al2014optimal} is used in other work, including \cite{alzenad20173}, where horizontal and vertical placements are decoupled, and \cite{kalantari2016number}, where the problem of placing multiple aerial base stations is addressed. In \cite{mozaffari2015drone}, using a probabilistic model for LoS, the downlink coverage performance of aerial base stations is investigated, and the optimal base station altitude, which leads to a maximum ground coverage and minimum required transmit power for a single base station, is derived. The work is extended for the placement of multiple aerial base stations in \cite{mozaffari2016efficient}. In \cite{8764728}, air-to-ground channels characteristics, including height-dependent path loss models, root mean square (RMS) delay spread and the number of multi-path components, at 3.9GHz for suburban areas and for UAV altitudes up to 40m are investigated and compared against ray tracing simulations. In \cite{8770066}, large-scale and small-scale channel parameters are extracted for LoS and NLoS cases at 1GHz and 4GHz from actual measurements; and an altitude-dependent path loss model is proposed. In \cite{7835273}, extensive measurements are taken to model air-to-ground channel characteristics, including path loss, RMS delay spread, Rician K-factor, and inter-antenna correlations for sub-urban and near-urban environments. In recent years, the use of machine learning techniques, including deep neural networks, in wireless communication applications has become increasingly popular \cite{zhang2019deep}. Machine learning based methods have been proposed to estimate path loss \cite{Zhang2019}, classify the area model selection \cite{5624542}, identify wireless technology \cite{8292183}, identify interference \cite{schmidt2017wireless}, and allocate resources \cite{8011311}. Deep neural networks have been used to predict path loss exponent and shadowing factor \cite{ates2019} and path loss distribution \cite{Omar2020}. In this paper, we propose a deep learning based approach to determine path loss distribution in an area and optimize aerial base station (transmitter) altitude. Motivated by the fact that regional characteristics, such as building densities and heights, play a major role in path loss values, we aim to predict the path loss distribution of an area directly from its satellite image, which captures all regional characteristics visually. Given a dataset of satellite images and corresponding path loss distributions, a deep neural network is trained to convert an image to the corresponding path loss distribution. Once the path loss distributions are estimated, the coverage, i.e., the percentage of the transmitters with path loss values less than a threshold in the region, is calculated. We design our network such that it produces path loss distributions for multiple base station altitudes. Therefore, we choose the altitude which results in the maximum coverage. Our work is unique in the sense that it allows determining the optimal base station altitude directly from a satellite image, which is input to a deep neural network to predict path loss distribution. The path loss distribution portion of our method has similarities to the work done in \cite{Omar2020}, but there are major differences. Other than the fact that \cite{Omar2020} does not involve any altitude optimization, the network in \cite{Omar2020} produces path loss distribution for a single transmitter altitude. In this paper, the network is designed to produce multiple path loss distributions, where each distribution corresponds to a different transmitter altitude. The work in \cite{Omar2020} can be extended for multiple altitudes; however, a separate network has to be trained and stored for each transmitter altitude. In this paper, the training process involves a single network, sharing common layers for different altitudes. This reduces the overall number of parameters to be learned, which is critical in deep learning to achieve better performance for a given dataset size. To train the proposed network, we first generate a dataset by running ray tracing simulations on 3D models of regions for which we have the satellite images as well. The ray tracing simulations produce path loss distributions, which are coupled with satellite images to form the dataset. A deep network is trained to produce path loss distributions for multiple altitudes from each satellite image. While the training process takes time, once trained, the network simply takes a satellite image to instantly produce multiple path loss distributions. \begin{figure*}[ht] \centering \includegraphics[width=16cm,page=1]{Figures/lastfig-min.pdf} \caption{A satellite image of a region, the corresponding path loss map obtained through ray tracing simulations, and the path loss distribution.} \label{powermap} \end{figure*} The paper is organized as follows. In Section~\ref{sec:approach}, the proposed approach is briefly presented. The details, including the dataset generation procedure and the deep neural network architecture, are given in Section~\ref{sec:dataset} and Section~\ref{sec:prediction}, respectively. The performance of the deep neural network, the details of altitude optimization process, and the experimental results are discussed in Section~\ref{sec:results}. Finally, in Section~\ref{sec:conclusion}, the paper is concluded with a summary and possible future work. \begin{figure*}[ht] \centering \includegraphics[width=16.4cm]{Figures/approach4.pdf} % \caption{(a) A satellite image of the target region is input to a deep neural network to produce path loss distributions at multiple altitudes. The network consists of a convolutional neural network (CNN) layer, followed by several fully connected layers (fc). The output layer is designed such that the path loss distribution for a specific transmitter height (${h}_i$) is produced at a specific part of the output. The initial portion of the network is taken from the VGG16 network \cite{vgg16}; the entire network is re-trained for our dataset. (b) A threshold value is chosen to determine the coverage. Receivers with path loss value greater than the threshold are not covered by the transmitter. Path loss distributions are passed through the threshold to determine the ratio of covered receivers. The altitude that has the maximum coverage ratio is the optimum altitude.} \label{fig:PredictionModel} \end{figure*} \section{Overview of the Proposed Approach} \label{sec:approach} The base station altitude optimization problem is defined as determining the altitude which results in the maximum number of serviceable receivers. Received signal strength, which is a function of the operation frequency, transmit power of the base station, antenna gains of the transmitter and receiver, and path loss, determines if a receiver is in the coverage area or not. Assuming there is only one transmitter and the receivers are of same type, the path loss becomes the only variable determining the coverage. The maximum allowable path loss, which we denote $PL_{th}$, can be set as the threshold; any receiver with path loss higher than this threshold is considered out of coverage. Fig. \ref{powermap} gives an illustration of path loss map and path loss distribution of an area. On the left of the figure, we have a satellite image of a region. The 3D model, which is not shown, of the region is input to a ray tracing software to obtain the path loss values of the receivers, which are uniformly distributed over the entire area. The path loss values are shown as a color map in the middle of the figure. The path loss values are quantized to 26 bins (with 3dB bin widths) to form the path loss distribution, which is shown on the right of the figure. The coverage (the ratio of serviceable receivers with path loss value less than a specific threshold) is calculated by summing up the path loss values less than the threshold. To determine the optimal altitude which yields the maximum coverage, we need to have path loss distributions corresponding to different base station altitudes. We, therefore, design our path loss estimation network to generate path loss distributions for multiple altitudes in a single inference. Our approach is illustrated in Fig.~\ref{fig:PredictionModel}. An image is input to a deep neural network, which consists of convolutional layers and fully connected layers. The convolutional layers extracts high and low level features, which are then flattened passed through several fully connected layers. The output of the network is a vector, which has path loss distributions for different transmitter altitudes in its designated parts. The path loss distributions are then passed through a specified threshold value to calculate coverage for each altitude. The altitude maximizing the coverage is set as the optimum altitude. Training a deep network requires a large dataset. In cases where the dataset size is limited, a common practice is to take a pre-trained network and re-train it with the available data for the desired application. We use this technique in our application. Specifically, we took a portion of the pre-trained VGG16 network \cite{vgg16}, appended two fully connected layers, and trained the entire network with our data. The VGG16 is pre-trained on the ImageNet dataset \cite{imagenet}, and it extracts high and low level image features, representing the regional characteristics. The fully connected layers convert these features path loss distributions. \section{Dataset Generation} \label{sec:dataset} The data requirement for training a deep neural network is extremely large. Generating the dataset using actual measurements were not feasible due to time, cost and legal issues of flying UAVs in urban areas. Therefore, we use the dataset generation method presented in \cite{ates2019}. Using areas with known 3D models, ray tracing simulations are used to obtain the path loss at each receiver point for each transmitter altitude. The received path loss values are then converted to path loss distributions. Specifically, 500 geographical regions, each with a size of $1.8 \times 1.8$ km, are extracted as in \cite{ates2019}. For each region, we have the satellite image as well as the 3D model. Each 3D model is imported to a ray tracing simulation software.\footnote{https://www.remcom.com/wireless-insite-em-propagation-software} The transmitter is placed in the center of the region at a specific height. We placed 12,100 ($110 \times 110$) receivers uniformly distributed over the region at 1.5 meters above ground. We assume having a flat terrain with dry earth material and concrete buildings. We run the simulations for each transmitter altitude and each region separately. We choose 40m, 80m, 120m, and 300m as the representative set of transmitter altitudes in our experiments. The parameters used in the dataset generation are listed in Table \ref{params}. The resulting path loss values at the receivers are processed to generate the path loss distributions. The path loss values corresponding to receivers that are inside a building are removed by utilizing the 3D models, which indicate the building locations. The remaining path loss values are quantized to 26 bins, starting from 55dB to 130dB bin centers, and bin widths of 3dB. The distributions are normalized so that the bin values add up to one for each distribution. We repeat the simulations for 4 different altitudes. The path loss distributions for each altitude are concatenated to construct a target vector of size 104-by-1. By repeating the simulations for different target areas, we construct a dataset of 500 images and corresponding target vectors. \begin{table}[ht] \centering \resizebox{7cm}{!}{\begin{tabular} {|l|l|} \hline Transmission frequency & 900 MHz \\ \hline Transmission altitudes & 40, 80, 120 and 300 m \\ \hline Transmitted power & +43 dBm \\ \hline Receiver sensitivity & -85 dBm \\ \hline Antenna radiation pattern & Omni-directional \\ \hline Receiver antenna height & 1.5 m \\ \hline Antenna polarization & Vertical \\ \hline Transmitted signal & Sinusoid \\ \hline Bandwidth & 8 MHz \\ \hline \end{tabular}} \caption{Ray tracing simulation parameters.} \label{params} \end{table} \section{Network Architecture} \label{sec:prediction} The input to the network is of size $224 \times 224 \times 3$. The network produces 104 values, corresponding to path loss distributions for four transmitter heights. The network consists of a common pre-trained network (VGG16~\cite{vgg16}) followed by fully connected layers. The VGG16 network is a well-known architecture used for image classification; and it is pre-trained on the ImageNet dataset \cite{imagenet}. This portion of the network extracts the common features associated with the region. These features include low-level features such as lines, edges, corners, and other primitive features, as well as high-level features such as geometric structures and shapes with different colors and texture. Our intuition is that these features well describe the regional characteristics that directly affect the communication channel properties of the area. The last layers allow specialization/prediction of distributions for different altitudes by properly weighting the features extracted from the common layers. The final layer is a 104 unit layer with a softmax function at the end. The dataset is divided into 400 images for training and 100 images for testing. During training, the stochastic gradient descent optimizer \cite{bottou1991stochastic} is used with a learning rate of 0.0001, a momentum of 0.7, a batch size of 8, and cross-entropy as the loss function. The network can be modified (by reducing the size of the bin width and therefore increasing the number of bins) to increase the resolution of path loss distributions. This would increase the number of parameters to be learned during training; and we would need more data to successfully train the network parameters. Similarly, we can add more altitudes to the network, which would again require more training data. \section{Results and Discussions} \label{sec:results} \subsection{Deep learning model performance} The mean squared error (MSE) between the true and predicted path loss distribution values is used to evaluate the network performance. Table \ref{tab:MSE} shows the MSE for each altitude. By comparing the MSE results to the variance of the true distribution values in the test set, it can be seen that the network is predicting the true distributions well. From the table, we notice that the prediction performance is better for higher altitudes. This improvement is due to the higher probability of LoS links for high altitudes. When the UAV is at a low altitude, such as $40$m, the communication link may suffer from shadowing due to high building, making it more difficult to predict path loss. \begin{table}[ht] \centering \begin{tabular}{|c|c|c|} \hline Altitude & MSE [$10^{-3}$] & Test set variance [$10^{-3}$] \\ \hline $40$ m & 0.65 & 4.29 \\ \hline $80$ m & 0.32 & 2.61 \\ \hline $120$ m & 0.21 & 2.44 \\ \hline $300$ m & 0.11 & 4.42 \\ \hline \end{tabular} \caption{MSE between the true and predicted distribution values, and the variance of the true distribution values in the test set.} \label{tab:MSE} \end{table} In Fig.~\ref{regression_plot}, the true versus predicted path loss distribution values are shown for the entire test set. We note that the predicted path loss values match the true values well, except for a relatively small number of outliers. In Fig.~\ref{tab:Output_Samples}, we provide some examples of the test set showing the true versus predicted distributions with the corresponding satellite images. The regions are arranged from best to worst according to the average MSE of the four altitudes; the average MSE is written above each image. We notice that regions with low MSE values correspond to sub-urban areas. The MSE increases in the regions where there are high-rise buildings, causing extreme shadowing and multi-path reflections. In the last example, there is a high-rise building in the middle of the region, blocking the transmitter signal and resulting in high path loss at almost all receiver locations. As the transmitter altitude is increased, the receivers finally start get the signal from the transmitter. Even in such challenging situations, the network predicts the distributions well. \begin{figure} \centering \includegraphics[page=2,scale=0.5]{Figures/vgg16_output3.pdf} \caption{True versus predicted path loss distribution values.} \label{regression_plot} \end{figure} Fig.~\ref{tab:Output_Samples} also includes the results of two baseline methods, i.e., the free-space path loss model \cite{sarkar2003survey} and the Okumura-Hata model \cite{hata1980empirical}. The distributions predicted with the free-space path loss and Okumura-Hata models do not match well with the true distributions as these prediction methods are generic models with few categories for the regional characteristics and can not handle all sorts of variations. On the contrary, our approach can extract the regional characteristics and provide more accurate predictions. \begin{figure*} \begin{tabular}{llll} & \begin{minipage}{1in} \includegraphics[page=13,scale=0.5,trim=0.5cm 0cm 0cm 0cm]{Figures/vgg16_output2_compressed.pdf} \end{minipage} & \begin{minipage}{1in} \includegraphics[page=103,scale=0.5,trim=0.5cm 0cm 0cm 0cm]{Figures/vgg16_output2_compressed.pdf} \end{minipage} & \begin{minipage}{1in} \includegraphics[page=55,scale=0.5,trim=0.5cm 0cm 0cm 0cm]{Figures/vgg16_output2_compressed.pdf} \end{minipage} \\ & \begin{minipage}{2in} \includegraphics[page=14,scale=0.35]{Figures/vgg16_okufree_rural.pdf} \end{minipage} & \begin{minipage}{2in} \includegraphics[page=104,scale=0.35]{Figures/vgg16_okufree_suburban.pdf} \end{minipage} & \begin{minipage}{2in} \includegraphics[page=56,scale=0.35]{Figures/vgg16_okufree_urban.pdf} \end{minipage} \\ & \begin{minipage}{1in} \includegraphics[page=99,scale=0.5,trim=0.5cm 1cm 1cm 0.1cm]{Figures/vgg16_output2_compressed.pdf} \end{minipage} & \begin{minipage}{1in} \includegraphics[page=159,scale=0.5,trim=0.5cm 1cm 1cm 0.1cm]{Figures/vgg16_output2_compressed.pdf} \end{minipage} & \begin{minipage}{1in} \includegraphics[page=201,scale=0.5,trim=0.5cm 1cm 1cm 0.1cm]{Figures/vgg16_output2_compressed.pdf} \end{minipage} \\ & \begin{minipage}{2in} \includegraphics[page=100,scale=0.35]{Figures/vgg16_okufree_rural.pdf} \end{minipage} & \begin{minipage}{2in} \includegraphics[page=160,scale=0.35]{Figures/vgg16_okufree_suburban.pdf} \end{minipage} & \begin{minipage}{2in} \includegraphics[page=202,scale=0.35]{Figures/vgg16_okufree_urban.pdf} \end{minipage} \\ \end{tabular} \caption{Sample results of the proposed path loss distribution method, compared to the true distributions, and against the free-space and Okumura-Hata models for different regions and transmitter altitudes.} \label{tab:Output_Samples} \end{figure*} \begin{figure*} \centering \begin{tabular}{cc} \includegraphics[page=1,scale=0.42]{Figures/covplot2dtrlog.pdf} \\ \includegraphics[page=9,scale=0.42]{Figures/covplot2dtrlog.pdf} \\ \includegraphics[page=8,scale=0.42]{Figures/covplot2dtrlog.pdf} \end{tabular} \caption{Coverage percentages as a function of UAV altitude and path loss threshold levels for three sample regions.} \label{Output_Samples_true} \end{figure*} \subsection{Altitude optimization} UAV altitude optimization can be done by choosing the altitude that has the maximum coverage, which is defined as the area under the path loss distribution curve below a specific threshold value. Since the distributions are quantized, the coverage is calculated by summing the values that are below the threshold value. To investigate altitude optimization, we performed additional simulations for different altitudes, for a few regions. Fig.~\ref{Output_Samples_true} shows the coverage curves for three different regions at seven different altitudes ($40$m, $80$m, $120$m, $160$m, $300$m, $600$m, $1500$m), and for five different path loss threshold values ($116$dB, $119$dB, $122$dB, $125$dB, $128$dB). In each row of the figure, we have the satellite image of the region, the coverage as a function of transmitter altitude, and the coverage as a function of path loss threshold. \begin{table*} \centering \resizebox{\textwidth}{!}{\begin{tabular}{|l|l||*{8}{c|}} \cline{3-10} \multicolumn{2}{c|}{}&\multicolumn{2}{c|}{\textbf{40 m}}& \multicolumn{2}{c|}{\textbf{80 m}}&\multicolumn{2}{c|}{ \textbf{120 m}}& \multicolumn{2}{c|}{\textbf{300 m}} \\ \hline Satellite image &$PL_{th}$&True&Predicted&True&Predicted&True&Predicted&True&Predicted \\ \hline \hline \multirow{4}{*}{\includegraphics[page=55,scale=0.14,trim=1cm 1cm 1cm 1cm,clip]{Figures/vgg16_output2_compressed.pdf}}& 128 dB & 0.8849 &0.9153 &0.9643&0.9701 & \textcolor{red}{\textbf{0.9657}} &\textcolor{red}{\textbf{0.9802}} &0.9532&0.978 \\ & 125 dB & 0.8614 &0.8933 & 0.9479 &0.9598 & \textcolor{red}{\textbf{0.9512}} &\textcolor{red}{\textbf{0.9713}} & 0.9337&0.966 \\ & 122 dB & 0.8316 &0.864 & 0.925 &0.9429 &\textcolor{red}{\textbf{0.9308}} &\textcolor{red}{\textbf{0.9582}} &0.9092 & 0.9487 \\ & 119 dB & 0.7949 &0.8294 & 0.8898 &0.9222 & \textcolor{red}{\textbf{0.9052}}&\textcolor{red}{\textbf{0.9417}} & 0.8799& 0.9262 \\\hline \multirow{4}{*}{\includegraphics[page=77,scale=0.14,trim=1cm 1cm 1cm 1cm,clip]{Figures/vgg16_output2_compressed.pdf}}& 128 dB &0.962 &0.9209 & 0.9681 &\textcolor{red}{\textbf{0.9808}} &\textcolor{red}{\textbf{0.969}} &0.9786 &0.9659 &0.9805 \\ & 125 dB & 0.952 & 0.902 & \textcolor{red}{\textbf{0.9614}} & \textcolor{red}{\textbf{0.9722}} & 0.9609 & 0.9705 &0.9538 & 0.9688\\ & 122 dB & 0.9371 &0.8753 & \textcolor{red}{\textbf{0.9531}} & 0.9575 & 0.953 & \textcolor{red}{\textbf{0.9593}} &0.9402 & 0.9502 \\ & 119 dB & 0.9186 &0.845 & 0.9405 &0.9379 & \textcolor{red}{\textbf{0.9426}}&\textcolor{red}{\textbf{0.9431}} & 0.9183 &0.924 \\\hline \multirow{4}{*}{\includegraphics[page=199,scale=0.14,trim=1cm 1cm 1cm 1cm,clip]{Figures/vgg16_output2_compressed.pdf}}& 128 dB &0.1776 & 0.6299 &0.7695 &0.8105 &0.8787 & 0.8743 &\textcolor{red}{\textbf{0.9687}} & \textcolor{red}{\textbf{0.9988}}\\ & 125 dB &0.131 & 0.5816 &0.7338 &0.7786 &0.8537 &0.8492 &\textcolor{red}{\textbf{0.9503}} & \textcolor{red}{\textbf{0.9827}}\\ & 122 dB & 0.0796&0.5468 & 0.6988&0.7437 & 0.829&0.8217 & \textcolor{red}{\textbf{0.9308}}&\textcolor{red}{\textbf{0.9625}} \\ & 119 dB & 0.0415&0.5017 &0.665 &0.7019 & 0.7968&0.7908 & \textcolor{red}{\textbf{0.9102}}&\textcolor{red}{\textbf{0.9366}} \\ \hline \end{tabular}} \caption{Coverage values calculated from true distributions and predicted distributions at different path loss thresholds $PL_{th}$ for various regions. Highest true and predicted coverage values are highlighted in "red" color.} \label{tab:compare} \end{table*} In the first region, there are relatively few buildings. This means, the region can be covered well with LoS links even when the UAV altitude is low. As the altitude becomes higher, the coverage drops because of the reduction in signal strength. (See the coverage-altitude plot.) As the path loss threshold value is increased, we get more coverage as expected. In the second and the third regions, there are more buildings; therefore, low UAV altitudes result in less coverage. Better coverage can be achieved by increasing the UAV altitude. As the UAV altitude is increased, the coverage eventually starts to decay due to the increasing distance between the transmitter and receiver. The optimum altitude for the second region is higher than the optimum altitude for the third region because of the existence of high-rise buildings in the second region. For a path loss threshold of $128$dB, a coverage of about $95\%$ is achieved when the transmitter is at $600$m for the second region; whereas, the optimum coverage is achieved when the transmitter is at $300$m for the third region. We can also make further deductions by investigating the coverage-altitude and coverage-threshold plots. For example, in the first region, where we mostly have LoS links, the coverage changes little for $40$m to $600$m. The effect of altitude is more when there are buildings in the region, as in the cases of second and third images. Combining the path loss distribution estimations from the deep network and the altitude optimization process, we have a complete flow from an image to an optimum altitude. We tested the process with the path loss distributions obtained from the deep network. In Table \ref{tab:compare}, we exemplify coverage values obtained from true distributions and predicted distributions. We show two correct and one incorrect altitude selection. In the first and third regions, both the true distributions and predicted distributions result in the same altitude, 120m and 300m, respectively. In the second example, predicted distributions resulted in incorrect optimum altitudes for two threshold values. Even in those few incorrect cases the coverage values are close to each other at different altitudes, meaning that even an incorrect altitude is selected, similar coverage would be achieved. \section{Conclusions} \label{sec:conclusion} In this paper, we present a deep learning based approach to estimate the path loss distributions in an area for multiple altitudes in a single inference from a 2D satellite image, and then use the predicted path loss distributions to optimize the altitude of a UAV, serving as a base station in an air-to-ground communication systems. The training process of the deep neural network is computational demanding; but once the network is trained, the inference can be done accurately in real time. This is a significant advantage over ray tracing simulations. While we demonstrated the idea for four different altitudes due to the extensive simulation requirements to obtain the training dataset for each altitude, the approach can be extended for more altitudes. The main challenge is the dataset generation process, which require many satellite images and ray tracing simulations on the 3D models corresponding to the satellite images. Similarly, the method can be extended for other transmission frequencies. Another possible extension of this work is to move the transmitter position in large satellite image, crop a target region centered around the transmitter position, and predict the path loss distributions for each transmitter position using the cropped target region. In this way, both the optimum altitude and position can be determined. \bibliographystyle{IEEEtran}
{'timestamp': '2021-12-30T02:27:31', 'yymm': '2112', 'arxiv_id': '2112.14551', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14551'}
arxiv
\section{Introduction} With the development of information technology, most of the engineering and science records are currently stored in computers with the electronic forms, such as earthquake records \cite{1ogata1981lewis}, medical records \cite{2johnson2016mimic}, public safety records \cite{3mohler2018improving}, failure records \cite{4zhang2020survival}, and so on. Meanwhile, with the increase of internet applications, these diverse applications also lead to a large number of records, like IPTV records \cite{5luo2014you} and social network records \cite{6zhao2015seismic}. In general, these records are in the form of asynchronous sequence data, which contain the event occurring time and type of event. These event sequence data contain a lot of valuable knowledge, which can be used to understand the relationship between events, predict possible future events, as well as the time of occurrence, and so on. How to mine the knowledge from these asynchronous sequences is a subject worthy of continued attention, and one of the most widely used methods is the point process model \cite{7daley2007introduction}, and the most commonly used model in the point process model is the Hawkes process model \cite{8hawkes1971spectra}. In previous years, because the Hawkes process with self-excited characteristics can well model the trigger mode between events, the traditional Hawkes process is widely applied in many fields. For instance, Ogata utilizes space-time Hawkes process to analyze the earthquake and corresponding aftershock \cite{1ogata1981lewis}. Zhao et al. make use of the Hawkes process to predict the popularity of tweets on Internet \cite{6zhao2015seismic}. Reynaud-Bouret et al. provide a new way to detect the distances between genomic events on the DNA (Deoxyribonucleic Acid) sequences \cite{9reynaud2010adaptive}. Kobayashi and Lamhbiotte \cite{10kobayashi2016tideh} present a new framework of the time-dependent Hawkes process, whose impact functions are time-dependent. They make use of this model to reveal the periodic characteristics of Twitter reposting. Xu et al. utilize the Hawkes process to uncover the Granger causality between users choosing to watch TV programs \cite{11xu2016learning}. Zhou et al. present ADMM (Alternating Direction Method of Multipliers)-based algorithm to train the Hawkes process to find out the relationship between the social media user \cite{12zhou2013learning}. Unfortunately, there are two critical inherent shortcomings for the traditional Hawkes process, one shortcoming is that the traditional Hawkes process ignores the influence of mutual inhibition between events, which does not conform to the actual situation to a certain extent. Another shortcoming is the lack of strong nonlinear fitting capability in the traditional Hawkes process, which also limits the expressive ability of the model. Therefore, to mitigate the above problem, and with the development of neural networks and deep learning, also due to the ability to effectively model sequence data of recurrent neural network (RNN), the Hawkes process models based on RNN are proposed. For example, Du et al. embed sequence data information (including time-stamp and event type) into RNN and propose recurrent marked temporal point processes (RMTPP) to model the conditional intensity function considering the historical nonlinear dependence \cite{13du2016recurrent}. Similar to RMTPP, Mei et al. propose a continuous-time LSTM (Long Short-Term Memory) to simulate the conditional intensity of point processes, which is called neural Hawkes processes \cite{14mei2017neural}. In this continuous neural Hawkes process, the effect of the previous event is decreasing with time. And in \cite{15xiao2017modeling} two RNNs are used to model the conditional intensity function, one is for processing time-stamp information and the other for processing historical event information. The goals of these models are effectively model the sequence data, and accurately predict the types of events that will occur in the future and the moments of event occurrence. For instance, for electronic medical records, we can predict the types and times of the next attack based on the patient’s medical history, and provide more effective and timely help for the patient's treatment. We can also predict the next possible failure time and type for a large-scale production system based on the failure sequence, and perform maintenance and prevention in advance to improve safety and economic benefits for the production process. However, these models based on RNN inevitably inherit the disadvantages of RNN. For example, for certain chronic sequelae, it may take a long time for patients to develop symptoms. These sequelae may have obvious long-term characteristics, such as diabetes, cancer, and other chronic diseases. These RNN-based models are difficult to describe the long-term dependence between events with a long sequence distance \cite{16bengio1994learning}, while the ideal point process model should be able to attack these problems. Moreover, when training RNN-based models, problems such as gradient vanishing and explosion \cite{17pascanu2013difficulty} often appear, this will necessarily impact the performance of the model. Fortunately, RNN is not the only choice of sequential modeling now, with the advent of self-attention mechanism \cite{18DBLP:journals/corr/BahdanauCB14}, sequence models in literatures have become vast and are growing rapidly, among them, the most striking one, transformer \cite{19vaswani2017attention}, are developed and applied to speech recognition \cite{20yu2016automatic}, machine translation \cite{21koehn2009statistical}, video recognition \cite{22girdhar2019video} and other fields. Inspired by these successes, Zhang et al. present the self-attention Hawkes process \cite{23zhang2020self}, furthermore, Zuo et al. propose transformer Hawkes process based on the attention mechanism and encoder structure in transformer \cite{24DBLP:conf/icml/ZuoJLZZ20}. But for the existing attention Hawkes model, the input feeding into the transformer is a simple stacking of the event encoding and the temporal position encoding, while we tend to extract the existing underlying intrinsic information in the event type and the time stamp in the event sequence. Therefore, inspired by the relative encoding Hawkes process \cite{25dai2019transformer,26al2019character}, we modify the traditional dot product attention and propose a new dot product attention mechanism, which additionally introduces temporal encoding as input to the attention mechanism, we dub this model as Temporal Augmented Attention Transformer Hawkes Process (TAA-THP). Our paper is organized as follows. In section 2, we systematically introduce the related work of our methods, and next, we describe our model in detail, which is related to the modified dot-product temporal augmented attention structure, and the acquisition of conditional intensity function based on the hidden representation of events sequences. In section 4, we instruct the prediction method and the objective function of TAA-THP. Then, we conduct the experiments to confirm the effectiveness of the TAA-THP model, we also perform the ablation study to figure out the impact of the introduction of temporal attention. At last, we summarize our research work and look forward to future research directions. \section{Related work} \subsection{Traditional Hawkes process} Hawkes process is one of the most widely applied point process models in sequential modeling, which is proposed by Alan Hawkes in 1971 \cite{8hawkes1971spectra}. The general paradigm of Hawkes process is shown as Eq. \ref{eq1}: \begin{equation} \label{eq1} \lambda (t) = \mu (t) + \sum\limits_{i:t_i < t} {\phi (t - t_i )} \end{equation} where $\mu (t)$ is the background intensity function, describes the base possibility of event occurrence over time, $\phi (t)$ is the impact function, which is used to represents the historical event impact, and $\sum\limits_{i:t_i < t} {\phi (t - t_i )} $ records all the impact of history events to this current instant $t$. The traditional Hawkes process model in Eq. \ref{eq1} ignores the inhibition effect between the events, and until now, there are still countless variants based on this model in various application fields. Mohler proposes a novel modulated Hawkes process, to quickly identify risks to protect communities from a range of social harm events, such as crime, drug abuse, traffic accident and medical emergencies \cite{3mohler2018improving}. Zhang et al. \cite{4zhang2020survival} use the Weibull background intensity instead of the constant background intensity, which can better model the trend of failure occurrence over time, Zhang et al. verify the effectiveness of the Weibull-Hawkes process, and reveal the trend of background probability of failures in the compressor station over time and the Granger causality between the failures. Xu et al. \cite{5luo2014you} use the non-parametric Hawkes process model, and a corresponding learning algorithm to obtain the Granger causality on of IPTV users on watching the program. Kobayashi and Lamhbiotte use the time-dependent Hawkes process to prove that Twitter reposts have a clear tidal effect \cite{10kobayashi2016tideh}. Yang et al. \cite{27yang2017online} come up with an online learning method of Hawkes process based on the nonparametric method. In 2018, Alan reviews and summarizes the application of the Hawkes process in the financial field \cite{28hawkes2018hawkes}. Hansen et al. show powerful expressive ability in describing the neural excitation process of Hawkes process in neuroscience with the Lasso (Least absolute shrinkage and selection operator) method \cite{29hansen2015lasso}. \subsection{Neural Hawkes Process} Du et al. present the RMTPP models \cite{12zhou2013learning}, which can learn the history effect through RNN, including history event type and time-stamp. This model abandons the restrictions of the Hawkes process and other point process models firstly and achieves improvements than the traditional Hawkes process. Xiao et al. \cite{15xiao2017modeling} utilize two RNN to model the event sequence, one of them is used to model the background intensity and the other is used to model the impact of historical events. Mei and Eisner \cite{14mei2017neural} propose a new LSTM, i.e., the continuous-time LSTM, whose state can decay with time, and based on this LSTM, they come up with the neural Hawkes process to model the asynchronous event sequence. With the mature self-attention mechanism, the self-attention-based neural Hawkes processes are proposed, the self-attention Hawkes process is the first model which utilizes the self-attention mechanism \cite{23zhang2020self}. Based on the success of the transformer, Zuo et al. utilize the encoder structure in the transformer to get the hidden representation of sequences data, and then convert it to the continuous conditional intensity functions \cite{24DBLP:conf/icml/ZuoJLZZ20}. In recent researches about the neural Hawkes process, the self-attention Hawkes process and transformer Hawkes process achieve great success, which are on the foundation of self-attention mechanism, thus we also focus on the self-attention in our proposed TAA-THP. \subsection{Transformer models} In 2017, Vaswani et al. propose the transformer model \cite{19vaswani2017attention}, which makes full use of self-attention mechanism \cite{18DBLP:journals/corr/BahdanauCB14}, and achieves great success in sequence learning. The architecture of transformer is shown as Fig.\ref{fig1}. \begin{figure}[!htbp] \centering \includegraphics[scale=1]{transformer.pdf} \caption{The architecture of transformer model} \label{fig1} \end{figure} The transformer model is made up of multiple encoder and decoder modules and there are the only self-attention mechanism and position-wise-feed-forward structure without using the recurrence neural network architecture. Meanwhile, recent researches shows that recurrent learning may be more important beyond imagination in sequential learning, thus, Dehghani et al. propose the universal transformer \cite{30DBLP:conf/iclr/DehghaniGVUK19}, which combine the recurrent learning and self-attention mechanism, moreover, in order to better allocate model computing resources, the Adaptive Computation Time (ACT) mechanism \cite{31graves2016adaptive} is introduced into models, then, this model achieves better results than transformers and also achieves Turing completeness. Dai et al. come up with a new transformer called Transformer-XL \cite{25dai2019transformer}, which consists of a segment-level recurrence mechanism and a novel positional encoding scheme, not only does the model perform better, the learning speed is also faster than previous models. \section{Proposed Model} In this section, we are going to introduce the details of the temporal attention augmented transformer Hawkes process, including its model structure and corresponding continuous conditional intensity function. We list the notations used in this paper, which is shown in Table 1. \begin{table}[!htbp] \centering \caption{Nomenclature} \label{tb1} \begin{tabular}{ccc} \hline Symbols & Description & Size\\ \hline $S_e$ & The dataset of sequences & / \\ $s_n$ & The $n$-th sequence & / \\ $I_n$ & The length of the $n$-th sequence & $\mathbb{N}^+$ \\ $N$ & The total number of sequences& $\mathbb{N}^+$ \\ $C$ & The total number of type of events in sequences & $\mathbb{N}^+$ \\ $t_i$ & The time stamp of \textit{i}-th event & $\mathbb{R}$ \\ $c_i$ & The event type of \textit{i}-th event & $\mathbb{N}^+$ \\ $D$ & The model dimension of transformer & $\mathbb{N}^+$ \\ $D_H$ & The dimension of position-wise-feed-forward part of transformer & $\mathbb{N}^+$ \\ $\bm{x}$ & The temporal position encoding & $\mathbb{R}^D$ \\ $\bm{E}$ & The embedding matrix of event type & $\mathbb{R}^{D\times C}$ \\ $\bm{c_i}$ & one-hot encoding vector of each event & $\mathbb{R}^C$ \\ $L$ & The number of multi-head attention & $\mathbb{R}$ \\ $\left\{ {{\mathbf{A}}_l } \right\}_{l = 1}^L $ & The attention variable of multi-head attention & ${\mathbb{R}}^{D_V}$ \\ $D_K$ & The dimension of query and key vector & $\mathbb{N}^+$ \\ $D_V$ & The dimension of value vector & $\mathbb{N}^+$ \\ $\bm{S}$ & State & $\mathbb{R}^{D}$ \\ $\left\{ {{\bm{Q}}_l } \right\}_{l = 1}^L $ & The query variable of multi-head attention & $ \mathbb{R}^{I_n \times D_K } $ \\ $\left\{ {{\bm{K}}_l } \right\}_{l = 1}^L $ & The key variable of multi-head attention & $ \mathbb{R}^{I_n \times D_K } $ \\ $\left\{ {{\bm{V}}_l } \right\}_{l = 1}^L $ & The value variable of multi-head attention & $ \mathbb{R}^{I_n \times D_V } $ \\ $\left\{ {{\bm{W}}_Q^l } \right\}_{l = 1}^L$ & The query matrix of multi-head attention & $\mathbb{R}^{D \times D_K } $ \\ $\left\{ {{\bm{W}}_K^l } \right\}_{l = 1}^L$ & The key matrix of multi-head attention & $\mathbb{R}^{D \times D_K } $ \\ $\left\{ {{\bm{W}}_V^l } \right\}_{l = 1}^L$ & The value matrix of multi-head attention & $\mathbb{R}^{D \times D_V } $ \\ $\left\{ {{\bm{W}}_{Tem}^l } \right\}_{l = 1}^L$ & The temporal attention variable of multi-head attention & $\mathbb{R}^{D \times D_K } $\\ $\left\{ {{\bm{b}}_{lq} } \right\}_{l = 1}^L $ & The bias of dot-product attention & $\mathbb{R}^{D_K } $ \\ $\left\{ {{\bm{b}}_{lq} } \right\}_{l = 1}^L $ & The bias of temporal attention & $\mathbb{R}^{D_K } $ \\ $\bm{W}_multi$ & The aggregation matrix of multi-head attention & $\mathbb{R}^{L{D_V}\times D } $ \\ $\left\{ {{\bm{W}}_i^{FC} ,{\bm{b}}_i^{FC} } \right\}_{i = 1}^4$ & The parameters of fully connected neural network & / \\ $\bm{H}$ & The hidden representation of sequence & $\mathbb{R}^{I_n\times D}$ \\ $\bm{h}(t_i)$ & The hidden representation of \textit{i}-th event & $\mathbb{R}^{D}$ \\ $\mathcal{H}_t$ & The previous history at time \textit{t} & \\ $b_c$ & The background intensity of event type \textit{c} & $\mathbb{R}$ \\ ${\bm{w}}_{\alpha _c } $ & The weight of continuous parameter of conditional intensity function of event type & $\mathbb{R}^{1\times D}$ \\ ${\bm{w}}_c^T $& Historical weight parameter of conditional intensity function of event type & $\mathbb{R}^{1\times D}$ \\ $\bm{W}_{time}$ & The prediction parameter of time-stamp & $\mathbb{R}^{1\times D}$ \\ $\bm{W}_{type}$ &The prediction parameter of event type & $\mathbb{R}^{C\times D}$ \\ \hline \end{tabular} \end{table} \subsection{Temporal Attention Augmented Transformer Hawkes Process} Generally speaking, transformer-based Hawkes process model utilizes the encoder structure of different kinds of the transformer to get the hidden representation of event sequence. Assuming there are sequences in the dataset $S_e$ , and the $n$-th sequence is $s_n = \{ t_i ,c_i \} _{i = 1}^{I_n } $ , whose length is $I_n$ . Each pair in $S_n$ is composed with two parts, e.g., $t_i$ and $c_i$ . Among them, $c_i$ is the type of event that occurred and $t_i$ is the corresponding time-stamp. Following point process theory, time-stamp is the event occurring instant in tandem along the time axis, which is consistent with the position encoding of the transformer-based model for asynchronous sequences. Thus, we can make use of this general method to encode the timestamp as a positional encoding, similar to other transformer-based models \cite{19vaswani2017attention}, and \cite{24DBLP:conf/icml/ZuoJLZZ20}, which is shown in Eq.\ref{eq2}: \begin{equation} \label{eq2} [{\bm{x}}(t_i )]_j = \left\{ {\begin{array}{*{20}c} {\cos \left( {t_i /10000^{\frac{{j - 1}}{D}} } \right),{\rm{if}}\:j\:{\rm{is}}\:{\rm{odd}},} \\ {\sin \left( {t_i /10000^{\frac{j}{D}} } \right),{\rm{if}}\:j\:{\rm{is}}\:{\rm{even}}.} \\ \end{array}} \right. \end{equation} where $\bm{x}$ is the position encoding for transformer model, throughout the latter part of the paper, we will call it as temporal encoding, and $D$ is the dimension of transformer model. For the event encoding, we utilize one-hot encoding vector of each event ${\mathbf{c}}_i \in \mathbb{R}^C $, and embedding matrix ${\mathbf{E}} \in \mathbb{R}^{D \times C}$ to get it. In this way, we can get ${\bm{X}}^T$ and $({\bm{EC}}_n )^T $, which are the corresponding temporal encoding and event encoding of the sequence, where ${\bm{X}} = \{ {\bm{x}}(t_1 ),{\bm{x}}(t_2 ),...,{\bm{x}}(t_{I_n } )\} \in \mathbb{R}^{D \times I_n }$ and $ {\bm{C}}_n = [{\bm{c}}_1 ,{\bm{c}}_2 ,...,{\bm{c}}_{I_n } ] \in \mathbb{R}^{C \times I_n } $ . So as to obtain the hidden representation of event sequence, we input the ${\bm{X}}^T$ and $({\bm{EC}}_n )^T $ to the model we proposed, whose schematic diagram is shown in Fig.\ref{fig2}. \begin{figure}[!htbp] \centering \includegraphics[scale=1]{2.pdf} \caption{The schematic diagram of Temporal Attention Augmented Transformer Hawkes Process (TAA-THP), in TAA-THP, we modify the traditional attention mechanism and highlight the use of temporal encoding information of event sequence.} \label{fig2} \end{figure} As shown in Fig.\ref{fig2}, in initial, event and temporal encoding are inputted to the model, and the input of each encoding layer is the output of the previous layer plus temporal encoding. Which means in the first layer of TAA-THP, we can calculate . Meanwhile, we modify the multi-head self-attention and add temporal encoding as an additional auxiliary input. The tricks, such as layer normalization, residual connection, and dropout, are also involved in TAA-THP, to utilize the information of temporal encoding iteratively, the traditional dot-product multi-head self-attention in encoding layers are modified by us, the new dot-product multi-head self-attention with temporal augmented attention is written as follows: \begin{equation} \label{eq3} {\bm{A}}_l = Softmax\left[ {mask\left( {\frac{{\left( {{\bm{Q}}_l + {\bm{b}}_{lq} } \right){\bm{K}}_l^T + \left( {{\bm{Q}}_l + {\bm{b}}_{lt} } \right)\left( {{\bm{X}}^T {\bm{W}}_{Tem}^l } \right)^T }} {{\sqrt {D_K } }}} \right)} \right]{\bm{V}}_l \end{equation} In Eq.3, ${\bm{b}}_{lq}$ and ${\bm{b}}_{lq }$ are the bias vectors of query matrix , these biases will help the model to calculate the attention more flexible. The term $\left( {{\mathbf{Q}}_l + {\mathbf{b}}_{lq} } \right){\mathbf{K}}_l^T $ is the modified dot-product attention operation, which just adds a bias term in traditional dot-product attention operation. We focus on another term, i.e., $\left( {{\mathbf{Q}}_l + {\mathbf{b}}_{lt} } \right)\left( {{\mathbf{X}}^T {\mathbf{W}}_{Tem}^l } \right)^T$ , this term re-introduces the temporal information into the dot-product, rather than just add the temporal encoding to $\bm{S}$ . In this term, ${\bm{X}}^T {\bm{W}}_{Tem}^l$ is the linear transformation of temporal encoding ${\bm{X}}^T$ ,${\bm{W}}_{Tem}^l \in \mathbb{R}^{D \times D_K } $ is the linear transformation matrix of the $l$-th head attention, and for the $l$-th query, key and value matrix are obtained from Eq.\ref{eq4}: \begin{equation} \label{eq4} {\bm{Q}}_l = {\bm{SW}}_Q^l ,{\bm{K}}_l = {\bm{SW}}_K^l ,{\bm{V}}_l = {\bm{SW}}_V^l \end{equation} where $\bm{S}$ , as described in following Algorithm 1, is the input of each encoding layer.${\bm{W}}_Q^l ,{\bm{W}}_K^l \in \mathbb{R}^{D \times D_K }$ and ${\bm{W}}_V \in \mathbb{R}^{D \times D_V }$ are a linear transformation of $\bm{S}$ . And in general, for our proposed transformer model TAA-THP, we impose the constraint $D_K = D_V $, which is similar to the usual conventions. Meanwhile, in order to shield the impact of future events on current events (one-way characteristics of time) we utilize the masked self-attention mechanism similar to \cite{18DBLP:journals/corr/BahdanauCB14}, which set the elements above the main diagonal of the matrix to be negative infinity, the function $mask( \cdot )$ is used to ensure that future events in the matrix will not affect the attention weights of current events. By means of Eq.\ref{eq3} and Eq.\ref{eq4}, we can obtain , which is the $l$-th attention matrix. To improve the expressive ability of the model, most of the existing attention mechanism models use multi-head attention. Assuming there are $L$ self-attention heads, then, we can get $L$ outputs ${\bm{A}}_1 ,{\bm{A}}_2 ,...,{\bm{A}}_L $ based on Eq.\ref{eq3} and Eq.\ref{eq4}, the corresponding parameters are $\left\{ {{\bm{W}}_Q^l ,{\bm{W}}_K^l ,{\bm{W}}_{Tem}^l ,{\bm{W}}_V^l } \right\}_{l = 1}^L $ . The formula for combining multi-head attention into one output is described as Eq.\ref{eq5}: \begin{equation} \label{eq5} {\mathbf{A}} = \left[ {{\mathbf{A}}_1 ,{\mathbf{A}}_2 ,...,{\mathbf{A}}_L } \right]{\mathbf{W}}_{multi} \end{equation} where ${\bm{W}}_{multi} \in \mathbb{R}^{LD_V \times D}$ is the aggregation matrix. In the position-wise-feed-forward part of each encoding layer, a convolutional neural network (CNN) module is added between the two fully connected layers, the CNN implement the following calculation: \begin{equation} \label{eq6} {\bm{S}} = {\rm{CNN}}\left( {{\rm{ReLU}}({\bm{AW}}_1^{FC} + {\bm{b}}_1 )} \right){\bm{W}}_2^{FC} + {\bm{b}}_2 \end{equation} The CNN module consists of a one-dimension convolutional layer, a nonlinear activation function (ReLU function) and a one-dimension max-pooling layer. Based on the thumb rule and the cross-validation results, we set the convolution kernel have 1 input channel, 4 output channels, the size of the convolution kernel is 3, the stride is 2, and the padding is 0, and the size and stride of max-pooling layer are 2. Our aim for incorporating the CNN module is to improve the local perception of the model so that the model can better learn the dependencies between events. In summary, the algorithm for calculating the implicit representation of the event sequence through asynchronous event sequence data is shown in Algorithm \ref{alg1}. \begin{algorithm} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \caption{Temporal Attention Augmented Transformer Hawkes Process (TAA-THP)} \label{alg1} \begin{algorithmic}[2] \REQUIRE The number of encoding layers: $n$, event-type encoding $({\bm{EC}}_n )^T$ . Temporal encoding (position encoding) ${\bm{X}}^T$ . \ENSURE Hidden representation (State) $ {\mathbf{H}} \in \mathbb{R}^{D \times I_N } $of event sequence \STATE Initialize state $ {\bm{S}} \leftarrow ({\bm{EC}}_n )^T $ . \STATE \textbf{for} $i$ \textbf{in} $n$ , \STATE ${\bm{S}} \leftarrow {\bm{S}} + {{ }}{\bm{X}}^T $ , \STATE ${\bm{S}} \leftarrow output\;of\;{\rm{the}}\;i{\rm{ - th }}\;{\rm{encoding\;layer}}({\bm{S}},{\bm{X}}^T )$ \STATE \textbf{return} ${\bm{H}} \leftarrow {\bm{S}}$ \end{algorithmic} \end{algorithm} And inspired by \cite{24DBLP:conf/icml/ZuoJLZZ20} and \cite{32wang2019language}, using Algorithm \ref{alg1}, we will get the output $\bm{H}$ , and $\bm{H}$ will be utilized as the input of a postprocessing part, which consists of a fully connected layer, RNN layer, and another fully connected layer. The structure of the postprocessing part is summed up in Eq. \ref{eq7}: \begin{equation} \label{eq7} {\bm{H}} = {\rm{RNN}}\left( {{\rm{ReLU}}({\bm{HW}}_3^{FC} + {\bm{b}}_3 )} \right){\mathbf{W}}_4^{FC} + {\bm{b}}_4 \end{equation} Based on cross-validation and other related researches, we set the network dimension of RNN to zero (which means no postprocessing part) or 64. The types of RNN networks that can be used include but are not limited to LSTM and GRU, after $\bm{H}$ passes through this part, the dimension of $\bm{H}$ remains unchanged. Whether the post-processing part in the proposed TAA-THP can improve the performance of the model depends on the characteristics of the dataset. \subsection{Conditional Intensity Function} The relationship between the probability of occurrence and occurring time of each type of event can be described by its corresponding conditional intensity function, after getting the hidden representation of sequence, we can utilize it to calculate the conditional intensity function $\lambda _c (t\left| {\mathcal{H}_t } \right.)$, where $\mathcal{H}_t = (t_j ,c_j ):t_j < t$, which is the history before time , we adopt the similar approach in [24] to calculate the conditional intensity function, which is shown as Eq.\ref{eq8}: \begin{equation} \label{eq8} \lambda _c (t\left| {\mathcal{H}_t } \right.) = f(b_c + \alpha _c \frac{{t - t_i }} {{t_i }} + {\bm{w}}_c^T {\bm{h}}(t_i )) \end{equation} where $t_i$ is the time-stamp of the last event which its occurrence time is the closest to $t$, and $\bm{h}_t$ is the hidden representation corresponding to this event. The overall background intensity is $b_c + \alpha_c {\bm{h}}(t_i )\frac{{t - t_i }} {{t_i }}$ , here $t \in [t_i ,t_{i + 1} )$ , $b_c$ is the constant background intensity, $\alpha_c$ is the coefficient of time-dependent background intensity. In \cite{24DBLP:conf/icml/ZuoJLZZ20}, the $\alpha_c$ is fixed to -0.1, which indicates that when no event occurs, the conditional intensity function will inevitably decay over time. This assumption does not completely conform to reality and limits the expressive ability of the model. In TAA-THP, to make up for this drawback, we let $\alpha_c = {\bm{w}}_{\alpha_c } {\bm{h}}(t_i )$, i.e., the background intensity change with the past history, which improves the model's ability to fit the conditional intensity function. Compared with the traditional Hawkes process model, the time-dependent background intensity can better fit the basic probability of event occurrence. $f(x) = \frac{1} {\beta }\log (1 + e^{\beta x} ) $ is softplus function, and $\beta$ is the softness parameter of softplus function. Softplus function is an improved version of the ReLU function, compared with ReLU, this nonlinear function is smoother, and the activity of most neurons is guaranteed, which makes the model learning ability stronger. Finally, the overall conditional intensity function is the sum of the conditional intensity functions of all types of events, as shown in Eq.\ref{eq9}: \begin{equation} \label{eq9} \lambda (t\left| {\mathcal{H}_t } \right.){\rm{ = }}\sum\limits_{c = 1}^C {\lambda _c (t\left| {\mathcal{H}_t } \right.)} \end{equation} \section{Prediction Task and Model Training} In general, the objective function of the point process model is constructed from the likelihood function \cite{7daley2007introduction}, more specifically, for a sequence $s_n = \{ t_i ,c_i \} _{i = 1}^{I_n }$ , the log-likelihood function of $s_n$ is shown as Eq.\ref{eq10}: \begin{equation} \label{eq10} L(s_n ) = \sum\limits_{i = 1}^{I_n } {\log } \,\lambda (\left. {t_i } \right|\mathcal{H}_i ) - \int_{t_1 }^{t_{I_n } } {\lambda (\left. t \right|\mathcal{H}_t )} dt \end{equation} and assuming there are $N$ sequences in the dataset, then the model parameters can be solved by the maximum log-likelihood principle: \[ \max \sum\nolimits_{n = 1}^N {L(s_n )} \] However, let $\Lambda = \int_{t_1 }^{t_{I_n } } {\lambda \left( {\left. t \right|\mathcal{H}_t } \right)} dt $ , due to $\lambda (\left. t \right|\mathcal{H}_t )$ is derived from the neural network, the closed-form of is hard to get, and we have two approximate methods to solve it, Monte Carlo sampling method \cite{33robert2013monte} and the numerical analysis method \cite{34stoer2013introduction}. The Monte Carlo sampling method \cite{33robert2013monte}, the approximate value of $\Lambda$ is shown in Eq.\ref{eq11}: \begin{equation} \label{eq11} \hat \Lambda _{MC} = \sum\limits_{i = 2}^L {\left( {t_i - t_{i - 1} } \right)} (\frac{1} {M}\sum\limits_{m = 1}^M {\lambda (u_m )} ) \end{equation} where $u_m$ is sampled from the uniform distribution $U(t_{i - 1} ,t_i )$ . It is worth noting that $\hat \Lambda _{MC} $ calculated by this method is an unbiased estimate of $\Lambda$. And for the numerical analysis method \cite{34stoer2013introduction}, based on the trapezoidal rule, we can get the estimate of $\Lambda$ as shown in Eq.\ref{eq12}: \begin{equation} \label{eq12} \hat \Lambda _{NA} = \sum\limits_{i = 2}^{I_n } {\frac{{t_i - t_{i - 1} }} {2}} (\lambda (\left. {t_i } \right|\mathcal{H}_i ) + \lambda (\left. {t_{i - 1} } \right|\mathcal{H}_{i - 1} )) \end{equation} The computational complexity of the numerical analysis method is significantly less than the Monte Carlo sampling method, but the error is larger. It is a reasonable alternative when the accuracy requirements are not high. Below we give a more scrutinizing discussion. Recall that after obtaining the conditional intensity function of each type of event through Eq.\ref{eq8}, we can predict the occurrence instant of events in the future. Traditionally \cite{7daley2007introduction}, the dominant paradigm to calculate the conditional intensity function can be gotten from Eq.\ref{eq13}: \begin{equation} \label{eq13} \begin{array}{l} p(\left. t \right|{\cal H}_t ) = \lambda (\left. t \right|{\cal H}_t )\exp t( - \int_{t_i }^t {\lambda (\left. s \right|{\cal H}_t )} ds) \\ \hat t_{i + 1} = \int_{t_i }^\infty {t\cdot p(\left. t \right|{\cal H}_t )dt} \\ \hat c_{i + 1} = \mathop {\arg \max }\limits_c \frac{{\lambda _c (\hat t_{i + 1} |{\cal H}_{i + 1} )}}{{\lambda (\hat t_{i + 1} |{\cal H}_{i + 1} )}} \\ \end{array} \end{equation} However, this paradigms are flexible, but highly intractable, which have some limitations, for instance, $\lambda (\left. t \right|{\cal H}_t )$ is derived from the neural network, which is hard to get the closed-form solution of $\int {t\cdot p(\left. t \right|{\cal H}_t )dt} $ , moreover, we need to calculate the improper integral $\int_{t_i }^\infty {t\cdot p(\left. t \right|{\cal H}_t )dt} $ based on Monte Carlo sampling \cite{33robert2013monte}, generally speaking, the upper limit of integration can be replaced by a large enough number when we take advantage of Monte Carlo sampling from the uniform distribution to approximately calculate the integral, but this still has a larger error compared with the upper limit of integration being infinite, Monte Carlo sampling under the exponential distribution can take the upper limit of integration to infinity, while high computational complexity limits the utility of this approach. Therefore, we desire to use the powerful fitting ability of the neural network and the extracted hidden representation from the sequence of events, to predict the type and time of events that may occur in the future. The prediction formula is presented as Eq.\ref{eq14}: \begin{equation} \label{eq14} \begin{array}{l} \hat t_{i + 1} = {\bm{W}}_{time} {\bf{h}}(t_i ) \\ \widehat{\bf{p}}_{i + 1} = Softmax({\bm{W}}_{type} {\bf{h}}(t_i )) \\ \hat c_{i + 1} = \mathop {\arg \max }\limits_c {\bf{\hat p}}_{i + 1} (c) \\ \end{array} \end{equation} In addition, the prediction parameter, ${\bm{W}}_{time}$ and ${\bm{W}}_{type}$ , should also be optimized, we define the prediction loss of occurring time of each type of event and type of events as Eq.\ref{eq15} and Eq.\ref{eq16}: \begin{equation} \label{eq15} L_{time} (s_n ) = \sum\nolimits_{i = 2}^{I_n } {(t_i - \hat t_i )^2 } \end{equation} \begin{equation} \label{eq16} L_{type} (s_n ) = \sum\nolimits_{i = 2}^{I_n } { - {\bf{c}}} _i^T \log (\widehat{\bf{p}}_i ) \end{equation} Thus, the overall objective function of TAA-THP is shown as Eq.\ref{eq17}: \begin{equation} \label{eq17} \min \sum\limits_{n = 1}^N { - L(s_n )} + \alpha _{type} L_{type} (s_n ) + \alpha _{time} L_{time} (s_n ) \end{equation} where $\alpha _{type} $ and $\alpha _{time}$ are hyperparameters, which will help keep the stability of model training, the objective function in Eq. 17, can be optimized by stochastic gradient descent algorithm including but not limited to momentum method and ADAM (Adaptive moment estimation)\cite{35kingma2014adam}, we use ADAM optimizer with default hyperparameter i.e., we set learning rate=0.0001, betas are 0.9 and 0.999, eps =$10^8$, weight\_decay = 0. \section{Experiments} In this section, we are going to compare the model performance of TAA-THP and numerous baselines on a wide range of synthetic and real-life datasets, and figure out the effect of the introduction of temporal augmented attention. Firstly, we introduce the details of datasets and baselines, then, we compare the model performance on the foundation of experimental results, at last, we explore the effect of the presence or absence of temporal augmented attention on the performance of the model in the ablation study. \subsection{Datasets} In this subsection, we make use of two artificial datasets, and four real-world datasets of event sequence to conduct the experiments, Table 2 introduces the characteristics of each dataset: \begin{table}[!htbp] \centering \label{tb2} \caption{Characteristics of datasets used in experiments.} \begin{tabular}{cccccc} \hline \multirow{2}{*}{Dataset} & \multirow{2}{*}{C} & \multicolumn{3}{c}{Sequence Length} & \multirow{2}{*}{Events} \\ \cline{3-5} & & Min & Aver. & Max & \\ \hline Synthetic & 5 & 20 & 60 & 100 & 602,697 \\ NeuralHawkes & 5 & 20 & 60 & 100 & 602,984 \\ Retweets & 3 & 50 & 109 & 264 & 2,173,533 \\ MIMIC-II & 75 & 2 & 4 & 33 & 2,419 \\ StackOverflow & 22 & 41 & 72 & 736 & 480,413 \\ Financial & 2 & 829 & 2074 & 3319 & 414,800 \\ \hline \end{tabular} \end{table} \textbf{Synthetic and NeuralHawkes} \cite{14mei2017neural}: Mei generates two sets of artificial sequences based on the thinning algorithm, including Hawkes process model and continues-time LSTM neural Hawkes process model, the parameters are randomly sampled. \textbf{Retweets} \cite{6zhao2015seismic}:This dataset contains a large number of sequences of tweets, every sequence includes an original tweet (the original content is some user post) and its following retweets. The time and label of the user of each retweet are recorded in the sequence, and labels are divided into three classes based on the number of their followers: “small”, “medium”, and “large”. \textbf{StackOverflow} \cite{36leskovec2014snap}: StackOverflow is one of the most famous programming Q\&A websites. The website rewards users with various badges to encourage them to take part in community activities. It is worth noting that the same badge can be donated to the same user, and this dataset includes lots of users’ reward histories in the range of two years, each user’s history is treated as a sequence, and each event in sequences represents the acquisition of badge. \textbf{Electrical Medical Records} \cite{2johnson2016mimic}: MIMIC-II dataset includes patients’ records of visitation to a hospital’s ICU during seven years. Each patient’s record is treated as an independent sequence, and each event contains the corresponding time-stamp and diagnosis of the patient. \textbf{Financial Transactions} \cite{12zhou2013learning}: The financial dataset involves a lot of short-term transaction history of a stock in one day. The operation of each transaction is recorded as the event, and this dataset only has two kinds of events: “buy” and “sell”, and the unit of the time-stamp in milliseconds. Based on the cross-validation results on validation dataset, we obtain the hyper-parameters of our model on different datasets, which are shown as Table 3. \begin{table}[!htbp] \centering \label{tb3} \caption{The hyper-parameters of Temporal Attention Augmented Transformer Hawkes Process} \begin{tabular}{ccccccccc} \hline Dataset & Batch Size & $D$ & $D_H$ & $D_K=D_V$ & Heads of attention & Layers of model & $D_{\rm{RNN}}$ & Dropout \\ \hline Synthetic & 16 & 64 & 256 & 64 & 3 & 3 & 64 & 0.1 \\ NeuralHawkes & 16 & 64 & 256 & 64 & 3 & 3 & 64 & 0.1 \\ Retweets & 16 & 64 & 256 & 64 & 3 & 3 & 64 & 0.1 \\ MIMIC-II & 1 & 128 & 256 & 256 & 5 & 5 & 0 & 0.1 \\ StackOverflow & 4 & 128 & 512 & 256 & 4 & 4 & 64 & 0.1 \\ Financial & 1 & 128 & 512 & 512 & 4 & 4 & 64 & 0.1 \\ \hline \end{tabular} \end{table} \subsection{Baselines} \textbf{RMTPP} \cite{12zhou2013learning}: Du et al. come up with a recurrent network point process model, which effectively models the event types and time-stamp in the sequence by embedding history to the vector. \textbf{NHP} \cite{14mei2017neural}: Mei and Eisner firstly present a novel neural Hawkes process, which based on the continuous-time LSTM, the continuous-time LSTM has decay property of impact of historical events. \textbf{SAHP} \cite{23zhang2020self}: Zhang et al. firstly come up with the sequence encoding through the self-attention mechanism, which utilizes the position encoding method to encode the time-stamp, and after the implicit representation of the sequence is obtained, the implicit representation of the sequence is used to calculate the model parameters of the Hawkes process. \textbf{THP} \cite{24DBLP:conf/icml/ZuoJLZZ20}: Base on the performance improvement of the transformer, Zuo et al. propose the transformer Hawkes process, which achieves state-of-the-art performance. We can obtain the following experimental results to verify the performance of THP based on the model and the hyper-parameter they provide. \subsection{Experimental results and comparison} In this subsection, in order to validate the performance of TAA-THP, we compare the TAA-THP and baselines’ performance. First of all, we compare the loglikelihood value of TAA-THP and baselines on the test dataset, and for simplicity, we named it Loglike. The Loglike is the most basic model measurement for the point process model, which indicates how well the model fits in the data. In our experimental process, we set $\alpha_time $ and $\alpha_type $ in TAA-THP to zero. The loglike of baselines and TAA-THP on different test datasets are shown in Table 4. \begin{table}[!htbp] \centering \caption{The value of log-likelihood function of different models on the test datasets.} \begin{tabular}{cccccc} \hline Datasets & RMTPP & NHP & SAHP & THP & TAA-THP \\ \hline Synthetic & \textbackslash{} & -1.33 & 0.520 & 0.834 & \textbf{1.66} \\ NeuralHawkes & \textbackslash{} & -1.02 & 0.241 & 0.966 & \textbf{1.77 } \\ Retweets & -5.99 & -5.06 & -5.85 & -4.69 & \textbf{-1.04} \\ StackOverflow & -2.60 & -2.55 & -1.86 & -0.559 & \textbf{-0.545} \\ MIMIC-II & -1.35 & -1.38 & -0.520 & -0.143 & \textbf{-0.111} \\ Financial & -3.89 & -3.60 & \textbackslash{} & -1.388 & \textbf{-1.18} \\ \hline \end{tabular} \end{table} As we can find out in Table 4, TAA-THP outperforms existing baselines in terms of the value of the log-likelihood function on all test datasets. This phenomenon proves that TAA-THP can more effectively model the event sequences than existing baselines. However, the acquisition of Loglike can’t provide effective help for the practical application of the model, because loglike is only an abstract measurement, it does not have practical meaning. Thus, we tend to compare the prediction accuracies in terms of the occurring time of each type of event and type of events for existing baselines and our proposed TAA-THP model, which have very important practical application significance. For instance, in terms of the electronic medical records, based on the patient's medical history, we can predict the type of illness and the occurring time of the next attack, and provide more effective and timely help for the patient's treatment. We can also predict the next possible failure time and type for a large-scale system based on the failure sequence, and perform maintenance and prevention in advance to improve safety and economic benefits in production. It is worth noting that, for any sequence of events $s_n$ , assuming the length is $I_n$ , we don’t predict the possible type and time of the first event, in other words, for the sequence $s_n$ , we make n-1 predictions, and we set $\alpha_time=0.01 $ and $\alpha_type=1 $ . The prediction accuracies of event types are shown in Table 5 and Fig. 3. \begin{table}[] \centering \caption{Predict accuracies for different models on various datasets.} \begin{tabular}{ccccc} \hline Dataset & RMTPP & NHP & THP & TAA-THP \\ \hline StackOverflow & 45.9 & 46.3 & 46.79 & 46.83 \\ MIMIC-II & 81.2 & 83.2 & 83.2 & 84.4 \\ Financial & 61.95 & 62.20 & 62.23 & 62.43 \\ \hline \end{tabular} \end{table} \begin{figure}[!htbp] \label{fig3} \centering \subfigure[]{ \includegraphics[width=4.5cm]{soacc.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{mimicacc.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{finacc.pdf} } \caption{Predictive accuracies for existing baselines and TAA-THP. Based on the five times train-dev-test partition, five experiments are performed on each dataset, and then the mean and standard deviation of different models are obtained.} \end{figure} From Fig. 3 and Table 5, on these real-world datasets, we can see that the accuracies of event prediction of our TAA-THP model have been improved compared with the existing baselines. In our point of view, we think these results are caused by the introduction of temporal attention, which decouples the simple stacking of event encoding and temporal position encoding in the traditional dot product attention mechanism. And we will verify this hypothesis on the ablation study in subsection 5.4. However, we can see that the improvement of prediction accuracies is relatively small, however, The experimental results of Loglike have confirmed that TAA-THP can better model the sequence data, and then we will test the prediction ability of occurrences of the events for different models. As for the prediction error of the occurring time of each type of event, we use RMSE (Root Mean Squared Error) as uniform metric evaluation criteria, RMSE of the existing baselines and TAA-THP are shown in Table 6 and Fig. 4. \begin{table}[!htbp] \centering \caption{RMSE of different models on various datasets} \begin{tabular}{ccccc} \hline Dataset & RMTPP & NHP & THP & TAA-THP \\ \hline StackOverflow & 9.78 & 9.83 & 4.99 & 3.91 \\ MIMIC-II & 6.12 & 6.13 & 0.859 & 0.868 \\ Financial & 1.56 & 1.56 & 0.02575 & 0.02570 \\ \hline \end{tabular} \end{table} \begin{figure}[!htbp] \label{fig3} \centering \subfigure[]{ \includegraphics[width=4.5cm]{rmseso.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{mcrmse.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{fcrmse.pdf} } \subfigure[]{ \includegraphics[width=4.5cm]{rmsezoom.pdf} } \caption{RMSE for existing baselines and TAA-THP. Based on the five times train-dev-test partition, five experiments are performed on each dataset, and then the mean and standard deviation of different models are obtained.} \end{figure} From Fig. 4 and Table 6, we can find out that the RMSE of TAA-THP is generally smaller than the ones of the existing baselines. The experimental results for Loglike, accuracy, and RMSE has the obvious improvement than the existing baselines on the different scenes, for example, for the MIMIC-II dataset the number of the event types is 75, and the average length of sequences is only 4, for the Retweets dataset the number of the event types is 3, and the average length of sequences is 264, while for StackOverflow dataset the number of the event types is 22, and the average length of sequences is 736, both of them are relatively big, and for Financial dataset, the number of event types is only 2, and the average length of sequences is 2074. The characteristics of these datasets are obvious differences, our model shows a certain degree of robustness, and we can conclude that the TAA-THP can effectively capture the short-term and long-term dependencies between events. \subsection{Ablation study} So as to figure out the specific influence of the introduction of temporal augmented attention, we conduct the ablation study on StackOverflow, MIMIC-II, and Financial datasets. If we remove the temporal augmented attention in TAA-THP network architecture, the only difference between it and traditional dot-product attention is the bias ${\bm{b}}_{lq} $ . Therefore, here, we temporarily name this attention structure as biased attention, and the dot-product operation is shown as Eq.\ref{eq18}: \begin{equation} \label{eq18} {\bf{A}}_l = Softmax\left[ {mask\left( {\frac{{\left( {{\bf{Q}}_l + {\bf{b}}_{lq} } \right){\bf{K}}_l^T }}{{\sqrt {D_K } }}} \right)} \right]{\bf{V}}_l \end{equation} Compare with Eq.3, the term $\left( {{\bf{Q}}_l + {\bf{b}}_{lt} } \right)\left( {{\bf{X}}^T {\bf{W}}_{Tem}^l } \right)^T $ is removed, which is the temporal attention, we compare the three evaluation criteria, e.g., Accuracy, RMSE, and Loglike on three datasets, the results are shown in Table 7. And to more intuitively compare the impact of temporal attention, we visualize the performance of models in Fig. 5, Fig. 6 and Fig. 7. \begin{table}[!htbp] \centering \caption{The ablation experimental results of temporal attention.} \begin{tabular}{cccc} \hline Dataset & Evaluation criteria & Biased attention & TAA-THP \\ \hline \multirow{3}{*}{StackOverflow} & Accuracy & 46.80 & 46.83 \\ & RMSE & 4.04 & 3.91 \\ & Loglike & -0.547 & -0.545 \\ \hline \multirow{3}{*}{MIMIC-II} & Accuracy & 84.00 & 84.41 \\ & RMSE & 0.872 & 0.868 \\ & Loglike & -0.129 & -0.111 \\ \hline \multirow{3}{*}{Financial} & Accuracy & 62.38 & 62.44 \\ & RMSE & 0.02573 & 0.02570 \\ & Loglike & -1.03 & -1.08 \\ \hline \end{tabular} \end{table} \begin{figure}[!htbp] \centering \subfigure[]{ \includegraphics[width=4.5cm]{soabrmse.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{mcabrmse.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{fiabrmse.pdf} } \caption{in terms of Loglike, visualization of ablation experimental results with and without temporal attention.} \end{figure} \begin{figure}[!htbp] \centering \subfigure[]{ \includegraphics[width=4.5cm]{soabacc.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{mcabacc.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{fiabacc.pdf} } \caption{in terms of RMSE criteria, visualization of ablation experimental results with and without temporal attention. } \end{figure} \begin{figure}[!htbp] \centering \subfigure[]{ \includegraphics[width=4.5cm]{sologab.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{milogab.pdf} } \quad \subfigure[]{ \includegraphics[width=4.5cm]{filogab.pdf} } \caption{in terms of prediction accuracies, visualization of ablation experimental results with and without temporal attention} \end{figure} From Fig. 5 and Table 7, we can see that with removing of temporal attention, the Loglikes on the datasets become smaller overall, which verifies the effectiveness of introducing temporal attention mechanism. Meanwhile, we can find out that the Loglike and accuracies of Biased attention are still higher than the existing baselines, we guess that this is the effect of bias ${\bm{b}}_{lq}$, which can keep most of the neurons in the model activated. Fig. 6, Fig. 7, and Table 7 show the prediction performance of models, we find that the lack of temporal attention reduces the prediction performance of event occurring time and type of event. This result confirms the merit of introducing temporal attention. Moreover, after removing temporal attention from the TAA-THP model, the prediction accuracies of the event will decrease, which can test and verify the hypothesis we put forward in subsection 5.3, the additional temporal attention indeed helps to decouple the simple concatenating of event encoding and time position encoding. In our standpoint, when we introduce temporal attention, it passes through a linear transformation ${\bm{X}}^T {\bm{W}}_{Tem}^l $ which is depicted in Eq.\ref{eq3}, which is similar to the training mechanism of the residual network. During the model training, the model can spontaneously decide whether the temporal information will feed into the multi-head attention, how much information is actually sent over the multi-head attention, it depends on the value of elements of $ {\bm{W}}_{Tem}^l $ , through the experimental results, we see that the model with temporal attention performs better, which confirms that temporal attention does exist in the model in its own right, and it plays an effective and positive role. \section{Conclusions and future works} In this paper, we come up with a new structure of the transformer Hawkes process. We improve the traditional dot-product attention mechanism. We propose to introduce temporal attention to the encoder of the transformer. The experimental results confirm that the additional introduction of temporal attention significantly improves the performance, especially in the predicting error for the occurring time and type of next event, and the overall likelihood function value on the sequence of events. In addition, through additional ablation study, we verify that the introduction of temporal attention is indeed effective. And in the future, we hope to propose a more valuable model based on the transformer and incorporate another generative neural network model to acquire better performance.
{'timestamp': '2021-12-30T02:24:03', 'yymm': '2112', 'arxiv_id': '2112.14472', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14472'}
arxiv
\section{Introduction}\label{sec:intro} DNA-sequencing aims to measure the genetic makeup of individuals. Without going into details about the many different technologies, these processes determine (fragments of) the genetic sequence. Commonly, the primary data analysis consists, among other steps, of: 1) alignment against a reference genome, e.g., GRCh38 for human samples, and 2) variant calling. The primary result is a list of variants, i.e., a set of differences that is specific for the measured individual (sample), often reported in a tabular file like the Variant Call Format~(VCF)~\cite{vcf}. These variants are used in subsequent applications ranging from fundamental and association research studies to clinical diagnostics. It is advantageous to look only at differences (with regard to some reference) as the genome is usually large~(ca.~$3 \cdot 10^9$ nucleotides for humans), but the individual differences (between two genomes) are relatively small~(ca.~$0.6\%$~\cite{variation}). When variants are associated with phenotypic traits they are reported in literature and stored (with their annotation) in (locus specific) databases. Usually, the representation of the variant in VCF is refined to a representation more suitable for reporting. For this, many (domain specific) languages exist. Most notable are: the recommendations of the Human Genome Variation Society~(HGVS)~\cite{hgvs}, SPDI~\cite{spdi}; the internal data model for variants used by the National Center for Biotechnology Information (NCBI) and the Variant Representation Specification~(VRS)~\cite{vrs}; developed by the Global Alliance for Genomic Health (GA4GH). These languages attempt to represent the observed differences in a human-understandable and/or machine interpretable manner and whereas VCF is implicitly tied to a specific process, these representations are process agnostic and universally interpretable. Within the domain of variant recording, some simplifications are common. First, small (local) variants originating from the same allele are recorded separately because this is convenient when storing large numbers of variants in databases. Phasing information, i.e., how small variants relate to each other when properly distributed over alleles, is often lost or incomplete. This is, partially, a direct consequence of the sequencing technology and partially because this information is removed. Second, in some representations (notably, HGVS) uncertainties might be expressed. Usually, the uncertainties relate to the positioning of the variant within the reference genome, but also the exact makeup of larger insertions might by unknown. Finally, unchanged regions may be implicit. During the primary data analysis, in particular the alignment step, the sequence from the reference genome is assumed to be present even when direct evidence, e.g., coverage information from the sequencing process, is lacking. For the remainder of this paper, we adopt a strict view on the nature of variants: 1) We see a combination of (many) smaller variants originating from the same allele as just another variant. This closely follows the interpretation of allele descriptions in HGVS. Considering small variants in isolation is possible by trivially constructing an artificial allele containing only the variant(s) of interest. 2) We consider only \emph{interpretable} variants, i.e., given a \emph{reference sequence} there is a deterministic and unambiguous way of ``applying'' the variants such that the result is the (originally) measured \emph{observed sequence} cf. the Unix~\texttt{diff} and \texttt{patch} utilities. As is already observed within the various variant representation languages, it is often possible to have multiple representations describing the same observed sequence. These possibilities can originate from the choice of ``operator'', e.g., a single nucleotide variant (SNV) can also be represented by a deletion (of one nucleotide) followed by an insertion (of again one nucleotide). Another source contributing to the number of possibilities is the structure of the reference sequence. Consider the reference sequence~\texttt{ATTTA} and the observed sequence~\texttt{ATTA}. One of the symbols~\texttt{T} is removed; to say which one specifically yields a number ($3$) of possibilities. To determine a universally accepted representation of a variant, most variant representation languages employ a \emph{normalization} procedure. Normalization chooses a \emph{canonical} representation from the set of possibilities. Unfortunately, this procedure is not standardized over the various languages, e.g., the $3'$-rule in HGVS vs. the $5'$-rule in VCF. Within a certain language, however, proper normalization solves the problem of identifying \emph{equivalent} variant representations. The implications of using non-normalized variants representations have been reviewed in~\cite{variant_name, variant_calling, curation, litvar}. Solutions to this problem are presented in~\cite{unified, improved_vcf, vmc_spec, smash, plyranges, gql, ask2me}. Often dedicated tooling~\cite{varsome, validator, mutalyzer, vde} is needed to rigorously apply the proposed normalization procedure. Normalized variant representations can be textually compared using standard string matching. \begin{figure}[ht!] \begin{center} \begin{tikzpicture}[yscale=-.8, minimum size=4.5mm] \node[rectangle, fill=black!15, thick] (al0_ref0) at (0.0, 0) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al0_ref1) at (0.5, 0) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al0_ref2) at (1.0, 0) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al0_ref3) at (1.5, 0) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al0_ref4) at (2.0, 0) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al0_ref5) at (2.5, 0) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al0_ref6) at (3.0, 0) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al0_ref7) at (3.5, 0) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al0_obs0) at (0.0, 1) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al0_obs1) at (0.5, 1) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al0_obs2) at (1.0, 1) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al0_obs3) at (1.5, 1) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al0_obs4) at (2.0, 1) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al0_obs5) at (2.5, 1) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al0_obs6) at (3.0, 1) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al0_obs7) at (3.5, 1) {\texttt{G}}; \draw[semithick] (al0_ref0) -- (al0_obs0); \draw[semithick] (al0_ref2) -- (al0_obs2); \draw[semithick] (al0_ref3) -- (al0_obs3); \draw[semithick] (al0_ref4) -- (al0_obs4); \draw[semithick] (al0_ref7) -- (al0_obs7); \path (al0_ref0.west) -- (al0_ref7.east) node[midway, above=1.5em] {$\texttt{[2delA;5\_6insCT]}$}; \node[rectangle, fill=black!15, thick] (al1_ref0) at (0.0, 2.5) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al1_ref1) at (0.5, 2.5) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al1_ref2) at (1.0, 2.5) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al1_ref3) at (1.5, 2.5) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al1_ref4) at (2.0, 2.5) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al1_ref5) at (2.5, 2.5) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al1_ref6) at (3.0, 2.5) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al1_ref7) at (3.5, 2.5) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al1_obs0) at (0.0, 3.5) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al1_obs1) at (0.5, 3.5) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al1_obs2) at (1.0, 3.5) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al1_obs3) at (1.5, 3.5) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al1_obs4) at (2.0, 3.5) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al1_obs5) at (2.5, 3.5) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al1_obs6) at (3.0, 3.5) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al1_obs7) at (3.5, 3.5) {\texttt{G}}; \draw[semithick] (al1_ref0) -- (al1_obs0); \draw[semithick] (al1_ref2) -- (al1_obs2); \draw[semithick] (al1_ref3) -- (al1_obs3); \draw[semithick] (al1_ref5) -- (al1_obs5); \draw[semithick] (al1_ref7) -- (al1_obs7); \node[rectangle, fill=black!15, thick] (al4_ref0) at (6.0, 0) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al4_ref1) at (6.5, 0) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al4_ref2) at (7.0, 0) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al4_ref3) at (7.5, 0) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al4_ref4) at (8.0, 0) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al4_ref5) at (8.5, 0) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al4_ref6) at (9.0, 0) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al4_obs0) at (6.0, 1) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al4_obs1) at (6.5, 1) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al4_obs2) at (7.0, 1) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al4_obs3) at (7.5, 1) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al4_obs4) at (8.0, 1) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al4_obs5) at (8.5, 1) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al4_obs6) at (9.0, 1) {\texttt{G}}; \draw[semithick] (al4_ref0) -- (al4_obs0); \draw[semithick] (al4_ref1) -- (al4_obs1); \draw[semithick] (al4_ref3) -- (al4_obs3); \draw[semithick] (al4_ref4) -- (al4_obs4); \draw[semithick] (al4_ref6) -- (al4_obs6); \path (al4_ref0.west) -- (al4_ref6.east) node[midway, above=1.5em] {$\texttt{[3delA;5\_6insT]}$}; \node[rectangle, fill=black!15, thick] (al5_ref0) at (6.0, 2.5) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al5_ref1) at (6.5, 2.5) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al5_ref2) at (7.0, 2.5) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al5_ref3) at (7.5, 2.5) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al5_ref4) at (8.0, 2.5) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al5_ref5) at (8.5, 2.5) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al5_ref6) at (9.0, 2.5) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al5_obs0) at (6.0, 3.5) {\texttt{G}}; \node[rectangle, fill=black!15, thick] (al5_obs1) at (6.5, 3.5) {\texttt{-}}; \node[rectangle, fill=black!15, thick] (al5_obs2) at (7.0, 3.5) {\texttt{A}}; \node[rectangle, fill=black!15, thick] (al5_obs3) at (7.5, 3.5) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al5_obs4) at (8.0, 3.5) {\texttt{C}}; \node[rectangle, fill=black!15, thick] (al5_obs5) at (8.5, 3.5) {\texttt{T}}; \node[rectangle, fill=black!15, thick] (al5_obs6) at (9.0, 3.5) {\texttt{G}}; \draw[semithick] (al5_ref0) -- (al5_obs0); \draw[semithick] (al5_ref2) -- (al5_obs2); \draw[semithick] (al5_ref3) -- (al5_obs3); \draw[semithick] (al5_ref4) -- (al5_obs4); \draw[semithick] (al5_ref6) -- (al5_obs6); \node[draw, fit=(al0_ref0) (al4_obs6)] {}; \node[draw, fit=(al1_ref0) (al5_obs6)] {}; \begin{scope}[on background layer] \fill[orange!30] ([xshift=.4pt, yshift=.5pt]al0_ref1.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al0_obs1.south east); \path (al0_ref1) -- (al0_obs1) node[midway] {\footnotesize $\dagger$}; \fill[orange!30] ([xshift=.4pt, yshift=.5pt]al0_ref5.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al0_obs5.south east); \path (al0_ref5) -- (al0_obs5) node[midway] {\footnotesize $\dagger$}; \fill[blue!30]([xshift=.4pt, yshift=.5pt]al0_ref6.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al0_obs6.south east); \path (al0_ref6) -- (al0_obs6) node[midway] {\footnotesize $\star$}; \fill[blue!30] ([xshift=.4pt, yshift=.5pt]al1_ref1.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al1_obs1.south east); \path (al1_ref1) -- (al1_obs1) node[midway] {\footnotesize $\star$}; \fill[orange!30] ([xshift=.4pt, yshift=.5pt]al1_ref4.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al1_obs4.south east); \path (al1_ref4) -- (al1_obs4) node[midway] {\footnotesize $\dagger$}; \fill[blue!30]([xshift=.4pt, yshift=.5pt]al1_ref6.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al1_obs6.south east); \path (al1_ref6) -- (al1_obs6) node[midway] {\footnotesize $\star$}; \fill[orange!30] ([xshift=.4pt, yshift=.5pt]al4_ref2.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al4_obs2.south east); \path (al4_ref2) -- (al4_obs2) node[midway] {\footnotesize $\dagger$}; \fill[blue!30] ([xshift=.4pt, yshift=.5pt]al4_ref5.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al4_obs5.south east); \path (al4_ref5) -- (al4_obs5) node[midway] {\footnotesize $\star$}; \fill[blue!30] ([xshift=.4pt, yshift=.5pt]al5_ref1.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al5_obs1.south east); \path (al5_ref1) -- (al5_obs1) node[midway] {\footnotesize $\star$}; \fill[blue!30] ([xshift=.4pt, yshift=.5pt]al5_ref5.north west) rectangle ([xshift=-.4pt, yshift=-.5pt]al5_obs5.south east); \path (al5_ref5) -- (al5_obs5) node[midway] {\footnotesize $\star$}; \end{scope} \end{tikzpicture} \caption{Two pairs (top and bottom) of minimal sequence level alignments for two variants (left and right) with respect to the same reference sequence~\texttt{GAATCG}. In the top pair the highlighted \emph{changes} show one matching ($\star$) change between the variants, but also non-matching ($\dagger$) changes. If we would only consider this pair, the conclusion would be that the variants overlap. However, taking \emph{all} minimal alignments into account, we will eventually encounter the bottom pair. Here, the right variant has no non-matching changes, while the left variant has one non-matching change. This leads to the conclusion that the left variant contains the right variant. Note that there are more minimal alignments for the left variant that are not shown for brevity, but they do not influence the conclusion.}\label{fig:example} \end{center} \end{figure} \noindent Arguably, identification of equivalent variant representations, i.e., determining whether two variant descriptions result in the same observed sequence, is currently the most interesting query in the variant domain, as it allows for the grouping and matching of equivalent variants and their annotations. With the advent of long read single molecule sequencing technologies (provided by platforms such as PacBio and Oxford Nanopore), which are capable of providing direct evidence of numerous small variants that originate from the same allele, a richer set of questions arises. In this paper we explore the relations of variants in an exhaustive manner. In addition to the equivalence relation, we partition the domain of binary variant relations into five Boolean relations: equivalence; containment, i.e., either a variant is fully contained in another or a variant fully contains another; overlap, i.e., two variants have (at least) one common element; and disjoint, i.e., no common elements. Because of this partitioning, exactly one of the five aforementioned relations is true for every pair of variants. For determining the relation, we consider all (minimal) variant representations simultaneously. An introductory example is given in Figure~\ref{fig:example}. \section{Formalization}\label{sec:formal} Formally, a variant representation is a pair $(R, \varphi)$, where $R$ is a \emph{string}; a finite sequence of \emph{symbols} from a non-empty finite \emph{alphabet}, e.g., $\Sigma = \{\texttt{A}, \texttt{C}, \texttt{G}, \texttt{T}\}$ called the reference sequence, and $\varphi$ is a finite set of \emph{operations} transforming the string~$R$ into the string~$O$, the observed sequence. The \emph{length} of a string~$S$, denoted by $|S|$, is the number of symbols in $S$. We refer to the symbol on position~$i$ of string~$S$ as $S_i$ with $1 \le i \le |S|$. This notation is extended in the natural way for substrings of $S$, i.e., $S_{i\ldots j}$ represents the string containing the contiguous symbols~$S_i,\ldots, S_j$, with $1 \le i < j \le |S|$. Note that the set of operations is dependent on the variant representation language used. Without loss of generality, we assume that all operations are in the form of a deletion of zero or more symbols followed by an insertion of zero or more symbols. The actual problem of transforming a reference sequence into an observed sequence is, for instance, handled in~\cite{mutalyzer}. The difference between the reference sequence~($R$) and the observed sequence~($O$) is the ``actual'' variant, which is, to some extend, independent from the original representation ($\varphi$) as we take \emph{all} minimal representations into account. To this end we perform a global pairwise alignment between $R$ and $O$. In contrast to the specialized alignment methods used in, for instance, short read sequencing, we use an elementary form of alignment which is close to a commonly used distance metric, the \emph{Levenshtein distance}~\cite{levenshtein}. The \emph{simple edit distance}, i.e., the Levenshtein distance without substitutions and weighing both deletions and insertions as $1$, from string~$R$ to string~$O$ is given by $d(R, O) = D(|R|, |O|)$ defined by the recurrence relation with $1 \le i \le |R|$ and $1 \le j \le |O|$: \begin{equation}\label{eq:edit} \begin{aligned} D(0, 0) &= 0, \\ D(i, 0) &= i, \\ D(0, j) &= j, \\ D(i, j) &= \begin{cases} D(i - 1, j - 1) & \text{if } R_i = O_j, \\ \min \begin{cases} D(i - 1, j) + 1, \\ D(i, j - 1) + 1 \\ \end{cases} & \text{otherwise}. \end{cases} \end{aligned} \end{equation} \bigskip \noindent The simple edit distance is related to the \emph{Longest Common Subsequence}~(LCS) problem~\cite{survey}: \begin{equation}\label{eq:lcs} D(i, j) = i + j - 2\cdot|\text{LCS}(R_{1\ldots i}, O_{1\ldots j})|. \end{equation} \noindent Commonly, the recurrence relation is computed using a dynamic programming approach by filling a matrix containing the solutions to Equation~\ref{eq:edit} in a bottom-up fashion~\cite{string_to_string}. Consider the computation of the simple edit distance between $R = \texttt{CATATATCG}$ and $O = \texttt{CTTATAGCAT}$ in Figure~\ref{fig:edit}. \begin{figure}[ht!] \[ \begin{array}{rc|ccccccccccc} \renewcommand*{\arraystretch}{1.2} & & \phantom{\circled{0}} & \phantom{\circled{1}} & \phantom{\circled{2}} & \phantom{\circled{3}} & \phantom{\circled{4}} & \phantom{\circled{5}} & \phantom{\circled{6}} & \phantom{\circled{7}} & \phantom{\circled{8}} & \phantom{\circled{9}} & \phantom{\circled{10}} \\ & & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ & & \texttt{.} & \texttt{C} & \texttt{T} & \texttt{T} & \texttt{A} & \texttt{T} & \texttt{A} & \texttt{G} & \texttt{C} & \texttt{A} & \texttt{T} \\ \hline 0 & \texttt{.} & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ 1 & \texttt{C} & 1 & \circled{0} & 1 & 2 & 3 & 4 & 5 & 6 & \circled{7} & 8 & 9 \\ 2 & \texttt{A} & 2 & 1 & 2 & 3 & \circled{2} & 3 & \circled{4} & 5 & 6 & \circled{7} & 8 \\ 3 & \texttt{T} & 3 & 2 & \circled{1} & \circled{2} & 3 & \circled{2} & 3 & 4 & 5 & 6 & \circled{7} \\ 4 & \texttt{A} & 4 & 3 & 2 & 3 & \circled{2} & 3 & \circled{2} & 3 & 4 & \circled{5} & 6 \\ 5 & \texttt{T} & 5 & 4 & \circled{3} & \circled{2} & 3 & \circled{2} & 3 & 4 & 5 & 6 & \circled{5} \\ 6 & \texttt{A} & 6 & 5 & 4 & 3 & \circled{2} & 3 & \circled{2} & 3 & 4 & \circled{5} & 6 \\ 7 & \texttt{T} & 7 & 6 & \circled{5} & \circled{4} & 3 & \circled{2} & 3 & 4 & 5 & 6 & \circled{5} \\ 8 & \texttt{C} & 8 & \circled{7} & 6 & 5 & 4 & 3 & 4 & 5 & \circled{4} & 5 & 6 \\ 9 & \texttt{G} & 9 & 8 & 7 & 6 & 5 & 4 & 5 & \circled{4} & 5 & 6 & 7 \\ \end{array} \] \caption{Computation of the simple edit distance between $R = \texttt{CATATATCG}$ and $O = \texttt{CTTATAGCAT}$. Matching symbols are annotated with a circle. The distance~(7) is given by the bottom-right element.}\label{fig:edit} \end{figure} The simple edit distance $D(|R|, |O|) = 7$ is given by the bottom-right element. Matching symbols are annotated with a circle. From this matrix a \emph{minimal representation} can be computed by tracing back from the bottom-right element to the top-left element while doing only orthogonal (left and up) steps for non-matching elements if the next element has a lower value than the current one. Vertical steps correspond to deletions, which are fully characterized by their position~$1 \le i \le |R|$. We annotate deletions with \texttt{del} and the deleted symbol from $R$ for convenience. Horizontal steps correspond to insertions, which occur between two consecutive positions~$i$ and $i + 1$, with $0 \le i \le |R|$ and listing the inserted symbol (taken from $O$). Insertions are annotated with \texttt{ins}. Special care is needed for consecutive insertions, i.e., multiple insertions between $i$ and $i + 1$. These insertions are \emph{ordered} and are often abbreviated as a single insertion inserting multiple symbols. For matching elements (circled) a diagonal step (up and left) is allowed, keeping the current value. The computation complexity of the simple edit distance is $\mathcal{O}(|R| \cdot |O|)$~\cite{lcs_complex}, although many tailored algorithms exist that have an improved bound for specific classes of strings~\cite{survey, tour, efficient_alllcs, optimal_lcs}. In practice this means that only a subset of the elements of the matrix needs to be computed, in particular if only one solution (or just the distance value) is required. In general, the number of equivalent trace backs, called LCS~\emph{embeddings} in~\cite{fast_alllcs, bounds}, is exponentially bounded by $\binom{|R| + |O|}{|R|}$. We call the set of all minimal representations~$\Phi(R, O)$ and we formalize the relations between variants with regard to reference sequence~$R$ by using their respective~$O$~and~$P$~observed sequences as generic representations as follows. In the remainder of this paper we use the HGVS~syntax (not the full nomenclature) to describe a particular variant representation. \begin{definition}[Equivalence]\label{def:equivalence} Two variants~$\varphi_O$~and~$\varphi_P$ are \emph{equivalent} if and only if $\Phi(R, O) = \Phi(R, P)$. \end{definition} \noindent As all minimal representations are equivalent, the set of all minimal representations must be equal. Consequently, $O = P$. Note that these variants are equivalent regardless of the reference sequence~$R$. \paragraph{Example:} $R = \texttt{TTTTTT}, \quad \varphi_O = \texttt{1delT}, \quad \varphi_P = \texttt{6delT}$ \\ \texttt{1delT} and \texttt{6delT} are equivalent because their respective observed sequences are equal. Classic normalization procedures followed by exact string matching are sufficient to draw the same conclusion. This does not hold for the remaining relations as they rely on checking all combinations of all minimal alignments. \begin{definition}[Containment]\label{def:containment} The variant~$\varphi_O$ \emph{contains} the variant~$\varphi_P$ if and only if $\varphi_O' \varsupsetneq \varphi_P'$ for some $\varphi_O' \in \Phi(R, O)$ and $\varphi_P' \in \Phi(R, P)$ and $\varphi_O$ is not equivalent to $\varphi_P$. \end{definition} \noindent We find a representation within the set of minimal representations for~$O$ that is a proper subset of a representation within the set of minimal representations for~$P$. \paragraph{Example:} $R = \texttt{TTTTTT}, \quad \varphi_O = \texttt{2\_5delinsGGG}, \quad \varphi_P = \texttt{3T>G}$ \\ \texttt{2\_5delinsGGG} contains \texttt{3T>G} and conversely, \texttt{3T>G} is contained by \texttt{2\_5delinsGGG}. \bigskip \noindent Notable examples of this relation can be found by comparing multiple alleles of polymorphic simple tandem repeats, i.e., a long repeat expansion contains all shorter ones. \begin{definition}[Overlap]\label{def:overlap} Two non-equivalent variants~$\varphi_O$~and~$\varphi_P$ \emph{overlap} if and only if $\varphi_O' \cap \varphi_P' \neq \varnothing$ for some $\varphi_O' \in \Phi(R, O)$ and $\varphi_P' \in \Phi(R, P)$ while neither $\varphi_O$ contains $\varphi_P$ nor $\varphi_P$ contains $\varphi_O$. \end{definition} \noindent A proper subset of a representation within the set of minimal representations for~$O$ is shared with a proper subset of a representation within the set of minimal representations for~$P$. \paragraph{Example:} $R = \texttt{TTTTTT}, \quad \varphi_O = \texttt{2\_4delinsGG}, \quad \varphi_P = \texttt{3T>A}$ \\ \texttt{2\_4delinsGG} has overlap with \texttt{3T>A} (the converse is also true). \bigskip \noindent Polymorphic SNVs are a notable example of the overlap relation, as they share the deleted nucleotide, and the inserted nucleotide is different by definition. \begin{definition}[Disjoint]\label{def:disjoint} Two variants~$\varphi_O$~and~$\varphi_P$ are \emph{disjoint} if they are not equivalent, are not contained in one another, and do not overlap. \end{definition} \noindent None of the minimal representations of~$O$ share anything with any of the minimal representations of~$P$. \paragraph{Example:} $R = \texttt{TTTTTT}, \quad \varphi_O = \texttt{2\_3insA}, \quad \varphi_P = \texttt{4\_5insA}$ \\ \texttt{2\_3insA} and \texttt{4\_5insA} \emph{are disjoint}. Although both insert the same symbol (\texttt{A}), this cannot occur at a common position within~$R$. \bigskip \noindent The properties of the Boolean relations given in Table~\ref{tab:properties} follow directly from the aforementioned definitions. The table is provided for completeness and future reference, and throughout this paper we use these properties to reason about relations. \begin{table}[ht!] \caption{Properties of the Boolean relations. The converse of ``contains'' is ``is contained'' and \textit{vice versa}.}% \label{tab:properties} \begin{center} \begin{tabular}{l | lll} \textbf{relation} & \textbf{symmetry} & \textbf{reflexivity} & \textbf{transitivity} \\ \hline equivalent & symmetric & reflexive & transitive \\ contains & asymmetric & irreflexive & transitive \\ is contained & asymmetric & irreflexive & transitive \\ overlap & symmetric & irreflexive & intransitive \\ disjoint & symmetric & irreflexive & intransitive \\ \end{tabular} \end{center} \end{table} \section{An Efficient Algorithm}\label{sec:algorithm} The formal definitions of the Boolean relations presented in Section~\ref{sec:formal} depend on the enumeration of all minimal variant representations. As explained in~\cite{bounds}, the number of representations is bounded exponentially by the length of strings~$R$ and~$O$. For large strings (such as whole human chromosomes up to ca.~$250 \cdot 10^6$) this approach is infeasible. In this section we present an alternative and efficient way for the computation of each of the relations. \paragraph{Equivalence} As follows directly from Definition~\ref{def:equivalence}, equivalence can be computed by a string matching over $O$ and $P$ in $\mathcal{O}(\min(|O|, |P|))$ time and $\mathcal{O}(|O| + |P|)$ space (storing both strings). This is optimal. Alternatively, we can compute \emph{metric}~$d$ for $O$ and $P$: $d(O, P) = 0 \iff \varphi_O$ is equivalent to $\varphi_P$. \paragraph{Containment} By using the properties of the metric~$d$, we observe that computing the minimal distances is sufficient. Using the \emph{triangle inequality}: $d(R, O) - d(R, P) = d(O, P) \land d(O, P) > 0 \iff \varphi_O$ contains~$\varphi_P$. \paragraph{Disjoint} Again, using the triangle inequality for metric~$d$: $d(R, O) + d(R, P) = d(O, P) \land d(O, P) > 0 \implies \varphi_O$ and~$\varphi_P$ are disjoint. Unfortunately, the converse is not true. Consider the counterexample $R = \texttt{CT}$, $O = \texttt{TG}$, and $P = \texttt{GC}$. $O$ and $P$ are disjoint despite their simple edit distances being: $d(R, O) = 2,\, d(R, P) = 2,\, d(O, P) = 2$. Their representations, however, have no common elements: $\Phi(R, O) = \{\texttt{[1delC;2\_3insG]}\}$ and $\Phi(R, P) = \{\texttt{[0\_1insG;2delT]}\}$. \bigskip \noindent The aforementioned distance-based approach can be efficiently computed using any LCS distance algorithm tailored for similar strings, e.g., \cite{lcs_wu}. However, to separate the disjoint and overlap relations we need to consider all minimal representations. With the notable exception of the naive dynamic programming approach introduced in Section~\ref{sec:formal}, existing algorithms typically do not compute all representations. The naive approach suffers from a $\mathcal{O}(|R| \cdot |O|)$ space complexity rendering it infeasible for whole human chromosomes. \subsection{Computing all Minimal Variant Representations}\label{sec:lcs} Here, we present an efficient algorithm to compute the relevant elements of the recurrence relation (Equation~\ref{eq:edit}) to be able to reconstruct \emph{all} minimal representations (alignments) within the theoretical complexity bounds: $\mathcal{O}(|R| \cdot |O|)$ time and using $\mathcal{O}(|R| + |O|)$ temporary space (excluding storing the solution). In practice, because of the high similarity between $R$ and $O$ the expected run-time is linear. The output of this algorithm is an LCS-graph as introduced by~\cite{efficient_alllcs}. We use the generic A* search algorithm~\cite{astar} which uses a heuristic to guide the search. In general, the space requirements of A*~search might be of concern. However, in our case, the space is quadratically bounded by the number of elements in the matrix. Furthermore, we demonstrate that by expanding partial solutions in a particular order, it is possible to bound the space requirements linearly: $\mathcal{O}(|R| + |O|)$. \bigskip \noindent We introduce the \emph{admissible} heuristic: \begin{equation}\label{eq:heuristic} h(R, O, i, j) = \left\lvert\left(|R| - i\right) - \left(|O| - j\right)\right\rvert. \end{equation} \noindent The heuristic~$h$ represents a best-case guess for the minimal distance from the current element~$(i, j)$ to the bottom-right element of the matrix (hoping to match as many symbols as possible). A* minimizes the total cost function for each solution: \begin{equation}\label{eq:astar} f(R, O, i, j) = D(i, j) + h(R, O, i, j), \end{equation} \noindent by taking into account the actual cost to reach element~$(i, j)$, given by $D(i, j)$ (see Equation~\ref{eq:edit}), and the projected minimal cost~$h$. A*~search iteratively expands partial solutions, also called the \emph{frontier}, based on the lowest $f$~value until the target element is expanded. In our case the progression of $f$-values is determined by the heuristic value of the first element $h(0, 0) = ||R| - |O||$ increasing with steps of~$2$ as the cost function increases by $1$ for each orthogonal step and the heuristic changes with either $+1$ or $-1$ for each orthogonal step. Diagonal steps, i.e., matching symbols, do not incur a change in $f$-value. This results in a constant parity for the $f$-values. The simple edit distance is given by the $f$-value of the target element~$(|R|, |O|)$. Constructing all minimal variant representations is analogous to the naive approach detailed in Section~\ref{sec:formal}. In typical A* implementations, the frontier is implemented as a priority queue. In our case, we observe that we can keep track of the elements in the frontier by describing a ``convex'' shape in the matrix. We use two arrays~$\mathit{rows}$ and~$\mathit{cols}$ that store the right-most element for a given column and the bottom-most element for a given row respectively. In Figure~\ref{fig:astar} we present the progression of the expansion of the matrix elements for the example: $R = \texttt{CATATATCG}$ and $O = \texttt{CTTATAGCAT}$. We use $\mathcal{O}(|R| + |O|)$~space (excluding the output) and we expand at most $\mathcal{O}(|R| \cdot |O|)$~elements. \begin{figure}[ht!] \subfloat[Expanded elements for $f = 1$.]{ \begin{minipage}[c][1\width]{ 0.45\textwidth} \centering \[ \scalemath{0.62}{ \begin{array}{rc|ccccccccccc} \renewcommand*{\arraystretch}{1.2} & & \phantom{\circled{0}} & \phantom{\circled{1}} & \phantom{\circled{2}} & \phantom{\circled{3}} & \phantom{\circled{4}} & \phantom{\circled{5}} & \phantom{\circled{6}} & \phantom{\circled{7}} & \phantom{\circled{8}} & \phantom{\circled{9}} & \phantom{\circled{10}} \\ & & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ & & \texttt{.} & \texttt{C} & \texttt{T} & \texttt{T} & \texttt{A} & \texttt{T} & \texttt{A} & \texttt{G} & \texttt{C} & \texttt{A} & \texttt{T} \\ \hline 0 & \texttt{.} & 1 & 1 & & & & & & & & & \\ 1 & \texttt{C} & & \circled{1} & 1 & & & & & & & & \\ 2 & \texttt{A} & & & & & & & & & & & \\ 3 & \texttt{T} & & & & & & & & & & & \\ 4 & \texttt{A} & & & & & & & & & & & \\ 5 & \texttt{T} & & & & & & & & & & & \\ 6 & \texttt{A} & & & & & & & & & & & \\ 7 & \texttt{T} & & & & & & & & & & & \\ 8 & \texttt{C} & & & & & & & & & & & \\ 9 & \texttt{G} & & & & & & & & & & & \\ \end{array} } \] \vspace{-2em} {\small \begin{align*} \mathit{rows} &= [1, 2], \\ \mathit{cols} &= [0, 1, 1] \end{align*}}% \end{minipage}} \hfill \subfloat[Expanded elements for $f = 3$.]{ \begin{minipage}[c][1\width]{ 0.45\textwidth} \centering \[ \scalemath{0.62}{ \begin{array}{rc|ccccccccccc} \renewcommand*{\arraystretch}{1.2} & & \phantom{\circled{0}} & \phantom{\circled{1}} & \phantom{\circled{2}} & \phantom{\circled{3}} & \phantom{\circled{4}} & \phantom{\circled{5}} & \phantom{\circled{6}} & \phantom{\circled{7}} & \phantom{\circled{8}} & \phantom{\circled{9}} & \phantom{\circled{10}} \\ & & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ & & \texttt{.} & \texttt{C} & \texttt{T} & \texttt{T} & \texttt{A} & \texttt{T} & \texttt{A} & \texttt{G} & \texttt{C} & \texttt{A} & \texttt{T} \\ \hline 0 & \texttt{.} & 1 & 1 & 3 & & & & & & & & \\ 1 & \texttt{C} & 3 & \circled{1} & 1 & 3 & & & & & & & \\ 2 & \texttt{A} & & 3 & 3 & 3 & \circled{3} & & & & & & \\ 3 & \texttt{T} & & & \circled{3} & \circled{3} & 3 & \circled{3} & & & & & \\ 4 & \texttt{A} & & & & & \circled{3} & 3 & \circled{3} & & & & \\ 5 & \texttt{T} & & & & & & \circled{3} & 3 & & & & \\ 6 & \texttt{A} & & & & & & & \circled{3} & 3 & & & \\ 7 & \texttt{T} & & & & & & & & & & & \\ 8 & \texttt{C} & & & & & & & & & & & \\ 9 & \texttt{G} & & & & & & & & & & & \\ \end{array} } \] \vspace{-2em} {\small \begin{align*} \mathit{rows} &= [2, 3, 4, 5, 6, 6, 7], \\ \mathit{cols} &= [1, 2, 3, 3, 4, 5, 6, 6] \end{align*}}% \end{minipage}} \subfloat[Expanded elements for $f = 5$.]{ \begin{minipage}[c][1\width]{ 0.45\textwidth} \centering \[ \scalemath{0.62}{ \begin{array}{rc|ccccccccccc} \renewcommand*{\arraystretch}{1.2} & & \phantom{\circled{0}} & \phantom{\circled{1}} & \phantom{\circled{2}} & \phantom{\circled{3}} & \phantom{\circled{4}} & \phantom{\circled{5}} & \phantom{\circled{6}} & \phantom{\circled{7}} & \phantom{\circled{8}} & \phantom{\circled{9}} & \phantom{\circled{10}} \\ & & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ & & \texttt{.} & \texttt{C} & \texttt{T} & \texttt{T} & \texttt{A} & \texttt{T} & \texttt{A} & \texttt{G} & \texttt{C} & \texttt{A} & \texttt{T} \\ \hline 0 & \texttt{.} & 1 & 1 & 3 & 5 & & & & & & & \\ 1 & \texttt{C} & 3 & \circled{1} & 1 & 3 & 5 & & & & & & \\ 2 & \texttt{A} & 5 & 3 & 3 & 3 & \circled{3} & 5 & & & & & \\ 3 & \texttt{T} & & 5 & \circled{3} & \circled{3} & 3 & \circled{3} & 5 & & & & \\ 4 & \texttt{A} & & & 5 & 5 & \circled{3} & 3 & \circled{3} & 5 & & & \\ 5 & \texttt{T} & & & & \circled{5} & 5 & \circled{3} & 3 & 5 & & & \\ 6 & \texttt{A} & & & & & \circled{5} & 5 & \circled{3} & 3 & 5 & & \\ 7 & \texttt{T} & & & & & & \circled{5} & 5 & 5 & 5 & & \\ 8 & \texttt{C} & & & & & & & & & \circled{5} & 5 & \\ 9 & \texttt{G} & & & & & & & & & & & \\ \end{array} } \] \vspace{-2em} {\small \begin{align*} \mathit{rows} &= [3, 4, 5, 6, 7, 7, 8, 8, 9], \\ \mathit{cols} &= [2, 3, 4, 5, 6, 7, 7, 7, 8, 8] \end{align*}}% \end{minipage}} \hfill \subfloat[Expanded elements for $f = 7$.]{ \begin{minipage}[c][1\width]{ 0.45\textwidth} \centering \[ \scalemath{0.62}{ \begin{array}{rc|ccccccccccc} \renewcommand*{\arraystretch}{1.2} & & \phantom{\circled{0}} & \phantom{\circled{1}} & \phantom{\circled{2}} & \phantom{\circled{3}} & \phantom{\circled{4}} & \phantom{\circled{5}} & \phantom{\circled{6}} & \phantom{\circled{7}} & \phantom{\circled{8}} & \phantom{\circled{9}} & \phantom{\circled{10}} \\ & & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\ & & \texttt{.} & \texttt{C} & \texttt{T} & \texttt{T} & \texttt{A} & \texttt{T} & \texttt{A} & \texttt{G} & \texttt{C} & \texttt{A} & \texttt{T} \\ \hline 0 & \texttt{.} & 1 & 1 & 3 & 5 & 7 & & & & & & \\ 1 & \texttt{C} & 3 & \circled{1} & 1 & 3 & 5 & 7 & & & & & \\ 2 & \texttt{A} & 5 & 3 & 3 & 3 & \circled{3} & 5 & \circled{7} & & & & \\ 3 & \texttt{T} & 7 & 5 & \circled{3} & \circled{3} & 3 & \circled{3} & 5 & 7 & & & \\ 4 & \texttt{A} & & 7 & 5 & 5 & \circled{3} & 3 & \circled{3} & 5 & 7 & & \\ 5 & \texttt{T} & & & \circled{7} & \circled{5} & 5 & \circled{3} & 3 & 5 & 7 & & \\ 6 & \texttt{A} & & & & 7 & \circled{5} & 5 & \circled{3} & 3 & 5 & \circled{7} & \\ 7 & \texttt{T} & & & & & 7 & \circled{5} & 5 & 5 & 5 & 7 & \circled{7} \\ 8 & \texttt{C} & & & & & & 7 & 7 & 7 & \circled{5} & 5 & 7 \\ 9 & \texttt{G} & & & & & & & & \circled{7} & 7 & 7 & 7 \\ \end{array} } \] \vspace{-2em} {\small \begin{align*} \mathit{rows} &= [4, 5, 6, 7, 8, 8, 9, 10, 10, 10], \\ \mathit{cols} &= [3, 4, 5, 6, 7, 8, 8, 9, 9, 9, 9] \end{align*}}% \end{minipage}} \caption{Computing the relevant elements of Equation~\ref{eq:edit} to efficiently reconstruct the set of all elements of the set of all minimal variant representations.}\label{fig:astar} \end{figure} \noindent The non-filled elements are not part of any minimal representation. The circled elements are needed to create the LCS-graph and therefore stored. The remaining elements are expanded, but not stored. For each circled element we determine its place in the LCS by: \begin{equation} \left\lfloor\frac{i + j - D(i, j)}{2}\right\rfloor - 1. \end{equation} \noindent This allows us to construct the LCS-graph efficiently. The LCS-graph for the example in Figure~\ref{fig:astar} is given in Figure~\ref{fig:graph}. The nodes in the LCS-graph are ordered on their position in the LCS. To construct the variant representations, edges are added for each node on level~$n$ to each node on level~$n + 1$ if $\mathit{i}_{n+1} > \mathit{i}_n$ and $\mathit{j}_{n+1} > \mathit{j}_n$, where each node is given by its position~$(i, j)$ in $D$. For instance, there is an edge from node~$(3, 2)$ on level~$1$ to node~$(5, 3)$ on level~$2$ (\texttt{4delA}). All orthogonal steps (Manhattan paths) within such a rectangle contribute to the set of elements of all minimal variant representations ($\bigcup\Phi$). To distinguish between the relations disjoint and overlap, it is sufficient to determine whether the two sets~($\bigcup\Phi(R, O)$ and~$\bigcup\Phi(R, P)$) of these elements is disjoint. Note that the number of elements in each set is bounded quadratically as opposed to enumerating all, exponentially bounded, minimal representations. Within the genetic variant domain, the reference sequence and both observed sequences are expected to be highly similar, resulting in expected linear time. Some practical implementation enhancements can also be applied, notably, reducing the number of elements to be added to the set by taking (partially) overlapping rectangles (edges in the LCS-graph) into account. For small alphabets, e.g., DNA nucleotides, an efficient bit string can be used in lieu of a proper set implementation. \begin{figure}[ht!] \begin{center} \resizebox{\textwidth}{!} { \begin{tikzpicture} \node[align=center, draw, circle, fill] (00) at (0, 0) {}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (11) at (2, 0) {\texttt{C}\\ $(1, 1)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (32) at (5, -2) {\texttt{T}\\ $(3, 2)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (33) at (5, 0) {\texttt{T}\\ $(3, 3)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (24) at (5, 2) {\texttt{A}\\ $(2, 4)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (53) at (8, -2) {\texttt{T}\\ $(5, 3)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (44) at (8, 0) {\texttt{A}\\ $(4, 4)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (35) at (8, 2) {\texttt{T}\\ $(3, 5)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (64) at (11, -2) {\texttt{A}\\ $(6, 4)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (55) at (11, 0) {\texttt{T}\\ $(5, 5)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (46) at (11, 2) {\texttt{A}\\ $(4, 6)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (75) at (14, -2) {\texttt{T}\\ $(7, 5)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (66) at (14, 0) {\texttt{A}\\ $(6, 6)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (69) at (14, 2) {\texttt{A}\\ $(6, 9)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (88) at (17, -2) {\texttt{C}\\ $(8, 8)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (97) at (17, 0) {\texttt{G}\\ $(9, 7)$}; \node[align=center, draw, ellipse, thick, minimum width=4.8em] (710) at (17, 2) {\texttt{T}\\ $(7, 10)$}; \node[align=center, draw, circle, fill] (1011) at (20, 0) {}; \draw[-{Latex[width=.5em]}, semithick] (00) -- (11); \draw[-{Latex[width=.5em]}, semithick] (11) -- (24) node[above, left, midway] {\footnotesize \texttt{1\_2insTT}}; \draw[-{Latex[width=.5em]}, semithick] (11) -- (33) node[above, midway] {\footnotesize \texttt{2A>T}}; \draw[-{Latex[width=.5em]}, semithick] (11) -- (32) node[below, left, midway] {\footnotesize \texttt{2delA}}; \draw[-{Latex[width=.5em]}, semithick] (24) -- (35); \draw[-{Latex[width=.5em]}, semithick] (33) -- (44); \draw[-{Latex[width=.5em]}, semithick] (32) -- (53) node[above, midway] {\footnotesize \texttt{4delA}}; \draw[-{Latex[width=.5em]}, semithick] (32) -- (44) node[above, left, midway] {\footnotesize \texttt{3\_4insT}}; \draw[-{Latex[width=.5em]}, semithick] (35) -- (46); \draw[-{Latex[width=.5em]}, semithick] (44) -- (55); \draw[-{Latex[width=.5em]}, semithick] (53) -- (64); \draw[-{Latex[width=.5em]}, semithick] (46) -- (69) node[above, midway] {\footnotesize \texttt{5delinsGC}}; \draw[-{Latex[width=.5em]}, semithick] (55) -- (66); \draw[-{Latex[width=.5em]}, semithick] (55) -- (69) node[above, left, midway] {\footnotesize \texttt{5\_6insAGC}}; \draw[-{Latex[width=.5em]}, semithick] (64) -- (75); \draw[-{Latex[width=.5em]}, semithick] (66) -- (710) node[above, left, midway] {\footnotesize \texttt{6\_7insGCA}}; \draw[-{Latex[width=.5em]}, semithick] (66) -- (88) node[below, near end, xshift=-.5em] {\footnotesize \texttt{7T>G}}; \draw[-{Latex[width=.5em]}, semithick] (66) -- (97) node[above, midway] {\footnotesize \texttt{7\_8delTC}}; \draw[-{Latex[width=.5em]}, semithick] (69) -- (710); \draw[-{Latex[width=.5em]}, semithick] (75) -- (88) node[below, midway] {\footnotesize \texttt{7\_8insAG}}; \draw[-{Latex[width=.5em]}, semithick] (75) -- (97) node[above, near end, xshift=-.5em] {\footnotesize \texttt{8C>A}}; \draw[-{Latex[width=.5em]}, semithick] (710) -- (1011) node[above, right, midway] {\footnotesize \texttt{8\_9delCG}}; \draw[-{Latex[width=.5em]}, semithick] (88) -- (1011) node[below, right, midway] {\footnotesize \texttt{9delinsAT}}; \draw[-{Latex[width=.5em]}, semithick] (97) -- (1011) node[above, midway, xshift=-.5em] {\footnotesize \texttt{9\_10insCAT}}; \end{tikzpicture}} \end{center} \caption{The LCS-graph for $R = \texttt{CATATATCG}$ and $O = \texttt{CTTATAGCAT}$. The coordinates refer to the coordinates of the matching characters in Figure~\ref{fig:astar}. Unlabeled edges indicate consecutive matches and do not contribute to the set of elements of all minimal variant representations.}\label{fig:graph} \end{figure} \subsection{Maximal Influence Interval}\label{sec:influence} Given any pair of variants (within the context of the same reference sequence), it is likely that their relation is disjoint purely based on their respective positions in the reference sequence. These disjoint relations can be determined efficiently at the cost of some pre-computation for individual variants (n.b. not pairs of variants). For each variant the \emph{maximal influence interval}, i.e., the interval given by the lowest column index for a deletion or an insertion in~$D$ and the highest column index for a deletion or an insertion in~$D$. This interval gives the extreme bounds, as positions in the reference sequence, of possible changes due to this variant. A pair of variants can only be non-disjoint when their influence intervals intersect. The pre-computing of the influence intervals of individual variants is specifically worthwhile in the context of repeated querying, e.g., a (locus specific) database and VCF annotation. \section{Experiments}\label{sec:experiments} To obtain an intuition of the impact of the proposed approach, we analyzed the well-studied \textit{CFTR}~gene (NG\_016465.4 with $257,\!188$bp) that provides instructions for making the cystic fibrosis transmembrane conductance regulator protein). In dbSNP~\cite{dbsnp} there are $62,\!215$~interpretable variants for the \textit{CFTR}~gene which would lead to $1,\!935,\!322,\!005$~pairs of variants to analyze. Using the pre-filtering method described in Section~\ref{sec:influence}, only $92,\!251$~eligible pairs of variants with a potential non-disjoint relation remain. \begin{table}[ht!] \caption{Relation counts for the pairwise comparison of variants in the \textit{CFTR}~gene. The counts are given based on the upper triangular matrix, so the converse relations are not included.}\label{tab:relcounts} \begin{center} \begin{tabular}{l | r} \textbf{relation} & \textbf{count} \\ \hline equivalent & $0$ \\ contains & $5,\!491$ \\ is contained & $4,\!629$ \\ overlap & $37,\!690$ \\ disjoint & $44,\!441$ \\ \end{tabular} \end{center} \end{table} \noindent When the algebra is applied to the remaining pairs we obtain the results in Table~\ref{tab:relcounts}. We observe that there are no equivalent pairs, meaning that there are no duplicate variant entries for \textit{CFTR} in dbSNP (indicating a correct application of the standard normalization techniques). There are $10,\!120$~containment relations (either contains or is contained), $37,\!690$~pairs have some form of overlap, and $44,\!441$~pairs are completely disjoint. \begin{figure}[ht!] \begin{center} \begin{tikzpicture} \begin{axis}[% height=7cm, width=10cm, axis y line*=left, axis x line*=bottom, ticklabel style={font=\small}, xlabel=length of influence interval, ylabel=average number of relations ] \addplot[blue!50,fill=blue!30,only marks] table [% x=length, y=count]{\influencelength}; \end{axis} \end{tikzpicture} \caption{Scatterplot of the average number of relations for all variants in \textit{CFTR} with a certain influence interval length.}% \label{fig:influence_scatter} \end{center} \end{figure} Zooming in to individual variant level, we find that $16,\!939$~variants are disjoint with all other variants based on pre-filtering alone and $45,\!276$ are potentially involved in a non-disjoint relation with another variant. $16,\!814$ of which turn out to be disjoint with all other variants. In total, $33,\!753$~variants are completely disjoint with all other variants. The remaining $28,\!462$~variants have a non-disjoint relation to some other variant(s). \noindent In Table~\ref{tab:examples}, we see a selection of variants in \textit{CFTR} that, at first sight, have a counter-intuitive relation with another variant. For pair~$1$, the left hand side (LHS) variant contains the right hand side (RHS) variant because the former can be left-justified to \texttt{11402\_11406del} to incorporate the deletion of region $11,\!402$ to $11,\!403$. For pair~$2$, the containment is less obvious, the LHS needs to be rewritten to \texttt{[151240\_151241insTATA;151270\_151271insCA]} to make this containment relation intuitively clear. For pair~$3$, the LHS can be written as \texttt{[151242\_151243del;151271\_151278del]} to make the overlap relation between the two variants clear. For pair~$4$, left-justification of the LHS to \texttt{112270\_112271insCTCTCTC} and rewriting the RHS to \texttt{[112269\_112270insCC; 112270\_112271insCTCT]} makes the overlap relation obvious. Finally, we can see from both pair~$2$ and~$3$ that in practice, variants that are reported to be well separated, still may have something in common. \begin{table}[hb!] \caption{Examples of non-trivial relations between variants in \textit{CFTR}. The variants are described using the HGVS nomenclature with respect to reference sequence NG\_016465.4 using the genomic~(g.) coordinate system.}\label{tab:examples} \begin{center} \begin{tabular}{l|l|l|l} \textbf{pair} & \textbf{LHS variant} & \textbf{relation} & \textbf{RHS variant} \\ \hline $1$ & \texttt{11404\_11408del} & contains & \texttt{11402\_11403del} \\ $2$ & \texttt{151270\_151271insTATACA} & contains & \texttt{151240\_151241insAT} \\ $3$ & \texttt{151271\_151280del} & overlap & \texttt{151240\_151255del} \\ $4$ & \texttt{112274\_112275insCTCTCTC} & overlap & \texttt{112269\_112270insCCTCTC} \\ \end{tabular} \end{center} \end{table} \noindent The ratio between the length of the influence interval and the number of relations a variant has on average is shown in Figure~\ref{fig:influence_scatter}. The length of the influence interval correlates strongly with the number of relations of a variant as expected. The variants with the largest influence interval lengths ($>\!150$) all happen to be large deletions. \begin{figure}[ht!] \begin{center} \begin{tikzpicture} \begin{axis}[% height=7cm, width=10cm, xlabel=number of relations, axis y line*=left, axis x line*=bottom, ticklabel style={font=\small}, xticklabels={$1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$, $10$, $>\!10$}, xtick={1,...,11}, yticklabel style={/pgf/number format/fixed,}, scaled y ticks=false, ylabel=number of variants, ybar] \addplot[blue!50,fill=blue!30] table[% x=relations, y=count] {\relationscount}; \end{axis} \end{tikzpicture} \caption{The distribution of the number of relations per variant. The long tail of counts of $11$ and above are aggregated. The most relations a single variant has is $435$.}\label{fig:rel_count} \end{center} \end{figure} \noindent The distribution of the number of relations per variant is shown in Figure~\ref{fig:rel_count}. More than half of all variants ($16,\!735$) have a single non-trivial relation with another variant, the remaining $11,\!727$~variants have a non-trivial relation with multiple variants. The distributions for both overlap and inclusion relations, are nearly identical. \section{Discussion}\label{sec:discussion} The relation between a pair of variants is only well-defined when both variants are described in the context of the same reference sequence. In general, we can extend the definitions to include variants on different reference sequences, the natural interpretation of which would be to consider two variants on different reference sequences to be disjoint, e.g., a variant on human chromosome~1 has nothing in common with a variant on human chromosome~2. This interpretation is sensible as long as the reference sequences are unrelated. In practice however, many reference sequences are actually referring to the same (or a strongly related) genetic locus, e.g., genes on chromosomes, different transcripts for the same gene and chromosomes in different reference genomes. Arguably, variants described in the context of these reference sequences could be seen as having potentially a non-disjoint relation. To properly compare these variants on sequence level, the differences between the reference sequences should also be taken into account. Structural variants are often reported in non-exact manner, i.e., not on sequence level precise. These representations are unsuitable for our method. Even if an exact structural variant representation is given, it unlikely to yield meaningful results; as the exact positions are not the same across samples. Instead, e.g., gene copies can be analyzed by the algebra when they are provided individually. The choice of relations presented here follows the ones from set theory, commonly used in a wide range of domains. For some specific domains more refined relations exists as well, e.g., for intervals the relations: ``starts with'', ``ends with'' and ``is directly adjacent'' are useful extensions~\cite{interval}. The set of relations could be further partitioned using these, or other, refinements. Unfortunately, the set of relations (see Table~\ref{tab:properties}) does not contain a relation that implies an ordering of variants, i.e., $\Phi(R, O) \le \Phi(R, P)$. A partial order of variants would require a relation with the properties: reflexive, antisymmetric and transitive. Sorting variants or storing variants in a particular order in a database (indexing) is meaningless in the context of this algebra. The interval ordering based on the pre-computed influence intervals described in Section~\ref{sec:influence} mitigates this problem. \subsection{Maximal Overlap} The actual make-up of the common changes between two variants is never computed. For all relations except the overlap relation the common changes can be trivially given: none for disjoint variants, either of the variants for equivalence, and the ``smaller'' variant for containment, i.e., the one that is contained within the other. This leaves, however, the overlapping variants. In general, there are many different sets of common changes between overlapping variants, some of which, especially the larger ones, may be more (biologically) relevant than others. The algorithm described in Section~\ref{sec:algorithm} determines whether there is at least one common change. Computing the maximal size of the overlap requires enumerating an exponential number of possible alignments, which is infeasible for all but extremely short sequences. \subsection{General Normalization}\label{sec:general} The current practice of normalizing variant representations is sufficiently powerful to cater for the equivalence relation (also illustrated in Section~\ref{sec:experiments}). Determining other relations is, in general, impossible when given a single normalized representation. Even SNVs, often regarded as trivially normalized, are problematic when querying for containment. Consider reference~$R = \texttt{CACAT}$ and the SNV~\texttt{3C>T} to obtain the observed sequence~$O = \texttt{CATAT}$. In the classical sense no normalization is necessary. When we consider a second variant~\texttt{3\_4insT} (\texttt{CACTAT}) we might draw the conclusion that this insertion is contained within the SNV based on the normalized position. A possible third variant~\texttt{2\_3insT} (\texttt{CATCAT}) has the same relation, but is less trivially found. When substrings adjacent to the variant match subsequences of the deleted or inserted string, the number of alignments increases exponentially, so regardless of which normalization procedure is used, however sophisticated, counter examples like this can always be constructed. Therefore procedures that rely on normalization will, in general, lead to wrong conclusions and cannot be employed to determine relations between variants. Within the domain specific languages for variant representations different normalization schemes are used, where arbitrary choices influence the normalized representation, e.g., the $3'$ and $5'$-rules. From the alignment matrix~$D$, it is also possible to choose a canonical path that represents a normalized representation. Sensible choices are either a bottom-most or top-most path. This corresponds to favoring either deletions over insertions at the beginning of a variant (or vice versa). Note that for all minimal variant descriptions in any of the domain specific languages, corresponding alignments can be found. It could be worthwhile to investigate whether a comprehensive set of deterministic rules exist to find these alignments as this can be used in the formalization of these languages. \subsection{Non-minimal Variant Representations} So far, we assumed that all variant representations are minimal with regard to Equation~\ref{eq:edit}. In practice, this is not always the case, nor is it necessary for our approach to work as the only constraint on the variant representation is its interpretability (see Section~\ref{sec:intro}). The relations are computed on all minimal alignments, where a non-minimal representation is minimized as part of the procedure. Interpreting the relations based on non-minimal representations yield surprising results. When we consider the reference $R = \texttt{GCTTT}$ with variant~$\varphi_O = \texttt{[1G>A;2C>G;3T>C]}$ ($O = \texttt{AGCTT}$) and variant~$\varphi_P = \texttt{[1G>A;2C>G]}$ ($P = \texttt{AGTTT}$). The naive conclusion, based on the non-minimal representation, would be $\varphi_O$ contains $\varphi_P$. However, both $\varphi_O$ and $\varphi_P$ are not minimal. The minimal alignments for $\Phi(R, O) = \{\texttt{[0\_1insA;3delT]}, \texttt{[0\_1insA;4delT]}, \texttt{[0\_1insA;5delT]}\}$ and the minimal alignment for $\Phi(R, P) = \{\texttt{[0\_1insA;2delC]}\}$ show that that the actual relation is overlap instead of containment. \bigskip \noindent A variant representation (in the classical sense) that covers all possible minimal alignments simultaneously is impossible to find in the general case because of potential mutual exclusivity of sub-alignments. A trivial solution is the full listing of the observed sequence. This, however, offsets the benefits of a representation that is humanly understandable and furthermore it introduces a huge amount of redundant information for larger sequences. \noindent However, based on the influence intervals introduced in Section~\ref{sec:influence}, a normalized \emph{maximal} variant representation can be defined. These take the form of a deletion insertion where the deletion spans the entire influence interval and the insertion potentially contains redundant reference information. For the SNV example in Section~\ref{sec:general} the maximal representation is~\texttt{2\_3delinsAT}, where first an~\texttt{A} is deleted and inserted again. SPDI (and consequently VRS) prescribes a normalization procedure that follows a similar approach~\cite{spdi} by extending the variant in both directions using a rolling procedure. We note that such a procedure, in general, does not result in all minimal alignments (nor the extreme bounds) being contained in the representation for all variants. Arguably, a maximal representation is not suitable in all contexts, e.g., reporting clinical results, but within the context of storing large quantities of variants in, for instance a database, the proposed maximal representations are appealing as the variants can be properly ordered and indexed on their deleted interval. Furthermore, these representations contain all information needed to determine the relations with other variants in the database without the need to use the reference sequence. The drawback, however, is that potentially larger inserted sequences are stored (\texttt{AT} in the example). In practice however, the influence intervals are small compared to the length of the reference sequence. \section{Conclusions}\label{sec:conclusion} Looking beyond the identification of equivalent variants, we introduced a comprehensive set of Boolean relations: equivalence, containment, overlap and disjoint, that partitions the domain of binary variant relations. Using these relations, additional variants of interest, i.e., variants with a specific relation to the queried variant can be identified. We determine these relations by taking all minimal alignments (on sequence level) into account. The relations can be computed efficiently using a novel algorithm that computes all minimal alignments. We have shown that these relations occur frequently in existing datasets, notably large ones like dbSNP. Approximately half of the variants in the \textit{CFTR}~gene in dbSNP has at least one non-disjoint relation with another variant within the same gene. We have shown that normalization of variant representations is not powerful enough to answer any but the trivial relation queries. Inspired by the alignment matrix, we introduced a maximal variant representation that allows for querying all relations while the variants are efficiently indexed in a database setting. In the case where phased variants (alleles) are available, directly querying on other (combinations of) variants is possible, e.g., is a variant contained within a given allele. The quantification and the make-up of the overlap relation remains an open problem. Locus specific databases can, without changing their internal representation of variants, use our algebra to query on these relations. Because our method is not tied to a particular representation, it can also be applied in VCF annotation tools. \noindent A Python implementation is available at \path{https://github.com/mutalyzer/algebra} as well as an interface at \path{https://v3.mutalyzer.nl/algebra}. \subsection{Future Work} The current Python implementation is suitable for sequences with the length of that of an average gene. An implementation in a more performance oriented language allows for the use of whole human chromosomes. Although, from the algebra perspective, a single canonical (or normalized) representation is insufficient, we see advantages of having such a representation in different contexts (especially for human interpretation). By looking at patterns within all the minimal alignments, we can potentially construct a canonical representation that reflects these patterns on sequence level in the variant, e.g., repeated elements can be separated from larger variants or a sequence level argument can be given for why close by SNVs should be (or not be) combined. These observations could be combined in a new implementation of a variant description extractor~\cite{vde}. Dealing with variants in an algebraic way can possibly be extended to higher-level calculations such as union and subtraction. The ability to mathematically construct larger alleles from smaller variants seems appealing in many domains. These techniques would also enable a proper sequence level remapping of variants onto other reference sequences, which is a recurring problem with the publication of every new reference genome. \printbibliography \end{document}
{'timestamp': '2021-12-30T02:25:23', 'yymm': '2112', 'arxiv_id': '2112.14494', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14494'}
arxiv
\section*{Acknowledgements} Edith Cohen is supported by Israel Science Foundation grant no.\ 1595-19. Haim Kaplan is supported by Israel Science Foundation grant no.\ 1595-19, and the Blavatnik Family Foundation. Yishay Mansour has received funding from the European Research Council (ERC) under the European Union’sHorizon 2020 research and innovation program (grant agreement No. 882396), by the Israel Science Foundation (grant number 993/17) and the Yandex Initiative for Machine Learning at Tel Aviv University. Uri Stemmer is partially supported by the Israel Science Foundation (grant 1871/19) and by the Cyber Security Research Center at Ben-Gurion University of the Negev. \printbibliography \section{Empirical Results} We implemented in Python our two main algorithms for $k$-tuple clustering: $\mathsf{PrivatekAverages}$ and $\mathsf{PrivatekNoisyCenters}$. We compared the two algorithms in terms of the sample complexity that is needed to privately separate the samples from a given mixture of Gaussians. Namely, how many $k$-tuples we need to sample such that, when executing $\mathsf{PrivatekAverages}$ or $\mathsf{PrivatekNoisyCenters}$, the resulting $k$-tuple $Y = \set{\py_1,\ldots,\py_k}$ satisfies the following requirement: For every $i \in [k]$, there exists a point in $Y$ (call it $\py_i$), such that for every sample $\px$ that was drawn from the $i$'th Gaussian, it holds that $i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \py_j}$. We perform three tests, where in each test we considered a uniform mixture of $k$ standard spherical Gaussians around the means $\set{R\cdot \pt{e}_i, -R\cdot \pt{e}_i}_{i=1}^{k/2}$, where $\pt{e}_i$ is the $i$'th standard basis vector. In all the tests, we generated each $k$-tuple by running algorithm k-means++ \cite{kmeansplusplus} over enough samples. In Test1 (\cref{Test1}) we examined the sample complexity in the case $d=1$, $k=2$, for $R \in \set{2^5,2^6,\ldots,2^{9}}$. In Test2 (\cref{Test2}) we examined the case $d=4$, $R = 512 \cdot k$, for $k \in \set{2,4,6,8}$. In Test3 (\cref{Test3}) we examined the case $k=2$, $R=256\sqrt{d}$, for $d \in \set{4,8,12,16}$. In all the experiments we used privacy parameters $\varepsilon = 1$ and $\delta = e^{-28}$, and used $\beta = 0.05$. In all the tests of $\mathsf{PrivatekNoisyCenters}$, we chose $\Delta = \frac{10}{\varepsilon}\cdot k \log(k/\delta) \sqrt{\log(k/\beta)}$, the number of $k$-tuples that we generated was exactly $3781$ (the minimal value that is required for privacy), but the number of samples per $k$-tuple varied from test to test. In the tests of $\mathsf{PrivatekAverages}$, we chose $\Lambda = 2^{10} \cdot k \sqrt{d}$ and $r_{\min} = 0.1$, we generated each $k$-tuple using $\approx 15 \cdot k$ samples, but the number of $k$-tuples varied from test to test.\footnote{By using $\tilde{\Omega}(kd)$ samples for creating each $k$-tuple, in Test3 (\cref{Test3}) we could avoid the dependency of $R$ in $\sqrt{d}$ (see \cref{sec:Gaussians:remarks} for more details). However, since we only used $O(k)$ samples for each $k$-tuple when testing $\mathsf{PrivatekAverages}$, then we could not avoid this dependency.} All the experiments were tested in a MacBook Pro Laptop with 4-core Intel i7 CPU with 2.8GHz, and with 16GB RAM. \begin{figure}[t] \centerline{\includegraphics[scale=.5]{Test1.png}} \caption{The case $d=1$ and $k=2$, for varies $R$.} \label{Test1} \end{figure} \begin{figure}[t] \centerline{\includegraphics[scale=.5]{Test2.png}} \caption{The case $d=4$ and $R=512 \cdot k$, for varies $k$.} \label{Test2} \end{figure} \begin{figure}[b] \centerline{\includegraphics[scale=.5]{Test3.png}} \caption{The case $k=2$, $R = 256 \sqrt{d}$, for varies $d$.} \label{Test3} \end{figure} The graphs show the main bottleneck of Algorithm $\mathsf{PrivatekAverages}$ in practice. It requires only $O_{\varepsilon,\delta}(k d)$ tuples (or $O_{\varepsilon,\delta}(k \sqrt{d})$ for large values of $d$) in order to succeed, but the hidden constant is $\approx 500,000$ for our choice of $\varepsilon$ and $\delta$, and this does not improve even when the assumed separation $R$ is very large. The cause of this large constant is the group privacy of size $O(k \ell)$ that we do in Step~\ref{step:computing-noisy-bound-aver}, where recall that $\ell = O\paren{\frac{\log^2(1/\delta)}{\varepsilon \log n}}$ (\cref{def:ell}). While in theory this $\ell$ is relatively small, with our choice of parameters we get $\ell \approx 1000$. This means that we need to execute the private average algorithm with $\hat{\varepsilon} \approx \frac{\varepsilon}{4000 k}$. Internally, this $\hat{\varepsilon}$ is shared between other private algorithms, and in particular, with an Interior Point algorithm that is one of the internal components of the average algorithm from \cref{prop:approx-aver-Rd}. This algorithm is implemented using the exponential mechanism \cite{MT07}, which simply outputs a random noise when the number of points is too small. We remark that prior work on differentially-private clustering, including in "easy" settings, is primarily theoretical. In particular, we are not aware of implemented methods that we could use as a baseline.\footnote{\Enote{Added:}We remark that in different settings, such as node, edge or weight-differential privacy, there exist some available implementations (e.g., \cite{PinotMYGA18}).} As a sanity check, we did consider the following naive baseline: For every sample point, add a Gaussian noise to make it private. Now, the resulting noisy samples are just samples from a new Gaussian mixture. Then, run an off-the-shelf non-private method to learn the parameters of this mixture. We tested this naive method on the simple case $d=1$ and $k=2$, where we generated samples from a mixture of standard Gaussians that are separated by $R = 512$. By the Gaussian mechanism, the noise magnitude that we need to add to each point for guaranteeing $(\varepsilon,\delta)$-differential privacy, is $\sigma \approx \frac{\Lambda}{\varepsilon}\sqrt{\log(1/\delta)} \gg 1$ for some $\Lambda > R$, meaning that the resulting mixture consists of very close Gaussians. We applied GaussianMixture from the package sklearn.mixture to learn this mixture, but it failed even when we used $100 M$ samples, as this method is not intended for learning such close Gaussians. We remark that there are other non-private methods that are designed to learn any mixture of Gaussians (even very weakly separated ones) using enough samples (e.g., \cite{suresh2014near}). The sample complexity and running time of these methods, however, are much worse than ours even asymptotically (e.g., the running time of \cite{suresh2014near} is exponential in $k$), and moreover, we are not aware of any implementation we could use.\footnote{Asymptotically, \cite{suresh2014near} requires at least $\tilde{\Omega}(d k^9)$ samples, and runs in time $\tilde{\Omega}(n^2d + d^2 (k^7 \log d)^{k^2})$. For the setting of learning a mixture of $k$ well-separated Gaussians, the approach of first adding noise to each point and then applying a non-private method such as \cite{suresh2014near}, results with much worse parameters than our result, which only requires $\tilde{O}(dk)$ samples and runs in time $\tilde{O}(dk^2n)$.} \section{Conclusion} We developed an approach to bridge the \remove{gaping }gap between the theory and practice of differentially private clustering methods. For future, we hope to further optimize the "constants" in the $k$-tuple clustering algorithms, making the approach practical for instances with lower separation. Tangentially, the inherent limitations of private versus non-private clustering suggest exploring different rigorous notions of privacy in the context of clustering. \section{Introduction} Differential privacy \cite{DworkMNS06} is a mathematical definition of privacy, that aims to enable statistical analyses of databases while providing strong guarantees that individual-level information does not leak. Privacy is achieved in differentially private algorithms through randomization and the introduction of ``noise'' to obscure the effect of each individual, and thus differentially private algorithms can be less accurate than their non-private analogues. In most cases, this loss in accuracy is studied theoretically, using asymptotic tools. As a result, there is currently a significant gap between what is known to be possible {\em theoretically} and what can be done {\em in practice} with differential privacy. In this work we take an important step towards bridging this gap in the context of {\em clustering related tasks}. The construction of differentially private clustering algorithms has attracted a lot of attention over the last decade, and many different algorithms have been suggested.\footnote{\cite{BDMN05,NRS07,FFKN09, McSherry09,GuptaLMRT10,Mohan2012,Wang2015,NockCBN16, Su2016,NSV16,DannyPrivatekMeans,Balcan17a, NS18_1Cluster,HuangL18,KaplanSt18,Stemmer20,ShechnerSS20,Ghazi0M20,Nguyen20}} However, to the best of our knowledge, none of these algorithms have been implemented: They are not particularly simple and suffer from large hidden constants that translate to a significant loss in utility, compared to non-private implementations. \begin{question} How hard is it to cluster privately with a practical implementation? \end{question} We take an important step in this direction using the following approach. Instead of directly tackling ``standard'' clustering tasks, such as $k$-means clustering, we begin by identifying a very simple clustering problem that still seems to capture many of the challenges of practical implementations (we remark that this problem is completely trivial without privacy requirements). We then design effective (private) algorithms for this simple problem. Finally, we reduce ``standard'' clustering tasks to this simple problem, thereby obtaining private algorithms for other tasks. In more detail, we introduce the following problem, called the {\em $k$-tuple clustering} problem. \begin{definition}[informal, revised in Definition~\ref{def:ktupleclustering}] An instance of the {\em $k$-tuple clustering} problem is a collection of $k$-tuples. Assuming that the input tuples can be partitioned into $k$ ``obvious clusters'', each consisting of one point of each tuple, then the goal is to report $k$ ``cluster-centers'' that correctly partition the input tuples into clusters. If this assumption on the input structure does not hold, then the outcome is not restricted. \end{definition} \begin{remark}\; \begin{enumerate} \item By ``obvious clusters'' we mean clusters which are far away from each other.\vspace{-7pt} \item The input tuples are {\em unordered}. This means, e.g.,\ that the ``correct'' clustering might place the first point of one tuple with the fifth point of another tuple.\vspace{-7pt} \item Of course, we want to solve this problem while guaranteeing differential privacy. Intuitively, this means that the outcome of our algorithm should not be significantly effected when arbitrarily modifying one of the input tuples. \end{enumerate} \end{remark} Observe that without the privacy requirement this task is trivial: We can just take one arbitrary input tuple $(x_1,...,x_k)$ and report it. With the privacy requirement, this task turns out to be non-trivial. It’s not that this problem cannot be solved with differential privacy. It can. It’s not even that the problem requires large amounts of data asymptotically. It does not. However, it turns out that designing an implementation with a practical privacy-utility tradeoff, that is effective on finite datasets (of reasonable size), is quite challenging. \subsection{Our algorithms for the ${\boldsymbol k}$-tuple problem} We present two (differentially private) algorithms for the $k$-tuple clustering problem, which we call $\mathsf{PrivatekAverages}$ and $\mathsf{PrivatekNoisyCenters}$. Both algorithms first privately test if indeed the input is partitioned into $k$ obvious clusters and quit otherwise. They differ by the way they compute the centers in case this test passes. Algorithm $\mathsf{PrivatekAverages}$ privately averages each identified cluster. Algorithm $\mathsf{PrivatekNoisyCenters}$, on the other hand, does not operate by averaging clusters. Instead, it selects one of the input $k$-tuples, and then adds a (relatively small) Gaussian noise to every point in this tuple. We prove that this is private if indeed there are $k$ obvious clusters in the input. We evaluate these two algorithms empirically, and show that, while algorithm $\mathsf{PrivatekAverages}$ is ``better in theory'', algorithm $\mathsf{PrivatekNoisyCenters}$ is much more practical for some interesting regimes of parameters. We now give a simplified overview of the ideas behind our algorithms. For concreteness, we focus here on $\mathsf{PrivatekAverages}$. Recall that in the $k$-tuple clustering problem, we are only required to produce a good output assuming the data is ``nice'' in the sense that the input tuples can be clustered into $k$ ``far clusters'' such that every cluster contains exactly one point from every tuple. However, with differential privacy we are ``forced'' to produce good outputs even when this niceness assumption does not hold. This happens because if the input data is ``almost nice'' (in the sense that modifying a small number of tuples makes it nice) then differential privacy states that the outcome of the computation should be close to what it is when the input data is nice. So, the definition of differential privacy forces us to cope with ``almost nice'' datasets. Therefore, the niceness test that we start with has to be a bit clever and ``soft'' and succeed with some probability also for data which is ``almost nice''. Then, in order to achieve good performances, we have to utilize the assumption that the data is ``almost nice'' when we compute the private centers. To compute these centers, Algorithm $\mathsf{PrivatekAverages}$ determines ({\em non-privately}) a clustering of the input tuples, and then averages (with noise) each of the clusters. The conceptual challenge here is to show that even though the clustering of the data is done non-privately, it is stable enough such that the outcome of this algorithm still preserves privacy. \subsection{Applications}\label{sec:introApplications} The significance of algorithms $\mathsf{PrivatekAverages}$ and $\mathsf{PrivatekNoisyCenters}$ is that many clustering related tasks can be privately solved by a reduction to the $k$-tuple clustering problem. In this work we explore two important use-cases: (1) Privately approximating the $k$-means under stability assumption, and (2) Privately learning the parameters of a mixture of well-separated Gaussians. \smallskip \noindent {\bf ${\boldsymbol k}$-Means Clustering} In $k$-means clustering, we are given a database ${\cal P}$ of $n$ input points in ${\mathbb R}^d$, and the goal is to identify a set $C$ of $k$ {\em centers} in ${\mathbb R}^d$ that minimizes the sum of squared distances from each input point to its nearest center. This problem is NP-hard to solve exactly, and even NP-hard to approximate to within a multiplicative factor smaller than $1.0013$ \citep{lee2017improved}. The current (non-private) state-of-the-art algorithm achieves a multiplicative error of $6.357$ \citep{ahmadian2019better}. One avenue that has been very fruitful in obtaining more accurate algorithms (non-privately) is to look beyond worst-case analysis \cite{OstrovskyRSS12,awasthi2010stability,ABS12,balcan2009approximate,bilu2012stable,kumar2010clustering}. In more details, instead of constructing algorithms which are guaranteed to produce an approximate clustering for any instance, works in this vain give stronger accuracy guarantees by focusing only on instances that adhere to certain ``nice'' properties (sometimes called stability assumptions or separation conditions). The above mentioned works showed that such ``nice'' inputs can be clustered much better than what is possible in the worst-case (i.e., without assumptions on the data). Given the success of non-private stability-based clustering, it is not surprising that such stability assumptions were also utilized in the privacy literature, specifically by \citet{NRS07,Wang2015,HuangL18,ShechnerSS20}. While several interesting concepts arise from these four works, none of their algorithms have been implemented, their algorithms are relatively complex, and their practicability on finite datasets is not clear. We show that the problem of stability-based clustering (with privacy) can be reduced to the $k$-tuple clustering problem. Instantiating this reduction with our algorithms for the $k$-tuple clustering problem, we obtain a simple and practical algorithm for clustering ``nice'' $k$-means instances privately. \smallskip \noindent {\bf Learning Mixtures of Gaussians.} Consider the task of {\em privately} learning the parameters of an unknown mixtures of Gaussians given i.i.d.\ samples from it. By now, there are various private algorithms that learn the parameters of a {\em single} Gaussian \cite{KV18,KLSU19,CWZ19,BS19,KSU20,BDKU20}. Recently, \cite{KSSU19} presented a private algorithm for learning mixtures of well-separated (and bounded) Gaussians. We remark, however, that besides the result of \cite{BDKU20}, which is a practical algorithm for learning a single Gaussian, all the other results are primarily theoretical. By a reduction to the $k$-tuples clustering problem, we present a simple algorithm that privately learns the parameters of a separated (and bounded) {\em mixture} of $k$ Gaussians. From a practical perspective, compared with the construction of the main algorithm of \cite{KSSU19}, our algorithm is simple and implementable. From a theoretical perspective, our algorithm offers reduced sample complexity, weaker separation assumption, and modularity. See \cref{sec:Gauss:comparison} for the full comparison. \subsection{Other Related Work} The work of \citet{NRS07} presented the sample-and-aggregate method to convert a non-private algorithm into a private algorithm, and applied it to easy clustering problems. However, their results are far from being tight, and they did not explore certain considerations (e.g., how to minimize the impact of a large domain in learning mixture of Gaussians). Another work by \citet{BKSW19} provides a general method to convert from a cover of a class of distributions to a private learning algorithm for the same class. The work gets a near-optimal sample complexity, but the algorithms have exponential running time in both $k$ and $d$ and their learning guarantees are incomparable to ours (they perform proper learning, while we provide clustering and parameter estimation). In the work of \cite{KSSU19}, they presented an alternative algorithm for learning mixtures of Gaussians, which optimizes the sample-and-aggregate approach of \cite{NRS07}, and is somewhat similar to our approach. That is, their algorithm executes a non-private algorithm several times, each time for obtaining a new ``$k$-tuple'' of means estimations, and then aggregates the findings by privately determine a new $k$-tuple of means estimation. But their approach has two drawbacks. First, in order to privately do that, their algorithm ignores the special $k$-tuples structure, and apply a more wasteful and complicated ``minimal enclosing ball'' algorithm from \cite{NS17_clustering,NSV16}. Second, in contrast to them, for creating a $k$-tuple, our algorithm only applies a non-private algorithm for \emph{separating} the samples in the mixture (i.e., for determine which samples belong to the same Gaussian), and not for estimating their parameters. This yields that we need less samples per invocation of the non-private algorithm for creating a single $k$-tuple, which results with an improved sample complexity (each $k$-tuple in our case is just the averages of each set of samples, which might not necessarily be very close to the true means, but is close enough for our setting where the Gaussians are well-separated). Finally, given a private separation of the sample, we just apply some private algorithm for estimating the parameters of each (single) Gaussian (e.g., \cite{KV18,KLSU19,CWZ19,BS19,KSU20,BDKU20}). For more details about our construction, see \cref{sec:mixture-of-gaus}. Furthermore, there are many differentially-private algorithms that are related to learning mixture of Gaussians (notably PCA) \cite{BlumDwMcNi05,KT13,CSS13,DTTZ14}, and differentially-private algorithms for clustering \cite{NRS07,GuptaLMRT10,NSV16,NS17_clustering,Balcan17a,KaplanSt18,HuangL18,Ghazi0M20}. We remark that for the learning Gaussians mixtures problem, applying these algorithms naively would introduce a polynomial dependence on the range of the data, which we seek to avoid. \remove{ \Enote{Old intro:} \section{Introduction} \ECnote{Add general text about what is privacy and its importance ... } put text \ECnote{Clustering-type problems, define the DP requirement (central model) in that context} In $k$-means clustering, we are given a database ${\cal P}$ of $n$ points in ${\mathbb R}^d$, and the goal is to identify a set $C$ of $k$ centers in ${\mathbb R}^d$ that approximately minimizes ${\rm COST}_{{\cal P}}(C) = \sum_{\px \in {\cal P}} \min_{\pc \in C}\norm{\px - \pc}^2$. We denote the lowest possible cost as ${\rm OPT}_{k}({\cal P})$. Since the task of minimizing the $k$-means is NP-hard, the literature has focused on approximation algorithms, with the current (non-private) state-of-the-art achieving multiplicative error of $6.357$ \cite{ahmadian2019better}. \ECnote{Mention practical solutions to the problem. Cite, EM, $k$-means++, bi-criteria. Also cite earlier results on multiplicative factors theoretical. Make a distinction between theory (very large running times, asymptotically) and practice.} \ECnote{Condense the below to precisely define neighboring and DP} \begin{definition}[Neighboring databases]\label{def:neighboring} Let ${\cal D} = \set{x_1,\ldots,x_n}$ and ${\cal D}' = \set{x_1',\ldots,x_n'}$ be two databases over a domain ${\cal X}$. We say that ${\cal D}$ and ${\cal D}'$ are \textbf{neighboring} if there is exactly one index $i \in [n]$ with $x_i \neq x_i'$. \end{definition} \begin{definition}[$(\varepsilon,\delta)$-indistinguishable]\label{def:indis} Two random variable $X,X'$ over a domain ${\cal X}$ are called $(\varepsilon,\delta)$-indistinguishable, if for any event $T \subseteq {\cal X}$, it holds that $\pr{X \in T} \leq e^{\varepsilon} \cdot \pr{Y \in T} + \delta$. If $\delta = 0$, we say that $X$ and $X'$ are $\varepsilon$-indistinguishable. \end{definition} \begin{definition}[$(\varepsilon,\delta)$-differential privacy \cite{DworkMNS06}]\label{def:DP} An algorithm $\cA$ is called $(\varepsilon,\delta)$-differentially private, if for any two neighboring databases ${\cal D},{\cal D}'$ it holds that $\cA({\cal D})$ and $\cA({\cal D}')$ are $(\varepsilon,\delta)$-indistinguishable. If $\delta = 0$ (i.e., pure privacy), we say that $\cA$ is called $\varepsilon$-differentially private. \end{definition} \ECnote{Add text, borrowing from below, on results for DP clustering in the central model, difficulties, gap from practice. Why these problems so far defied practical solutions. Also on mixtures of Gaussians.} Unlike in the non-private literature, it is known that every private algorithm for approximating the $k$-means cost must have an additive error (even computationally unbounded algorithms), which scales with the diameter of the input space. Hence, it is standard to assume an upper bound $\Lambda$ on the $\ell_2$ norm of all the input points ${\cal P}$. Typically (though not always), one aims to minimize the multiplicative error while keeping the additive error at most polylogarithmic in the size of the database. The current state-of-the-art construction \Enote{ .....} \ECnote{cite line of prior work on DP clustering (without assumptions on input). Culminating in Ravi/Nguyen. stressing not practical but illuminating} \ECnote{Meta question: Can we get closer to practice when the data is "Easy."?} \ECnote{Discuss easy or stable instances, what is known without privacy. In particular discuss $k$-means clustering and separating mixtures.} The non-private literature is ripe with results geared for efficient solutions on easier instances. Including dodging the NP hardness of unrestricted $k$-means clustering. {\bf edit below} As a common concrete example of such ${\cal P}$ and ${\cal A}$ that satisfy the above stability property is when ${\cal A}$ is a good (non-private) approximation algorithm for $k$-means, and ${\cal P}$ is well-separated for $k$-means, a notion that was first introduced in \citet{OstrovskyRSS12}. Formally, ${\cal P}$ is called $\phi$-separated if ${\rm OPT}_{k}({\cal P}) \leq \phi^2 {\rm OPT}_{k-1}({\cal P})$. It turns out that if ${\cal P}$ is $\phi$-separated for $k$-means, and ${\cal A}$ is a $\omega$-approximation algorithm for $k$-means, where $\phi^2(1 + \omega)$ is sufficiently small, then ${\cal P}$ and ${\cal A}$ satisfy our required stability property, yielding that our algorithm $\mathsf{PrivatekMeans}$ succeed well over ${\cal P}$ using ${\cal A}$. Following the work of \citet{OstrovskyRSS12}, several other works have related other notions of input-stability to clustering \cite{awasthi2010stability,awasthi2012center,balcan2009approximate,bilu2012stable,kumar2010clustering}. \ECnote{Discuss easy or stable instances, what is known with privacy. } {\bf edit below} In addition, several works gave differentially-private algorithms for approximating the minimal Wasserstein distance (\cite{Wasserstein1969}) of well-separated instances \cite{NRS07,wang2015differentially,huang2018optimal}, and in a recent work, \citet{ShechnerSS20} presented a differentially-private algorithm for approximating the $k$-means of such well-separated instances. The main result of \cite{ShechnerSS20} is a very simple transformation, called Private-Stable-$k$-Means, from any private $\omega$-approximation algorithm to a private $(1 + O(\phi^2))$-one, that works over $\phi$-separated database ${\cal P}$ with sufficiently small $\phi^2(1 + \omega)$. In addition, they presented Algorithm SampleAggregate-$k$-means that transform any (non-private) $k$-means approximation algorithm ${\cal A}$ into a private one, with very similar guarantees to our construction. Their algorithm also randomly partitions ${\cal P}$ into $T$ subsets (for large enough $T \ll n$), and executes ${\cal A}$ on each subset to obtain $k$ centers that are close to the optimal centers. But then, in order to privately estimating the averages of each cluster of the resulting partitioned multiset of $k$-tuples, their algorithm ignores the $k$-tuples structure and uses the (complicated) \cite{NS17_clustering}'s minimal enclosing ball algorithm for determine the clusters, while our algorithm uses Algorithm $\mathsf{PrivatekAverages}$ which is much more simpler and practical. \ECnote{Perhaps here discuss mixture of Gaussians, what is known, what would we consider stable.} \ECnote{Our approach and contributions at the high level} We define a basic problem of \emph{$k$-tuple clustering}. The input to $k$-tuple clustering is a set ${\cal T}$ of unordered $k$-tuples of vectors in ${\mathbb R}^d$. The desired output is a single $k$-tuple that (informally) perfectly separates a maximum number of tuples from ${\cal T}$. We design differentially private algorithms for $k$-tuple clustering that (informally) provide good utility on datasets for which a good solution exist. The algorithms we design for $k$-tuple clustering are relatively simple and friendlier to implement compared with alternative solutions based on existing differentially private tools and at the same time also provide tighter asymptotic bounds. We propose a framework to tackle private solutions for $k$-clustering type problems, where the input is a dataset of points in ${\mathbb R}^d$ and the output a set of $k$ points (a $k$-tuple). Our framework uses private $k$-tuple clustering as a tool and also assumes a non-private algorithm for the original problem that inputs a set of points and generates a $k$-tuple (e.g., $k$ cluster centers). The framework applies the non-private algorithm multiple times, to subsets (random samples) of the data. These runs yield a set ${\cal T}$ of $k$-tuples. Our private $k$-tuple clustering algorithm is then applies to ${\cal T}$ to generate a private $k$-tuple. The utility we obtain is conditioned on the instance being "stable" with respect to the original problem: Informally, that the $k$-tuples generated by the multiple applications of the non-private algorithm cluster well. We apply our framework to two well-studied $k$-clustering type problems: Our first application is to $k$-means clustering on well-separated instances. We obtain a differentially-private algorithm that is considerably simpler and more efficient than the state-of-the-art result of \citet{ShechnerSS20}. \ECnote{Put here more direct comparison to Shechner... (what we have that is not there)} The second application is to privately learn the parameters of mixtures of well-separated Gaussians. Our solution is both simpler and provides an asymptotic improvement over the state-of-the-art result of [Kamath et al. NeurIPS 2019]. Finally, we present empirical results for learning mixtures of very separated Gaussians, making our work the first that present a practical differentially-private algorithm for this task. \section{The tuple clustering problem} \ECnote{Precise definition, discussion on non-private and alternative private approaches and what is obtained, pseudocode, statement of properties} A $k$-tuple $X = \set{\px_1,\ldots,\px_k}$ is an unordered set of $k$ vectors $\px_i \in {\mathbb R}^d$. For a $k$-tuple $X$ and parameter $\Delta >0$ we define radii $(r_i^{X})_{i=1}^k$ so that $r_i^X = \min_{j \neq i} \norm{\px_i - \px_j}$. \begin{definition}[$\Delta$-partition of a tuple by a tuple] We say that a $k$-tuple $X$ $\Delta$-partitions another $k$-tuple $Y$ if each entry $\px_i$ of $X$ can be uniquely matched to entry $\py_{i_j}$ of $Y$ so that \[ \norm{\px_i - \py_{i_j}} \leq \frac1{\Delta} \cdot r_i^X(\Delta) .\] \end{definition} \Hnote{ Why $r_i^X(\Delta)$ ? and not $r_i^X$} \begin{definition}[$\Delta$-far balls] For a $k$-tuple $X$ and $\Delta$ we can consider a set of $k$ balls ${\cal B} = \set{B_1,\ldots,B_k}$, where $B_i(\px_i,\frac{1}{\Delta} r^X_i)$ has center $\px_i$ and radius, $\frac{1}{\Delta} r^X_i$. We refer to such balls as $\Delta$-far balls. \end{definition} Equivalently, A tuple $Y$ is $\Delta$-partitioned by $X$ if each ball in ${\cal B}$ contains exactly one entry from $Y$. \Hnote{Don't we want to parameterize the balls by X ? ${\cal B}^X$ ?} \begin{definition}[$k$-tuple clustering] The input to the problem is database ${\cal T}$ of $k$-tuples of size $n$ and $\Delta>1$. The output is a tuple that $\Delta$-partitions the maximum number of other tuples. \end{definition} We define "easy" instances to be those with a perfect solution, that is, we are promised that there is a tuple that $\Delta$-partition all other tuples. Without the requirement of privacy, the "easy" problem is quite easy to solve exactly. One can just pick an arbitrary $k$-tuple $\set{\px_1,\ldots,\px_k} \in {\cal T}$, construct the cluster ${\cal P}_1,\ldots,{\cal P}_k$ where ${\cal P}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \px_j}}$, and then compute the average $\pa_i$ of each ${\cal P}_i$. \Hnote{why not just spit an arbitrary tuple ?} However, this algorithm is not differentially private. To be differentially private, any outcome should be obtained with approximately the same probability when we change a single $k$-tuple (possibly moving to a neighboring database with no perfect solution \Hnote{We also have to deal with databases which are not easy ?}). In this algorithm, changing a single $k$-tuple may completely change the resulting partition (e.g., if the arbitrary tuple that we choose at the first step is exactly the different tuple), and hence, change the resulting averages. We therefore must consider approximate solutions and probabilistic outputs. Even for $k=1$ (which is a task of finding a point close to all other points), we need to assume some upper bound $\Lambda$ on the $\ell_2$ norm of the points in each tuple in ${\cal T}$. Second, we have to assume $r_{\min} > 0$ \ECnote{We need to explain $r_{\min}$ this better. Perhaps we can factor in $r_{\min}$ to the approximation. } We say that an algorithm is an $(\alpha,\beta)$-approximation to a perfect $k$-tuple clustering instance ${\cal T}$ if with probability $1-\beta$, it outputs $\set{pa_1,\ldots,\pa_k}$ that $\alpha\Delta$ partitions all tuples. \ECnote{I did some editing. Is the above ok? } \ECnote{discuss approaches with existing components and why they are not satisfactory. Not simple, large constants. } A direct approach to a private solution is through the Minimal Enclosing Ball algorithm of \citet{NS17_clustering}. This algorithm is given $n$ points and a (large enough) parameter $t \leq n$, and privately outputs a ball of radius $O(r_{opt})$ that contains (almost) $t$ points, where $r_{opt}$ is the radius of the smallest ball that contains $t$ points. To apply this algorithm to our problem, we ignore the $k$-tuple structure and execute \cite{NS17_clustering}'s algorithm $k$ times on the database ${\rm Points}({\cal T})$. Each time it would privately determine a ball that contains (almost) all the points of one of the ${\cal P}_i$'s, and remove them from ${\rm Points}({\cal T})$ before the next call to the algorithm. In order to privately compute an estimate $\tpa_i$ of each average $\pa_i$ such that $\norm{\pa_i - \tpa_i}$ is proportional to the (minimal) radius of a ball that contains ${\cal P}_i$, one can execute the private average algorithm of \citet{NSV16}. It can be shown that with this process, we can achieve $(\varepsilon,\delta)$-differential privacy for $(\alpha,\beta)$-estimating the $k$ averages of ${\cal P}$, where $\alpha = O\paren{\frac{\sqrt{d}}{\varepsilon n} \log \paren{\frac{nd}{\beta}} \log\paren{\frac{1}{\delta}}}$. However, the downside of this approach is that \cite{NS17_clustering}'s algorithm is not simple, and does not exploits the special $k$-tuples structure of the database.\Enote{maybe also explain why it is not simple. E.g., that it uses LSH, RecConcave, and more ...}\ECnote{Uri mentioned polynomial super-linear dependence on $kd$ also. We need to make this paragraph concise and crisp. We also use averaging (in one of the approaches), we just have a different method of creating the subsets.} \ECnote{ Present our solution taking things from section 9 and hiding all the unnecessary. Yes to Pseudocode. Precise statement of properties. just say enough so that we can precisely state the results and explain the algorithm. No proofs but intutions. yes to pictures. } \section{Application to $k$-means clustering} \section{Application to separating mixtures of Gaussians} \section{Empirical results} \section{Conclusion} \subsection{tuple clustering}\label{sec:intro:kAver} \ECnote{ Previous: Estimating the Averages of Partitioned $k$-Tuples } Suppose that we are given a database ${\cal T}$ of size $n$, each element in ${\cal T}$ is an (unordered) $k$-tuple over ${\mathbb R}^d$, and we are promised that ${\cal T}$ can be partitioned by $k$ far balls in ${\mathbb R}^d$. Namely, there exist $k$ balls $B_1,\ldots,B_k$ over ${\mathbb R}^d$, each $B_i$ is centered at some point $\pc_i \in {\mathbb R}^d$ and has radius $r_i \geq 0$, and the following holds: (1) For every $i \neq j: \text{} \norm{\pc_i - \pc_j} > 16 \cdot \max\set{r_i,r_j}$ (i.e., the balls are very far from each other),\footnote{Throughout this work, we denote by $\norm{\cdot}$ the standard $\ell_2$ norm.} and (2) For every $i \in [k]$ and a $k$-tuple $X = \set{\px_1,\ldots,\px_k} \in {\cal T}:\text{ }\size{X \cap B_i} = 1$ (i.e., each tuple in ${\cal T}$ contains exactly one point in each ball).\Enote{add picture?} Given this promise, let ${\rm Points}({\cal T})$ be the multiset (of size $kn$) of all the points in all the $k$-tuples in ${\cal T}$, and consider the task of estimating the average $\pa_i$ of each cluster ${\cal P}_i = {\rm Points}({\cal T}) \cap B_i$. Specifically, we say that an algorithm $(\alpha,\beta)$-estimates the averages of partitioned points, if given such a database ${\cal T}$ as input, then with probability $1-\beta$, it outputs $\set{\tilde{\pa}_1,\ldots,\tilde{\pa}_k}$ such that, for each $i \in [k]$, there exists an average (call it $\pa_i$) with $\norm{\tpa_i - \pa_i} \leq \alpha \cdot r_i$. Without privacy, it is quite easy to $(0,0)$-estimate the $k$ averages. One can just pick an arbitrary $k$-tuple $\set{\px_1,\ldots,\px_k} \in {\cal T}$, construct the cluster ${\cal P}_1,\ldots,{\cal P}_k$ where ${\cal P}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \px_j}}$, and then compute the average $\pa_i$ of each ${\cal P}_i$. However, this algorithm is not differentially private. To be differentially private, any outcome should be obtained with approximately the same probability when we change a single $k$-tuple (possibly moving to a neighboring database that is not partitioned by far balls). In this algorithm, changing a single $k$-tuple may completely change the resulting partition (e.g., if the arbitrary tuple that we choose at the first step is exactly the different tuple), and hence, change the resulting averages. In order to privately estimate the $k$ averages, we first need to make some assumptions on the database ${\cal T}$, even for $k=1$ (which is just the task of estimating the average of all points). First, we need to assume some upper bound $\Lambda$ on the $\ell_2$ norm of the points in each tuple in ${\cal T}$. Second, since we are interested in an average estimation that is proportional to the (minimal) radius of a ball that contains them, we also need to assume some lower bound $r_{\min} > 0$ on the radii of the (minimal) $k$ balls that partition ${\cal T}$, or alternatively, assume that the points in ${\rm Points}({\cal T})$ belong to a finite grid \Enote{Ref?}\Hnote{From ``Second, ...'': I do not follow this, is it still related to $k=1$ ? if all the points are at exactly the same place then we can report this place, i think ? For $k>1$ maybe you can say that there is a reduction from finding an interior point, but we need to be careful} One way to privately estimate the $k$ averages is to use the minimal enclosing ball algorithm of \citet{NS17_clustering}. This algorithm is given $n$ points and a (large enough) parameter $t \leq n$, and privately outputs a ball of radius $O(r_{opt})$ that contains (almost) $t$ points, where $r_{opt}$ is the radius of the smallest ball that contains $t$ points. In our case, one can ignore the $k$-tuple structure and execute \cite{NS17_clustering}'s algorithm $k$ times on the database ${\rm Points}({\cal T})$. Each time it would privately determine a ball that contains (almost) all the points of one of the ${\cal P}_i$'s, and remove them from ${\rm Points}({\cal T})$ before the next call to the algorithm. In order to privately compute an estimation $\tpa_i$ of each average $\pa_i$ such that $\norm{\pa_i - \tpa_i}$ is proportional to the (minimal) radius of a ball that contains ${\cal P}_i$, one can execute the private average algorithm of \citet{NSV16}. It can be shown that with this process, we can achieve $(\varepsilon,\delta)$-differential privacy for $(\alpha,\beta)$-estimating the $k$ averages of ${\cal P}$, where $\alpha = O\paren{\frac{\sqrt{d}}{\varepsilon n} \log \paren{\frac{nd}{\beta}} \log\paren{\frac{1}{\delta}}}$. However, the downside of this approach is that \cite{NS17_clustering}'s algorithm is not simple, and does not exploits the special $k$-tuples structure of the database.\Enote{maybe also explain why it is not simple. E.g., that it uses LSH, RecConcave, and more ...} In this work we present a much more simpler and practical $(\varepsilon,\delta)$-differentially private algorithm that $(\alpha,\beta)$-estimates the averages of partitioned $k$-tuples, with essentially the same parameter $\alpha$. In order to understand the main idea of our algorithm, suppose we are given an $n$-size database ${\cal T}$ of $k$-tuples, and a set of far balls ${\cal B} = \set{B_1,\ldots,B_k}$ around the centers $\set{\pc_1,\ldots,\pc_k}$ (respectively), that ``almost'' partitions ${\cal T}$. By ``almost'' we mean that, there exists some $\ell \ll n$ such that, by removing $\ell$ tuples from ${\cal T}$, we obtain a database that is partitioned by $\set{B_1,\ldots,B_k}$. Throughout this work, we call it $\ell$-partitioning. Now consider the following process $\mathsf{EstimateAverages}({\cal T},{\cal B})$: (1) Partition ${\rm Points}({\cal T})$ into $k$ multisets ${\cal P}_1,\ldots,{\cal P}_k$, where each ${\cal P}_i$ consists of the points in ${\cal P}$ that $\pc_i$ is closest center to them, and (2) Compute a noisy average $\tpa_i$ of each ${\cal P}_i$ using \cite{NSV16}'s algorithm with privacy parameters $\varepsilon,\delta \in (0,1]$, and output the set $\set{\tpa_1,\ldots,\tpa_k}$. Our main observation is that, for any neighboring databases ${\cal T},{\cal T}'$, and any sets of far balls ${\cal B}$ and ${\cal B}'$ that $\ell$-partition ${\cal P}$ and ${\cal P}'$ (respectively), the distributions of the outputs $\mathsf{EstimateAverages}({\cal P},{\cal B})$ and $\mathsf{EstimateAverages}({\cal P}',{\cal B}')$ are $(O( k \ell \varepsilon), O(k \ell \delta))$-indistinguishable.\Enote{define ind} The intuition is that, since ${\cal T}$ and ${\cal T}'$ are neighboring, the partition $\set{{\cal T}_1,\ldots,{\cal T}_k}$ in $\mathsf{EstimateAverages}({\cal P},{\cal B})$ and $\set{{\cal T}_1',\ldots,{\cal T}_k'}$ in $\mathsf{EstimateAverages}({\cal P}',{\cal B}')$ must be almost the same (in fact, we show that there are at most $2\ell + 1$ tuples that the two partitions do not agree on). The first attempt for translating the above observation into a differentially private algorithm that estimates the $k$ averages of ${\cal T}$, is to fix some small $\ell$, compute (non-privately) a set of far balls ${\cal B} = \set{B_1,\ldots,B_k}$ that $\ell$-partitioned ${\cal T}$ (fail if such balls do not exist), and then output $\mathsf{EstimateAverages}({\cal P},{\cal B})$. The main problem is that differential privacy is a worst-case guarantee. If we execute the above process with two neighboring databases ${\cal T},{\cal T}'$ such that ${\cal T}$ is $\ell$-partitioned by far balls and ${\cal T}'$ is not $\ell$-partitioned by any far balls, then the execution over ${\cal T}'$ will fail, meaning that the output over ${\cal T}$ is very distinguishable from the output over ${\cal T}'$. In order the overcome the above obstacle, we present a simple and efficient algorithm $\mathsf{PrivateTestPartition}$ that privately tests whether the input database ${\cal T}$ is well partitioned or not. For pedagogical reasons, assume that $\mathsf{PrivateTestPartition}$ gets as input two different databases of $k$-tuples ${\cal P}$ and ${\cal Q}$ with the promise that ${\cal P} \cup {\cal Q}$ is partitioned by far balls (later, given a multiset ${\cal T}$, we apply $\mathsf{PrivateTestPartition}$ with ${\cal P} = {\cal Q} = {\cal T}$ and slightly pay a group privacy of size $2$). Roughly, given ${\cal P}$ and ${\cal Q}$ as input, $\mathsf{PrivateTestPartition}$ chooses a random $J=\tilde{O}\paren{1/\varepsilon}$-size sub-multiset ${\cal R} \subset {\cal P}$. For each tuple $X = \set{\px_1,\ldots,\px_k} \in {\cal R}$, it defines a set of far balls ${\cal B}_X$ around the centers $\px_1,\ldots,\px_k$, privately checks (by adding Laplace noise of magnitude $\tilde{O}(J/\varepsilon)$) if the value of $\ell_X = \min\set{\ell \colon {\cal Q}\text{ is }\ell\text{-partitioned by }{\cal B}_{\px}}$ does not exceed some (small) threshold (denote this decision bit by ${\rm pass}_X$), and then applies a private counting algorithm on all the $J$ decisions bits do decide whether the test succeed or failed. On success, it outputs one of the balls ${\cal B}_X$ that had ${\rm pass}_X = 1$ (if ${\rm pass}_X = 0$ for all $X \in {\cal R}$, it outputs empty balls). For proving utility, we note that when the test succeed, then with high probability there exists at least one $X \in {\cal R}$ with ${\rm pass}_X = 1$, yielding that with high probability, any choice of such $X$ results with balls $B_X$ that $\ell$-partitions ${\cal Q}$ with some small $\ell$. For proving that the test is private, consider two executions of $\mathsf{PrivateTestPartition}$ over neighboring databases $({\cal P},{\cal Q})$ and $({\cal P}',{\cal Q}')$. If ${\cal P} \neq {\cal P}'$ (and ${\cal Q} = {\cal Q}'$), then the privacy holds since at most one decision bit can be affected. If ${\cal Q} \neq {\cal Q}'$ (and ${\cal P} = {\cal P}'$), then each estimation of $\ell_X$ is $\varepsilon/J$-differentially private, and by basic composition, all of them together are $\varepsilon$-differentially private. Hence, the privacy of this case now holds by simple post-processing argument (we remark that, since ${\cal R}$ is just a small subset of ${\cal P}$, we actually reduce its value using sub-sampling argument, which is significant for practice). In summary, our algorithm $\mathsf{PrivatekAverages}$ on input ${\cal T}$, executes $\mathsf{PrivateTestPartition}$ with ${\cal P} = {\cal Q} = {\cal T}$ which outputs $({ Status},{\cal B})$. If ${ Status} = ``Success"$, it executes $\mathsf{EstimateAverages}({\cal T},{\cal B})$ and outputs the resulting $k$ average estimations $\set{\tpa_1,\ldots,\tpa_k}$. \subsection{Applications} The importance of Algorithm $\mathsf{PrivatekAverages}$ is that many classical clustering-based tasks can be privately solved by a reduction to the problem of estimating the averages of partitioned tuples. In this work, we chose to present two important use-cases: (1) Privately approximating the $k$-means under stability assumption, and (2) Privately learning the parameters of a mixture of well-separated Gaussians. \paragraph{$k$-Means Clustering} In $k$-means clustering, we are given a database ${\cal P}$ of $n$ points in ${\mathbb R}^d$, and the goal is to identify a set $C$ of $k$ centers in ${\mathbb R}^d$ that approximately minimizes ${\rm COST}_{{\cal P}}(C) = \sum_{\px \in {\cal P}} \min_{\pc \in C}\norm{\px - \pc}^2$. We denote the lowest possible cost as ${\rm OPT}_{k}({\cal P})$. Since the task of minimizing the $k$-means is NP-hard, the literature has focused on approximation algorithms, with the current (non-private) state-of-the-art achieving multiplicative error of $6.357$ \cite{ahmadian2019better}. Unlike in the non-private literature, it is known that every private algorithm for approximating the $k$-means cost must have an additive error (even computationally unbounded algorithms), which scales with the diameter of the input space. Hence, it is standard to assume an upper bound $\Lambda$ on the $\ell_2$ norm of all the input points ${\cal P}$. Typically (though not always), one aims to minimize the multiplicative error while keeping the additive error at most polylogarithmic in the size of the database. The current state-of-the-art construction \Enote{ .....} Now, suppose that we are given a database ${\cal P}$ and a (non-private) $k$-means approximation algorithm ${\cal A}$, such that the following stability property holds: When executing ${\cal A}$ on a (large enough) random subset of ${\cal P}$, then with high probability, the output $\pc_1,\ldots,\pc_k$ is very close to the optimal $k$-means $\pc_1^*,\ldots,\pc_k^*$ of ${\cal P}$. Then using this property, we present our private algorithm $\mathsf{PrivatekMeans}$ that easily approximate the $k$-means of ${\cal P}$. Roughly, Algorithm $\mathsf{PrivatekMeans}$ randomly partitions ${\cal P}$ into $T$ subsets (for large enough $T \ll n$), and execute ${\cal A}$ on each subset to obtain $k$ centers that are close to the optimal centers. Then, it collects all the $T$ $k$-tuples of centers and executes Algorithm $\mathsf{PrivatekAverages}$ over them. The privacy follows since, for any given partition, two neighboring databases differ by only one of the subsets, and therefore, the resulting $T$ databases of $k$-tuples differ by at most $1$ tuple. For utility, note that by the stability property, w.h.p. all the $T$ $k$-tuples are partitioned by small $k$ balls around the optimal centers $\pc_1^*,\ldots,\pc_k^*$. Therefore, when executing $\mathsf{PrivatekAverages}$, we expect to get $k$ centers $\tilde{\pc}_1,\ldots,\tilde{\pc}_k$ that are close to $\pc_1^*,\ldots,\pc_k^*$. We then show that by performing a single (noisy) Lloyd step that preserve privacy, the resulting $k$ centers well approximate the $k$-means cost. As a common concrete example of such ${\cal P}$ and ${\cal A}$ that satisfy the above stability property is when ${\cal A}$ is a good (non-private) approximation algorithm for $k$-means, and ${\cal P}$ is well-separated for $k$-means, a notion that was first introduced in \citet{OstrovskyRSS12}. Formally, ${\cal P}$ is called $\phi$-separated if ${\rm OPT}_{k}({\cal P}) \leq \phi^2 {\rm OPT}_{k-1}({\cal P})$. It turns out that if ${\cal P}$ is $\phi$-separated for $k$-means, and ${\cal A}$ is a $\omega$-approximation algorithm for $k$-means, where $\phi^2(1 + \omega)$ is sufficiently small, then ${\cal P}$ and ${\cal A}$ satisfy our required stability property, yielding that our algorithm $\mathsf{PrivatekMeans}$ succeed well over ${\cal P}$ using ${\cal A}$. Following the work of \citet{OstrovskyRSS12}, several other works have related other notions of input-stability to clustering \cite{awasthi2010stability,awasthi2012center,balcan2009approximate,bilu2012stable,kumar2010clustering}. In addition, several works gave differentially-private algorithms for approximating the minimal Wasserstein distance (\cite{Wasserstein1969}) of well-separated instances \cite{NRS07,wang2015differentially,huang2018optimal}, and in a recent work, \citet{ShechnerSS20} presented a differentially-private algorithm for approximating the $k$-means of such well-separated instances. The main result of \cite{ShechnerSS20} is a very simple transformation, called Private-Stable-$k$-Means, from any private $\omega$-approximation algorithm to a private $(1 + O(\phi^2))$-one, that works over $\phi$-separated database ${\cal P}$ with sufficiently small $\phi^2(1 + \omega)$. In addition, they presented Algorithm SampleAggregate-$k$-means that transform any (non-private) $k$-means approximation algorithm ${\cal A}$ into a private one, with very similar guarantees to our construction. Their algorithm also randomly partitions ${\cal P}$ into $T$ subsets (for large enough $T \ll n$), and executes ${\cal A}$ on each subset to obtain $k$ centers that are close to the optimal centers. But then, in order to privately estimating the averages of each cluster of the resulting partitioned multiset of $k$-tuples, their algorithm ignores the $k$-tuples structure and uses the (complicated) \cite{NS17_clustering}'s minimal enclosing ball algorithm for determine the clusters, while our algorithm uses Algorithm $\mathsf{PrivatekAverages}$ which is much more simpler and practical. \paragraph{Learning Mixtures of Gaussians} In the learning mixtures of Gaussians problem, we are given samples for a mixture ${\cal D}$ of $k$ Gaussians over ${\mathbb R}^d$. The mixture is specified by $k$ components $G_1,\ldots,G_k$, where each $G_i$ is selected with probability $\omega_i \in [0,1]$ and is distributed as a Gaussian with mean $\mu_i \in {\mathbb R}^d$ and a covariance matrix $\Sigma_i \in {\mathbb R}^{d \times d}$. The goal is to recover the parameters $\set{(\omega_i, \mu_i, \Sigma_i)}_{i=1}^k$ from the samples. That is, we would like to output a mixture $\hat{{\cal D}} = \set{(\hat{\omega}_i, \hat{\mu}_i, \hat{\Sigma}_i)}_{i=1}^k$ such that ${\cal D}$ and $\hat{{\cal D}}$ are close in total-variation distance (which we denote by ${\rm d}_{\rm TV}(\cdot)$). We say that an algorithm $(\alpha,\beta)$-learns a mixture ${\cal D}$ with sample complexity $n$, if given $n$ sample from ${\cal D}$, with probability $1-\beta$ it outputs $\hat{{\cal D}}$ such that ${\rm d}_{\rm TV}({\cal D},\hat{{\cal D}}) \leq \alpha$. \Enote{cite non-private works here? I guess that there are plenty } It turns out that in order to privately learn a mixture, even for $d = k=1$ (i.e., learn a single univariable Gaussian), we must assume a priori bounds $R, \sigma_{\min},\sigma_{\max}$ such that $\forall i:\text{}\norm{\mu_i} \leq R\text{ and } \sigma_{\min} \leq \norm{\Sigma_i} \leq \sigma_{\max}$ \cite{BS16,KV18} (where by $\norm{\cdot}$ we denote the standard $\ell_2$ norm of a matrix). There are various private algorithms that learns the parameters of a single Gaussian \cite{KV18,KLSU19,CWZ19,BS19,KSU20,BDKU20}. Recently, \cite{KSSU19} presented a private algorithm for learning mixtures of well-separated (and bounded) Gaussians. Specifically, under the separation assumption $\forall i \neq j: \text{ } \norm{\mu_i - \mu_j} \geq \Omega\paren{\sqrt{k \log(nk/\beta)} + \sqrt{\frac1{w_i} + \frac1{w_j}}}\cdot \max \set{\norm{\Sigma_i}^{1/2}, \norm{\Sigma_j}^{1/2}}$, they presented an $(\varepsilon,\delta)$-differentially private algorithm that $(\alpha,\beta)$-learns such a separated and $(R,\sigma_{\min},\sigma_{\max})$-bounded mixture of $k$ Gaussians with sample complexity $n = \paren{\frac{d^2}{\alpha^2 w_{\min}} + \frac{d^2}{\varepsilon \alpha w_{\min}} + \frac{{\rm poly}(k) d^{3/2}}{w_{\min} \varepsilon}} \cdot {\rm polylog}\paren{\frac{d k R \sigma_{\max}}{\alpha \beta \varepsilon \delta \sigma_{\min}}}$. We remark, however, that besides the result of \cite{BDKU20}, which is a practical algorithm for learning a single Gaussian, all the other results are primarily theoretical. \Enote{maybe here is the place to explain why the construction of \cite{KSSU19} is far from being practical} In this work, we present a simple and practical algorithm $\mathsf{PrivatekGMM}$ that privately $(\alpha,\beta)$-learns the parameters of an $(R,\sigma_{\min},\sigma_{\max})$-bounded mixture of $k$ Gaussians under a weaker separation assumption from the one made by \cite{KSSU19}. Roughly, Algorithm $\mathsf{PrivatekGMM}$ can use any non-private algorithm ${\cal A}$ that learns the means of a Gaussian mixture. Given such ${\cal A}$, it executes it $T$ times (for large enough $T$), each time with enough new samples for guaranteeing w.h.p. that the means estimations $\tilde{\mu}_1,\ldots,\tilde{\mu}_k$ of ${\cal A}$ will be close enough to the actual means $\mu_1,\ldots,\mu_k$ (specifically, we need that $\forall i:\text{ }\norm{\mu_i - \tilde{\mu}_i} < \frac1{16} \cdot \min_{j \neq i} \norm{\mu_i - \mu_j}$), and then it executes our algorithm $\mathsf{PrivatekAverages}$ on the resulting $T$-size database of all the $k$-tuples means estimations. Since w.h.p. all the $T$ $k$-tuples are partitioned by small balls around the actuals means $\mu_1,\ldots,\mu_k$, then for large enough $T$ (but much smaller than $n$), we are guaranteed to obtain $k$ avegares estimations $\tilde{\pa}_1,\ldots,\tilde{\pa}_k$ that are very close to the actual means. In the next step, Algorithm $\mathsf{PrivatekGMM}$ partitions a fresh set of $n$ samples according to $\tilde{\pa}_1,\ldots,\tilde{\pa}_k$, where each sample $\px$ belongs to the $i$'th set if $\pa_i$ is the closest point to it among $\tilde{\pa}_1,\ldots,\tilde{\pa}_k$. Using a standard projection argument, we show that if we assume a separation of the form $\forall i \neq j: \text{ } \norm{\mu_i - \mu_j} > 2\sqrt{2\log(\beta/n)} \cdot \max \set{\norm{\Sigma_i}^{1/2}, \norm{\Sigma_j}^{1/2}}$ (which is independent of the dimension $d$), then with probability $1-\beta$, the above partition perfectly classifiy the points correctly (i.e., two points belong to the same set iff they both were sampled from the same Gaussian). Finally, we apply a private algorithm ${\cal A}'$ for learning the parameters of each single Gaussian (e.g., \cite{KLSU19} or \cite{BDKU20}) in each of the $k$ sets in the partition. Overall, our algorithm $\mathsf{PrivatekGMM}$ wraps (using algorithm $\mathsf{PrivatekAverages}$) any given non-private algorithm ${\cal A}$ that learns a mixture of Gaussians, along with any given private algorithm ${\cal A}'$ that learns a single Gaussian, in order to learn the parameters of a mixture of separated (and bounded) Gaussians under a weaker separation assumption than the one used by \cite{KSSU19}. The construction uses only black-box accesses to ${\cal A}$ and ${\cal A}'$, and also can be parallelized very easily. Furthermore, we show that using an additional step of sub-sampling, our algorithm improves the sample complexity of \cite{KSSU19}. See \cref{sec:Gauss:comparison} for the full comparison. \Enote{add discussion why JL is not usefull when we apply it directly on the learning mixtures of Gaussians problem} \paragraph{Other Problems} \Enote{TBD} } \section{Missing Proofs}\label{sec:missing-proofs} \subsection{Proving \cref{prop:cost-of-sample-is-good}}\label{missing-proof:cost-of-sample-is-good} In this section we prove \cref{prop:cost-of-sample-is-good}, restated below \begin{proposition}[Restatement of \cref{prop:cost-of-sample-is-good}] \propCostOfSampleIsGood \end{proposition} In the following, fix values of $s$ and $\beta$, let $\xi = \xi(s,\beta)$ and $M = M(s,\beta)$. The following event and claims are with respect to the random process in \cref{prop:cost-of-sample-is-good}. \begin{claim}[Event $E$ \cite{ShechnerSS20}]\label{claim:E} Let $E$ be the event that for every $C \in B(0,\Lambda)^k$, we have that \begin{align*} \size{\frac{n}s \cdot {\rm COST}_{{\cal S}}(C) - {\rm COST}_{{\cal P}}(C)} \leq \sqrt{M \cdot {\rm COST}_{{\cal P}}(C)} := \Delta(C) \end{align*} Then it holds that $\pr{E} \geq 1-\beta$. \end{claim} We next prove some useful facts that holds when event $E$ occurs. \begin{claim}\label{claim:cost-tC} Conditioned on event $E$, it holds that \begin{align*} {\rm COST}_{{\cal P}}(\tilde{C}) \leq \omega\cdot {\rm OPT}_k({\cal P}) + \Delta(C^{*}_{{\cal P}}) + \Delta(\tilde{C}), \end{align*} letting $\tilde{C}$ be the set from \cref{prop:cost-of-sample-is-good}, and letting $C^{*}_{{\cal P}}$ be the optimal $k$-means of ${\cal P}$. \end{claim} \begin{proof} Let $C^{*}_{{\cal S}}$ be the optimal $k$-means of ${\cal S}$. By the assumption on the algorithm $\mathsf{A}$, the set $\tilde{C}$ satisfies ${\rm COST}_{{\cal S}}(\tilde{C}) \leq \omega \cdot {\rm OPT}_k({\cal S})$. The proof follows by the following calculation \begin{align*} {\rm COST}_{{\cal P}}(\tilde{C}) &\leq \frac{n}{s} \cdot {\rm COST}_{{\cal S}}(\tilde{C}) + \Delta(\tilde{C})\\ &\leq \omega\cdot \frac{n}{s} \cdot {\rm COST}_{{\cal S}}(C^{*}_{{\cal S}}) + \Delta(\tilde{C})\\ &\leq \omega\cdot \frac{n}{s} \cdot {\rm COST}_{{\cal S}}(C^{*}_{{\cal P}}) + \Delta(\tilde{C})\\ &\leq \omega \cdot \frac{n}{s} \cdot \paren{\frac{m}{n}\cdot {\rm COST}_{{\cal P}}(C^{*}_{{\cal P}}) + \frac{s}{n} \cdot \Delta(C^{*}_{{\cal P}})} + \Delta(\tilde{C})\\ &= \omega\cdot {\rm OPT}_k({\cal P}) + \Delta(C^{*}_{{\cal P}}) + \Delta(\tilde{C}), \end{align*} where the third inequality holds by event $E$, \end{proof} We now prove a corollary of \cref{claim:cost-tC}. \begin{corollary}\label{cor:cost-Ct:1} Conditioned on event $E$, it holds that \begin{align*} \Delta(\tilde{C}) \leq 2\paren{M + \sqrt{M \omega {\rm OPT}_k({\cal P})}} \end{align*} \end{corollary} \begin{proof} Let $x = \Delta(\tilde{C}) = \sqrt{M \cdot {\rm COST}_{{\cal P}}(\tilde{C})}$. By \cref{claim:cost-tC}, it holds that \begin{align*} \frac{x^2}{M} - x \leq \omega\cdot {\rm OPT}_k({\cal P}) + \sqrt{M \cdot {\rm OPT}_k({\cal P})}. \end{align*} Since $x \geq 0$, we conclude that \begin{align}\label{eq:bounding-x} x &\leq \frac12\cdot \paren{M + \sqrt{M^2 + 4M \omega {\rm OPT}_k({\cal P}) + 4M^{1.5} \sqrt{{\rm OPT}_k({\cal P})}}}\nonumber\\ &\leq M + \sqrt{M \omega {\rm OPT}_k({\cal P})} + M^{0.75} \cdot {\rm OPT}_k({\cal P})^{1/4}\\ &\leq 2\paren{M + \sqrt{M \omega {\rm OPT}_k({\cal P})}},\nonumber \end{align} where the second inequality holds by the fact that $\sqrt{a+b} \leq \sqrt{a} + \sqrt{b}$ for $a,b \geq 0$, and the last inequality holds since the third term in (\ref{eq:bounding-x}) is either smaller than the first term, or smaller than the second one (recall that $M \geq 1$). \end{proof} The proof of \cref{prop:cost-of-sample-is-good} now immediately follows by \cref{claim:cost-tC} and \cref{cor:cost-Ct:1}. \subsection{Proving \cref{prop:close-centers-have-similar-cost}}\label{missing-proof:close-centers-have-similar-cost} \begin{proposition}[Restatement of \cref{prop:close-centers-have-similar-cost}] \propCloseCentersHaveSimilarCost \end{proposition} \begin{proof} In the following, for $\px \in {\cal P}$ let $i_{\px} = \operatorname*{argmin}_{i}\set{\norm{\px - \pc_{i}}}$ (i.e., the index of the closest center to $\px$ in $C$), and let $j_{\px} = \operatorname*{argmin}_{j}\set{\norm{\px - \pc_{j}'}}$ (i.e., the index of the closest center to $\px$ in $C'$). It holds that \begin{align*} \sum_{i=1}^k {\rm OPT}_1({\cal P}_i) &\leq \sum_{i=1}^k \sum_{\px \in {\cal P}_i} \norm{\px - \pc_i}^2\\ &= \sum_{\px \in {\cal P}} \norm{\px - \pc_{j_{\px}}}^2\\ &= \sum_{\px \in {\cal P}} \norm{\px - \pc_{i_{\px}}}^2 + \sum_{\px \in {\cal P}} \paren{\norm{\px - \pc_{j_{\px}}}^2 - \norm{\px - \pc_{i_{\px}}}^2}\\ &= {\rm COST}_{{\cal P}}(C) + \sum_{\px \in {\cal P}} \paren{\norm{\px - \pc_{j_{\px}}}^2 - \norm{\px - \pc_{i_{\px}}}^2} \end{align*} In the following, fix $\px \in {\cal P}$. We now bound \begin{align*} \norm{\px - \pc_{j_{\px}}}^2-\norm{\px -\pc_{i_{\px}}}^2 = \left(\norm{\px - \pc_{j_{\px}}}-\norm{\px -\pc_{i_{\px}}}\right)\left(\norm{\px -\pc_{j_{\px}}}+\norm{\px -\pc_{i_{\px}}}\right) \end{align*} % First, since $\norm{\px - \pc_{j_{\px}}'} \leq \norm{\px - \pc_{i_{\px}}'} $ it holds that \begin{align}\label{eq:x-cjx} \norm{\px - \pc_{j_{\px}}} \leq \norm{\px - \pc_{j_{\px}}'} + \norm{\pc_{j_{\px}}' - \pc_{j_{\px}}} \leq \norm{\px - \pc_{i_{\px}}'} + \gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}} \end{align} Second, \begin{align*} \norm{\px - \pc_{i_{\px}}} \geq \norm{\px - \pc_{i_{\px}}'} - \norm{\pc_{i_{\px}}' - \pc_{i_{\px}}} \geq \norm{\px - \pc_{i_{\px}}'} - \gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}} \end{align*} Therefore \begin{align*} \norm{\px - \pc_{j_{\px}}} - \norm{\px - \pc_{i_{\px}}} \leq 2\gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}} \end{align*} Now, $\norm{\px -\pc_{i_{\px}}} \leq \norm{\px -\pc_{j_{\px}}}$ and therefore \begin{align*} \norm{\px -\pc_{j_{\px}}}+\norm{\px -\pc_{i_{\px}}} &\leq 2 \norm{\px -\pc_{j_{\px}}}\\ &\leq 2\norm{\px - \pc_{i_{\px}}'} + 2\gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}}\\ &\leq 2\paren{\norm{\px - \pc_{i_{\px}}} + \norm{\pc_{i_{\px}}' - \pc_{i_{\px}}}}+ 2\gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}}\\ &\leq 2\norm{\px - \pc_{i_{\px}}} + 4\gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}}, \end{align*} where the second inequality holds by \cref{eq:x-cjx}. We now like to bound $\norm{\pc_{i_{\px}} - \pc_{j_{\px}}}$ as a function of $\norm{\px - \pc_{i_{\px}}}$. We first bound $\norm{\pc_{i_{\px}} - \pc_{j_{\px}}}$ as a function of $\norm{\px - \pc_{i_{\px}}'}$. \begin{align}\label{eq:px-pci-lowbound-ym-2} 2\norm{\px - \pc_{i_{\px}}'} &\geq \norm{\px - \pc_{i_{\px}}'} + \norm{\px - \pc_{j_{\px}}'}\nonumber\\ &\geq \norm{\pc_{i_{\px}}' - \pc_{j_{\px}}'}\nonumber\\ &\geq \norm{\pc_{i_{\px}} - \pc_{j_{\px}}} - \norm{\pc_{i_{\px}} - \pc_{i_{\px}}'} - \norm{\pc_{j_{\px}} - \pc_{j_{\px}}'}\nonumber\\ &\geq (1-2\gamma) \norm{\pc_{i_{\px}} - \pc_{j_{\px}}}, \end{align} In addition \[ \norm{\px - \pc_{i_{\px}}'}\leq \norm{\px - \pc_{i_{\px}}} + \norm{\pc_{i_{\px}} - \pc_{i_{\px}}'} \leq \norm{\px - \pc_{i_{\px}}} + \gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}} \] Therefore, \[ 2\norm{\px - \pc_{i_{\px}}} \geq (1-4\gamma) \norm{\pc_{i_{\px}} - \pc_{j_{\px}}} \] We have that \begin{align*} \norm{\px - \pc_{j_{\px}}}^2-\norm{\px -\pc_{i_{\px}}}^2 &= \left(\norm{\px - \pc_{j_{\px}}}-\norm{\px -\pc_{i_{\px}}}\right)\left(\norm{\px -\pc_{j_{\px}}}+\norm{\px -\pc_{i_{\px}}}\right)\\ &\leq \left(2\gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}}\right)\left(2 \norm{\px - \pc_{i_{\px}}} +4\gamma \norm{\pc_{i_{\px}} - \pc_{j_{\px}}}\right)\\ &\leq \left(\frac{4\gamma }{1-4\gamma}\norm{\px - \pc_{i_{\px}}} \right)\left((2+\frac{8\gamma }{1-4\gamma}) \norm{\px - \pc_{i_{\px}}} \right)\\ &\leq 32\gamma \norm{\px - \pc_{i_{\px}}}^2, \end{align*} where the least inequality holds since $\gamma \leq 1/8$. Now we can get the bound on the summation: \begin{align*} \sum_{\px \in {\cal P}} \paren{\norm{\px - \pc_{j_{\px}}}^2 - \norm{\px - \pc_{i_{\px}}}^2} \leq \sum_{\px \in {\cal P}} 32\gamma \norm{\px - \pc_{i_{\px}}}^2 \leq 32\gamma {\rm COST}_{{\cal P}}(C) \end{align*} \end{proof} \subsection{Proving \cref{thm:kGauss-utility}}\label{missing-proof:thm:kGauss-utility} In this section we prove the utility guarantee of $\mathsf{PrivatekGMM}$. We first by proving the following proposition that states the following: Assume that $\pX \sim {\cal N}(\mu,\Sigma)$ with $\norm{\Sigma} = \sigma^2$, and let $\py,\pz \in {\mathbb R}^d$ such that (1) $\norm{\py - \mu}$ is ``large enough'' (larger than $\Omega\paren{\sigma \sqrt{\log(1/\beta)}}$ ) , and (2) $\norm{\pz - \mu}$ is ``small enough''. Then with probability $1-\beta$ (over $\pX$) it holds that $\norm{\pX - \pz} < \norm{\pX - \py}$. Note that such an argument is trivial when $\norm{\py - \mu}$ is at least $\Omega(\sigma \sqrt{d \log(1/\beta)})$, but using a standard projection argument, we can avoid the dependency in $d$. \begin{proposition}\label{prop:separation} Let $\pX \sim {\cal N}(\mu,\Sigma)$ where $\norm{\Sigma} = \sigma^2$, let $\py \in {\mathbb R}^d$ with $\norm{\py - \mu} \geq 2(1+\gamma)\sqrt{2\log\paren{1/\beta}} \cdot \sigma$ for some $\gamma > 0$, and let $\pz \in {\mathbb R}^d$ with $\norm{\pz - \mu} \leq \frac{\gamma}{3(1+\gamma)} \norm{\py - \mu}$. Then with probability $1-\beta$ (over the choice of $\pX$), it holds that $\norm{\pX - \pz} < \norm{\pX-\py}$. \end{proposition} \begin{proof} Assume w.l.o.g. that $\mu = \pt{0}$. Let $\pW = \pz + \frac{\iprod{\pX-\pz,\py-\pz}}{\norm{\py-\pz}^2} (\py-\pz)$ be the projection of $\pX$ onto the line between $\py$ and $\pz$. In the following we bound the probability that $\frac{\iprod{\pX-\pz,\py-\pz}}{\norm{\py-\pz}^2} < \frac12$, which implies that $\norm{\pW - \pz} < \norm{\pW-\py}$, and therefore, $\norm{\pX - \pz} < \norm{\pX-\py}$. Note that $\rm ip{\pX,\py-\pz}$ is distributed according to the (one dimensional) Gaussian ${\cal N}(\pt{0}, (\py-\pz)^T \Sigma (\py-\pz))$ and it holds that $(\py-\pz)^T \Sigma (\py -\pz) \leq \sigma^2 \norm{\py-\pz}$. Therefore, by \cref{fact:one-Gaus-concet} we obtain that with probability $1-\beta$ it holds that $\rm ip{\pX,\py-\pz} < \sigma \norm{\py-\pz} \sqrt{2 \log(1/\beta)}$, and in the following we continue with the analysis assuming that this occurs. The proposition now follows by the following calculation. \begin{align*} \frac{\iprod{\pX-\pz,\py-\pz}}{\norm{\py-\pz}^2} &= \frac{\rm ip{\pX,\py-\pz} - \rm ip{\pz,\py-\pz}}{\norm{\py-\pz}^2}\\ &< \frac{\sigma \norm{\py-\pz} \sqrt{2 \log(1/\beta)} + \norm{\pz} \norm{\py -\pz}}{\norm{\py-\pz}^2}\\ &\leq \frac{\sigma \sqrt{2 \log(1/\beta)}}{\paren{1 - \frac{\gamma}{3(1+\gamma)}} \norm{y}} + \frac{\frac{\gamma}{3(1+\gamma)}}{1 - \frac{\gamma}{3(1+\gamma)}}\\ &\leq \frac{1}{2(1+\gamma) \paren{1 - \frac{\gamma}{3(1+\gamma)}}} + \frac{\frac{\gamma}{3(1+\gamma)}}{1 - \frac{\gamma}{3(1+\gamma)}}\\ &= \frac{1 + \frac{2 \gamma}{3}}{2(1 + \gamma)\frac{3 + 2\gamma}{3(1+\gamma)}}\\ &= \frac12, \end{align*} where in the second inequality holds since $\norm{\py-\pz} \geq \norm{\py} - \norm{\pz} \geq \paren{1 - \frac{\gamma}{3(1+\gamma)}} \norm{y}$, and the third inequality holds by the assumption on $\norm{\py}$. \end{proof} In addition, we use the following fact. \begin{fact}\label{fact:dTV-of-mixtures} Let ${\cal D} = \sum_{i=1}^k w_i {\cal D}_i$ be a mixture of the $k$ distributions ${\cal D}_1, \ldots, {\cal D}_k$, and let ${\cal D}' = \sum_{i=1}^k w_i' {\cal D}_i'$ be a mixture of the $k$ distributions ${\cal D}_1', \ldots, {\cal D}_k'$. Assume that for every $i \in [k]$ it holds that ${\rm d}_{\rm TV}({\cal D}_i,{\cal D}_i') \leq \frac{\alpha}{2}$ and $\size{w_i - w_i'} \leq \frac{\alpha}{k}$. Then ${\rm d}_{\rm TV}({\cal D},{\cal D}) \leq \alpha$. \end{fact} We now ready to prove \cref{thm:kGauss-utility}, stated for convenient below. \begin{theorem}[Restatement of \cref{thm:kGauss-utility}] \thmKGaussUtility \end{theorem} \begin{proof} Let $E_1 = \bigwedge_{j \in [t], i \in [k]} E_1^{t,i}$ where $E_1^{j,i}$ is the event that the $s$-size set ${\cal S}_j$ in Step~\ref{step:sample-gaus} of $\mathsf{GenEmpiricalMeans}$ contains at least $\frac{w_i s}{2}$ samples from the $i$'th Gaussian. Note that for every $j \in [t]$ and $i \in [k]$, it holds that \begin{align*} \pr{E_1^{j,i}} &= \pr{{\rm Bin}(s,w_i) \geq \frac{s w_i}{2}}\\ &\geq 1 - \pr{{\rm Bin}(s,w_{\min}) < \frac{s w_{\min}}{2}}\\ &\geq 1 - e^{-\frac{w_{\min} s}{4}} \end{align*} where the last inequality holds by \cref{fact:binom_concentration}. Therefore, we obtain that $\pr{E_1^{j,i}} \geq 1 - \frac{\beta}{8 k t}$ whenever $s \geq \frac{4}{w_{\min}} \log\paren{8 k t/\beta}$, which holds by the assumption on $s$. By the union bound, we deduce that \begin{align}\label{eq:E1} \pr{E_1} \geq 1 - \beta/8 \end{align} In the following, assume that event $E_1$ occurs. For $j \in [t]$ and $i \in [k]$ let $\hat{{\cal S}}_j^i$ be all the points in ${\cal S}_j$ that have been drawn from the $i$'th Gaussian ${\cal N}(\mu_{i},\Sigma_{i})$, and let $\hat{\mu}_{j,i} = {\rm Avg}\paren{\hat{{\cal S}}_j^i}$. Let $E_2 = \bigwedge_{j \in [t], i \in [k]} E_2^{j,i}$, where $E_2^{j,i}$ is the event that $\norm{\hat{\mu}_{j,i} - \mu_i} \leq \frac{\gamma h}{16} \cdot \sigma_{i}$. Since $\hat{\mu}_{j,i}$ is the average of at least $\frac{w_{i} s}{2}$ samples from the Gaussian ${\cal N}(\mu_i,\Sigma_i)$, we obtain by \cref{fact:gaus-avg} that with probability $1 - \frac{\beta}{8 k t}$ it holds that \begin{align}\label{eq:hmu_i-to-mu_i} \norm{\hat{\mu}_{j,i} - \mu_i} \leq \frac{\sqrt{2d} + 2\sqrt{\log \paren{\frac{8 k t}{\beta}}}}{\sqrt{w_i s}} \cdot \sigma_i \leq \frac{(1+\gamma) h}{\Delta} \cdot \sigma_i, \end{align} where the last inequality holds by the assumption on $s$ (by the second term in the maximum). Therefore, event $E_2^{j,i}$ occurs with probability at least $1 - \frac{\beta}{8 k t}$, and we conclude by the union bound that \begin{align}\label{eq:E2} \pr{E_2 \mid E_1} \geq 1 - \beta/8 \end{align} Let $E_3 = \bigwedge_{j=1}^t E_3^j$, where $E_3^j$ is the event that the resulting labeling function $L_j$ in Step~\ref{step:labeling} of the $j$'th iteration in $\mathsf{GenEmpiricalMeans}$ satisfies: \begin{align*} \forall \px,\px' \in {\cal S}_j:\quad \px,\px' \text{ were drawn from the same Gaussian } \iff L_j(\px) = L_j(\px'). \end{align*} Since $\mathsf{A}$ is a $(s,\frac{\beta}{8 t})$-labeling algorithm for ${\cal D}$, it holds that $\pr{E_3^j} \geq 1 - \frac{\beta}{8 t}$ for every $j \in [t]$, and we deduce by the union bound that \begin{align}\label{eq:E3} \pr{E_3} \geq 1 - \beta/8 \end{align} In the rest of the analysis we assume that event $E_1 \land E_2 \land E_3$ occurs. This means that for every $j \in [t]$ there exists a permutation $\pi_j$ over $[k]$ such that for each $i \in [k]$, the set of all points in ${\cal S}_j$ that have been drawn from the $i$'th Gaussian (which we denoted by ${\cal S}_j^i$) equals to $\set{\px \in {\cal S}_j \colon L_j(\px) = \pi_j(i)}$, and assume without loss of generality that for all $j \in [t]$, $\pi_j$ is the identity (i.e., $\pi_j(i) = i$). Therefore, for all $j \in [t]$ and $i \in [k]$ it holds that $\hat{\mu}_{j,i} = \bar{\mu}_{j,i}$, where $\bar{\mu}_{j,i}$ is the empirical mean from Step~\ref{step:compute-emp-mean}. Namely, we obtained that \begin{align}\label{eq:bar_mu-vs-mu} \forall j \in [t], i \in [k]: \quad \norm{\bar{\mu}_{j,i} - \mu_i} \leq \frac{(1+\gamma) h}{\Delta} \cdot \sigma_{i}, \end{align} and in particular, it holds that \begin{align}\label{eq:bar_mu-le-Lambda} \forall j \in [t], i \in [k]: \quad \norm{\bar{\mu}_{j,i}} \leq \norm{\mu_{j,i}} + \frac{(1+\gamma) h}{\Delta} \cdot \sigma_{i} \leq \Lambda \end{align} Therefore, we deduce that ${\cal T}$ from Step~\ref{step:kAveragesOnM} of $\mathsf{PrivatekGMM}$ is contained in $(B(\pt{0},\Lambda)^k)^*$, and is partitioned by the $\Delta$-far balls ${\cal B} = \set{B_i(\mu_i, r_i = \frac{(1+\gamma) h}{\Delta} \cdot \sigma_i )}_{i=1}^k$ (\cref{def:sep-balls}), where ${\rm Partition}({\cal T})$ is exactly $\set{{\cal P}_1 =\set{ \bar{\mu}_{j,1}}_{j=1}^t,\ldots,{\cal P}_k = \set{\bar{\mu}_{j,k}}_{j=1}^t}$ (note that the balls are indeed $\Delta$-far by the separation assumption that $\norm{\mu_i - \mu_j} \geq (1+\gamma) h \max\set{\sigma_i,\sigma_j}$). Therefore, since $\mathsf{B}$ is an $(t,\text{ }\alpha=1,\text{ }r_{\min}=\frac{(1+\gamma) h}{\Delta}\cdot \sigma_{\min},\text{ }\beta/8, \text{ }\Delta,\text{ }\Lambda=R + \frac{(1+\gamma) h}{\Delta}\cdot \sigma_{\max})$-averages-estimator, we obtain that the output $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$ of $\mathsf{B}({\cal T})$ in Step~\ref{step:kAveragesOnM} satisfy w.p. $1-\beta/8$ that: \begin{align}\label{eq:a-to-avg} \forall i \in [k]: \quad \norm{\hpa_i - {\rm Avg}\paren{{\cal P}_i}} \leq \max\set{r_i,r_{\min}} \leq \frac{(1+\gamma)h}{\Delta}\cdot \sigma_i \end{align} In the following, we denote by $E_4$ the event that \cref{eq:a-to-avg} occurs, where recall that we proved that \begin{align} \pr{E_4 \mid E_1 \land E_2 \land E_3} \geq 1 - \beta/8 \end{align} In the following, we also assume that event $E_4$ occurs. Recall that by \cref{eq:bar_mu-vs-mu}, for each $j \in [t]$ and $i \in [k]$ it holds that \begin{align}\label{eq:avg-to-mu_i} \norm{{\rm Avg}\paren{{\cal P}_i} - \mu_i} \leq \frac{(1+\gamma)h}{\Delta} \cdot \sigma_i, \end{align} and we deduce by \cref{eq:a-to-avg,eq:avg-to-mu_i} that for all $i \in [k]$ it holds that \begin{align}\label{eq:hpa_i-to-mu_i} \norm{\hpa_i - \mu_i} \leq \frac{2(1+\gamma)h}{\Delta} \cdot \sigma_i. \end{align} Therefore, for all $i \neq j$ it holds that \begin{align}\label{eq:hpa_i-to-mu_j} \norm{\hpa_j - \mu_i} \geq \norm{\mu_i - \mu_j} - \norm{\hpa_j - \mu_j} &\geq \paren{1-2/\Delta} (1+\gamma)h \cdot \max\set{\sigma_i,\sigma_j}\\ &\geq (1+\gamma/2)h \cdot \max\set{\sigma_i,\sigma_j}\nonumber \end{align} where the second inequality holds by the separation assumption along with \cref{eq:avg-to-mu_i}, and the last one holds by the choice of $\Delta$. Hence, we deduce from \cref{eq:hpa_i-to-mu_i,eq:hpa_i-to-mu_j} that for each $i \neq j$ it holds that \begin{align}\label{eq:hpa_i-to-mu_i-sec} \norm{\hpa_i - \mu_i} \leq \frac{2}{\Delta - 2} \cdot \norm{\hpa_j - \mu_i} = \frac{\gamma/2}{3(1+\gamma/2)}\cdot \norm{\hpa_j - \mu_i}, \end{align} where the last inequality holds since recall that $\Delta = 8 + 12/\gamma$. Since $h \geq 2 \sqrt{2 \log\paren{1/\beta'}}$ for $\beta' = \frac{\beta}{8n}$, then by \cref{prop:separation} (when setting $\py = \hpa_j$ and $\pz = \hpa_i$) along with \cref{eq:hpa_i-to-mu_j,eq:hpa_i-to-mu_i-sec}, for every $i \neq j$, when sampling a point $\px$ from the $i$'th Gaussian ${\cal N}(\mu_i,\sigma_i)$, then with probability $1 - \frac{\beta}{8n}$ it holds that $\norm{\px - \hpa_i} < \norm{\px - \hpa_j}$. Therefore, let $E_5$ be the event that for all $i \in [k]$ and all $\px \in {\cal P}''$ that have been sampled from the $i$'th Gaussian ${\cal N}(\mu_i,\Sigma_i)$, it holds that $\hpa_i$ is the closest point to each of them among $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$. Then by the union bound it holds that \begin{align}\label{eq:E_5} \pr{E_5 \mid E_1 \land E_2 \land E_3 \land E_4} \geq 1 - \beta/8 \end{align} In the following we also assume that event $E_5$ occurs. Let $E_6 = \bigwedge_{i \in [k]} E_6^{i}$ where $E_6^{i}$ is the event that ${\cal P}''$ contains at least $\frac{w_i n}{2}$ samples from the $i$'th Gaussian (namely, $\size{{\cal P}''_i} \geq \frac{w_i n}{4}$). Similar calculation to bounding $\pr{E_1}$, it holds that \begin{align}\label{eq:E_6} \pr{E_6 \mid E_1 \land \ldots \land E_5} \geq 1 - \beta/8 \end{align} provided that $n \geq \frac{4}{w_{\min}} \log\paren{8 k/\beta}$, which holds by the assumption on $n$. In the following we assume that event $E_6$ occurs, and let $E_7 = \land_{i=1}^k E_7^i$, where $E_7^i$ is the event that the output $(\hat{\mu}_i, \hat{\Sigma}_i)$ of the private algorithm $\mathsf{A}'$ in Step~\ref{step:priv-single-Gauss-est} of the $i$'th iteration satisfies ${\rm d}_{\rm TV}({\cal N}(\mu_i,\Sigma_i), {\cal N}(\hat{\mu}_i, \hat{\Sigma}_i)) \leq \eta/2$. By the assumption on algorithm $\mathsf{A}'$, we obtain that $\pr{E_7^i} \geq 1 - \frac{\beta}{16k}$ whenever $\size{{\cal P}''_i} \geq \upsilon$, which holds w.p. $1-\frac{\beta}{16}$ when $n \geq \frac{2\upsilon + \log(16k/\beta)}{w_i}$ (follows by \cref{fact:binom_concentration} for ${\rm Bin}(n,w_i)$ and $t = \sqrt{w_i n \log(16k/\beta)}$). Since $n \geq \frac{2\upsilon+ \log(16k/\beta)}{w_{\min}}$ by assumption, we obtain by the union bound that \begin{align}\label{eq:E_7} \pr{E_7 \mid E_1 \land \ldots \land E_6} \geq 1 - \beta/8. \end{align} In the following, for $i \in [k]$ let $L_i$ be the value of the Laplace noise in Step~\ref{step:Lap} of the $i$'th iteration, let $E_8^i$ be the event that $\size{L_i} \leq \frac2{\varepsilon} \log\paren{16 k/\beta}$, and let $E_8 = \land_{i=1}^k E_8^i$. By \cref{fact:laplace-concent}, for any fixing of $i \in [k]$ it holds that $\pr{E_8^i} \geq 1 - \frac{\beta}{8 k}$, and therefore, by the union bound it holds that \begin{align}\label{eq:E_8} \pr{E_8} \geq 1 - \beta/8. \end{align} In the following we also assume that $E_8$ occurs. It is left to show that when event $E_1 \land \ldots \land E_8$ occurs, then for every $i \in [k]$ it holds that \begin{align}\label{eq:hw_i-w_i} \forall i \in [k]: \quad \size{\hat{w}_i - w_i} \leq \eta/k. \end{align} Indeed, given \cref{eq:hw_i-w_i} and event $E_7$, we deduce by \cref{fact:dTV-of-mixtures} that ${\rm d}_{\rm TV}({\cal D},\hat{{\cal D}}) \leq \eta$, which holds with probability at least $\pr{E_1 \land \ldots \land E_8} \geq 1-\beta$ (holds by \cref{eq:E1} to \cref{eq:E_8}). We now prove that \cref{eq:hw_i-w_i} holds when $E_1 \land \ldots \land E_8$ occurs. Fix $i \in [k]$, let $L = \sum_{j=1}^k L_j$, and compute \begin{align*} \size{\hat{w}_i - w_i} &= \size{\frac{\hat{n}_i}{\hat{n}} - \frac{n_i}{n}} = \size{\frac{n_i + L_i}{n + L} - \frac{n_i}{n}}\\ &= \size{\frac{n L_i - n_i L}{n(n+L)}} = \size{\frac{(n-n_i)L_i - n_i \sum_{j \neq i} L_j}{n(n+L)}}\\ &\leq \frac{\frac{2k}{\varepsilon} \log\paren{8 k/\beta}}{n - \frac{2k}{\varepsilon} \log\paren{8 k/\beta}}\\ &\leq \eta/k, \end{align*} where the first inequality holds by event $E_8$, and the last one holds whenever $n \geq \frac{4 k^2}{\varepsilon \eta} \cdot \log\paren{8 k/\beta}$, which holds by the assumption on $n$. \end{proof} \section{Mixture of Gaussians}\label{sec:mixture-of-gaus} In this section we present our second application of $k$-tuple clustering, which is an $(\varepsilon,\delta)$-differentially private algorithm $\mathsf{PrivatekGMM}$ for learning a mixture of well separated and bounded $k$ Gaussians. We first start with relevant preliminaries for this section. \subsection{Preliminaries} The total variation distance between two distributions $P$ and $Q$ over a universe ${\cal U}$ is defined by ${\rm d}_{\rm TV}(P,Q) = \sup_{{\cal S} \subseteq {\cal U}} \size{P({\cal S}) - Q({\cal S})}$. Given a matrix $A = (a_{i,j})_{i,j \in [d]} \in {\mathbb R}^{d \times d}$, we let $\norm{A} = \sup_{\norm{\px} = 1} \norm{A \px}$ be its $\ell_2$ norm. \subsubsection{Gaussians} Let ${\cal N}(0,1)$ be the standard Gaussian distribution over ${\mathbb R}$ with probability density function $p(z) = \frac1{\sqrt{2\pi}} e^{-\frac{z^2}2}$. In ${\mathbb R}^d$, let ${\cal N}(\pt{0},{\mathbb I}_{d \times d})$ be the standard multivariate Gaussian distribution. That is, if $\pZ \sim {\cal N}(\pt{0},{\mathbb I}_{d \times d})$ then $\pZ = (Z_1,\ldots,Z_d)$ where $Z_1,\ldots,Z_d$ are i.i.d. according to $N(0,1)$. Other Gaussian distributions over ${\mathbb R}^d$ arise by applying (invertible) linear maps on ${\cal N}(\pt{0},{\mathbb I}_{d \times d})$. That is, the distribution $\pX \sim {\cal N}(\mathbf{\mu}, \Sigma = AA^T)$ for $\mu \in {\mathbb R}^d$ and (invertible) $A \in {\mathbb R}^{d \times d}$ is defined by $\pX = A \pZ + \mathbf{\mu}$, where $\pZ \sim N(\pt{0},{\mathbb I}_{d \times d})$, and it holds that $\ex{\pX} = \mu$ and ${\rm Cov}(\pX) = \paren{{\rm Cov}(X_i,X_j)}_{i,j}$ (the covariance matrix) equals to $\Sigma$. The contours of equal density are ellipsoids around $\mu$: $\set{\px \in {\mathbb R}^d \colon (\px - \mu)^T \Sigma^{-1}(\px - \mu) = r^2}$. We let ${\cal G}(d)$ be the family of all $d$-dimensional Gaussian --- that is, the set of all distribution ${\cal N}(\mu,\Sigma)$ where $\mu \in {\mathbb R}^d$ and $\Sigma$ is a $d \times d$ positive semidefinite (PSD) matrix. \begin{definition}[Bounded Gaussian]\label{def:bounded-gaus} For $R,\sigma_{\max},\sigma_{\min} > 0$, a Gaussian $\pG = {\cal N}(\mu,\Sigma) \in {\cal G}(d)$ is $(R,\sigma_{\max},\sigma_{\min})$-bounded if $\norm{\mu} \leq R$ and $\sigma_{\min}^2 \leq \norm{\Sigma} \leq \sigma_{\max}^2$. \end{definition} We next define the properties of a general algorithm that learns the parameters of a (single) bounded Gaussian. \begin{definition}[Learner for Bounded Gaussians]\label{def:LearnAlgSingleGaus} Let $\mathsf{A}$ be an algorithm that gets as input a database ${\cal P} \in ({\mathbb R}^d)^*$ and outputs $(\hat{\mu},\hat{\Sigma})$. We say that $\mathsf{A}$ is an $(\upsilon,\eta,\beta)$-learner for $(R,\sigma_{\max},\sigma_{\min})$-bounded Gaussians, if for any such bounded Gaussian ${\cal N}(\mu,\Sigma)$, algorithm $\mathsf{A}$ given $\upsilon$ i.i.d.\ samples from it as input, outputs w.p. $1-\beta$ a pair $(\hat{\mu},\hat{\Sigma})$ with ${\rm d}_{\rm TV}({\cal N}(\mu,\Sigma), {\cal N}(\hat{\mu},\hat{\Sigma})) \leq \eta$. \end{definition} \remove{ \begin{definition}[Private Algorithm for Learning a Bounded Gaussian]\label{def:privLearnAlgSingleGaus} Let $\mathsf{A}$ be an algorithm that gets as input a database ${\cal P} \in ({\mathbb R}^d)^*$ and parameters $d, \varepsilon,\delta,\eta,\beta,R,\sigma_{\max},\sigma_{\min}$, and outputs $(\hat{\mu},\hat{\Sigma})$. Let $s = s(d, \varepsilon,\delta,\eta,\beta,R,\sigma_{\max},\sigma_{\min})$ be a function. We say that $\mathsf{A}$ is a \textbf{private algorithm for learning a bounded Gaussian with sample complexity $\upsilon = \upsilon(d, \varepsilon,\delta,\eta,\beta,R,\sigma_{\max},\sigma_{\min})$} if given the above parameters, $\mathsf{A}$ is an $(\varepsilon,\delta)$-differentially private algorithm that satisfy the following utility guarantee: If ${\cal N}(\mu,\Sigma)$ is a $(R,\sigma_{\max},\sigma_{\min})$-bounded Gaussian, and ${\cal P}$ consists of at least $\upsilon$ i.i.d.\ samples from ${\cal N}(\mu,\Sigma)$, then with probability at least $1-\beta$ it holds that ${\rm d}_{\rm TV}({\cal N}(\mu,\Sigma), {\cal N}(\hat{\mu},\hat{\Sigma})) \leq \eta$. \end{definition} } In our construction, we would like to use a \emph{differentially private} algorithm that learns the parameters of single (bounded) Gaussians. The best known examples for such algorithms are the constructions of \cite{KLSU19} and \cite{BDKU20} in the \emph{zero Concentrated DP} model (zCDP \cite{BS16}). For instance, the algorithm of \cite{KLSU19} is $\frac{\varepsilon^2}2$-zCDP $(\upsilon,\eta,\beta)$-learner for $(R,\sigma_{\max},\sigma_{\min})$-bounded Gaussians, for $\upsilon = \tilde{O}\paren{\paren{\frac{d^2}{\eta^2} + \frac{d^2}{\varepsilon \eta} + \frac{d^{3/2} \sqrt{\log \paren{\frac{\sigma_{\max}}{\sigma_{\min}}}} + \sqrt{d \log R}}{\varepsilon}}\cdot \log(1/\beta)}$. We first remark that $\varepsilon$-DP implies $\frac{\varepsilon^2}{2}$-zCDP, and the latter implies $(\varepsilon\sqrt{\log(1/\delta)},\delta)$ for every $\delta > 0$. We also remark that without privacy, the required sample complexity is $\Theta\paren{\frac{d^2 \log(1/\beta)}{\eta^2}}$, which means that privacy comes almost for free unless $\frac1{\varepsilon}, \frac{\sigma_{\max}}{\sigma_{\min}}$ or $R$ are quite large. \subsubsection{Gaussian Mixtures} The class of Gaussian $k$-mixtures in ${\mathbb R}^d$ is \begin{align*} {\cal G}(d,k) := \set{\sum_{i=1}^k w_i \pG_i \colon \pG_1,\ldots,\pG_k \in {\cal G}(d), w_1,\ldots,w_k > 0, \sum_{i=1}^k w_i = 1} \end{align*} A Gaussian mixture can be specified by a set of $k$ triplets: $\set{(\mu_1,\Sigma_1,w_1), \ldots, (\mu_k,\Sigma_k,w_k)}$, where each triplet represents the mean, covariance matrix, and mixing weight of one of its components. \begin{definition}[Bounded Mixture of Gaussians] For $R,\sigma_{\max},\sigma_{\min},w_{\min} > 0$, a Gaussian mixture ${\cal D} = \set{(\mu_1,\Sigma_1,w_1), \ldots, (\mu_k,\Sigma_k,w_k)} \in {\cal G}(d,k)$ is $(R,\sigma_{\max},\sigma_{\min},w_{\min})$-bounded if for all $i \in [k]$, the Gaussian ${\cal N}(\mu_i,\Sigma_i)$ is $(R,\sigma_{\max},\sigma_{\min})$-bounded and $w_i \geq w_{\min}$. \end{definition} \begin{definition}[Separated Mixture of Gaussians] Let ${\cal D} = \set{(\mu_1,\Sigma_1,w_1), \ldots, (\mu_k,\Sigma_k,w_k)}$ be a mixture of $k$ Gaussians over ${\mathbb R}^d$, for $i \in [k]$ let $\sigma_i^2 = \norm{\Sigma_i}$, and let $h > 0$. We say that ${\cal D}$ is $h$-separated if \begin{align*} \forall 1 \leq i < j \leq k: \text{ }\norm{\mu_i-\mu_j} \geq h \cdot \max\set{\sigma_i,\sigma_j}. \end{align*} \end{definition} We next define a labeling algorithm for a mixture ${\cal D}$. \begin{definition}[Labeling Algorithm for a Mixture of Gaussians]\label{def:LabelingAlg} Let $s,k \in {\mathbb N}$, $\beta \in (0,1)$ and let ${\cal D} = \set{(\mu_1,\Sigma_1,w_1), \ldots, (\mu_k,\Sigma_k,w_k)}$ be a mixture of $k$ Gaussians. We say that an Algorithm $\mathsf{A}$ is an \textbf{$(s,\beta)$-labeling algorithm for the mixture ${\cal D}$} if with probability $1-\beta$, when sampling a database ${\cal P}$ of $s$ i.i.d.\ samples from ${\cal D}$, algorithm $\mathsf{A}$ on inputs ${\cal P},k$, outputs a labeling function $L \colon {\cal P} \rightarrow [k]$ such that for all $\px, \px' \in {\cal P}$: $\quad L(\px) = L(\px')$ $\iff$ $\px$ and $\px'$ were drawn from the same Gaussian. \end{definition} There are various examples of non-private algorithms that learns the parameters of mixtures of Gaussian under different separations assumptions, and most of them can be easily converted into a labeling algorithm. For instance, \cite{DS00,AK01} showed how to learn mixtures with separation that is only proportional to $d^{1/4}$. Moreover, there is a wide line of works that show how to handle mixtures with separation that is independent of $d$: Separation that is proportional to $\sqrt{k}$ \cite{AM05}, $k^{1/4}$ \cite{VW04}, $k^{\varepsilon}$ \cite{HSJ18,KPSJS18,diakonikolas18}, or even $\sqrt{\log k}$ \cite{RV17}. In \cref{sec:GausAlg} we show that our algorithm can transform each such non-private algorithm into a private one, as long as we are given $n$ points from a mixture that is at least $\tilde{\Omega}(\log n)-$separated. \subsubsection{Concentration Bounds} \begin{fact}[One-dimensional Gaussian]\label{fact:one-Gaus-concet} Let $\pX \sim {\cal N}(0,\sigma^2)$. Then for any $\beta > 0$ it holds that \begin{align*} \pr{\pX \geq \sigma \sqrt{2 \log(1/\beta)}} \leq \beta. \end{align*} \end{fact} \begin{fact}[follows by the Hanson-Wright inequality \cite{HV71}]\label{fact:gaus-concent-new} If $\pX \sim {\cal N}(\mu,\Sigma)$ then with probability at least $1-\beta$ it holds that \begin{align*} \norm{\pX - \mu} \leq \paren{\sqrt{d} + \sqrt{2 \log(1/\beta)}} \cdot \sqrt{\norm{\Sigma}}. \end{align*} \end{fact} The following fact is an immediate corollary of \cref{fact:gaus-concent-new}. \begin{fact}\label{fact:gaus-avg} Let $X_1,\ldots,X_m$ be i.i.d. random variables distributed according to a $d$-dimensional Gaussian ${\cal N}(\mu,\Sigma)$, and let $\sigma^2 = \norm{\Sigma}$. Then with $1-\beta$ it holds that \begin{align*} \norm{{\rm Avg}(X_1,\ldots,X_m) - \mu} \leq \frac{\sqrt{d} + \sqrt{2 \log (1/\beta)}}{\sqrt{m}} \cdot \sigma, \end{align*} \end{fact} \begin{proof} Follows by \cref{fact:gaus-concent-new} since ${\rm Avg}(X_1,\ldots,X_m)$ is distributed according to ${\cal N}(\mu,\frac1{m}\cdot \Sigma)$. \end{proof} \subsection{Algorithm $\mathsf{PrivatekGMM}$}\label{sec:GausAlg} In this section we describe our algorithm $\mathsf{PrivatekGMM}$ (\cref{alg:kGaus}) that privately learns a mixture of separated and bounded $k$ Gaussians ${\cal D} = \set{(\mu_1,\Sigma_1,w_1), \ldots, (\mu_k,\Sigma_k,w_k)}$. \begin{algorithm}[$\mathsf{GenEmpiricalMeans}$]\label{alg:genBalancedSamples} \item Input: A database ${\cal P}' = \set{\px_1,\ldots,\px_{n}}$ and parameters $k, s,t \in {\mathbb N}$, where $n \geq st$. \item Oracle: a (non-private) labeling algorithm $\mathsf{A}$ for a mixture of Gaussians. \item Operation:~ \begin{enumerate} \item For each $j \in [t]$: \begin{enumerate} \item Let ${\cal S}_j = \set{\px_{(j-1) s + 1},\ldots,\px_{j s}}$.\label{step:sample-gaus} \item Execute $\mathsf{A}$ on inputs $\tilde{{\cal P}} = {\cal S}_j, \tilde{k} =k$, and let $L_j \colon {\cal S}_j \rightarrow [k]$ be the resulting labeling function.\label{step:labeling} \item For each $i \in [k]:$ \begin{itemize} \item Compute $\bar{\mu}_{j,i} = {\rm Avg}\paren{\set{\px \in {\cal S}_j \colon L_j(\px) = i}}$.\label{step:compute-emp-mean} \end{itemize} \item Set $M_j = \set{\bar{\mu}_{j,1}, \ldots,\bar{\mu}_{j,k}} \in ({\mathbb R}^d)^k$.\label{step:balanced-samples} \end{enumerate} \item Output ${\cal T} = \set{M_1, \ldots, M_t} \in (({\mathbb R}^d)^k)^t$.\label{step:new-multisets-gaus} \end{enumerate} \end{algorithm} \begin{algorithm}[$\mathsf{PrivatekGMM}$]\label{alg:kGaus} \item Input: A database ${\cal P} = \set{\px_1,\ldots,\px_{2n}} \in \paren{{\mathbb R}^d}^{2n}$, parameters $k,s,t \in {\mathbb N}$ s.t. $n \geq s t$,, and privacy parameter $\varepsilon,\delta > 0$. \item Oracles: A (non-private) labeling algorithm $\mathsf{A}$, an $(\varepsilon/4,\delta/2)$-DP learner $\mathsf{A}'$ for (single) Gaussians, and an $(\varepsilon,\delta)$-DP $k$-tuple clustering algorithm $\mathsf{B}$. \item Operation:~ \begin{enumerate} \item Let ${\cal P}' = \set{\px_1,\ldots,\px_{n}}$ and ${\cal P}'' = \set{\px_{n+1},\ldots,\px_{2n}}$.\label{step:split-database} \item Compute ${\cal T} = \mathsf{GenEmpiricalMeans}^{\mathsf{A}}({\cal P}',k,s,t)$.\label{step:cM} \item Compute $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k} = \mathsf{B}({\cal T})$.\label{step:kAveragesOnM} \item For each $i \in [k]:$\label{step:Gaussian:forloop} \begin{enumerate} \item Let ${\cal P}_i''$ be the points in ${\cal P}''$ that $\hpa_i$ is the closest point to them among $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$. \label{step:compute-clusters-kmeans-gaus} \item Compute $(\hat{\mu}_i,\hat{\Sigma}_i) = \mathsf{A}'({\cal P}_i'')$.\label{step:priv-single-Gauss-est} \item Let $\hat{n}_i \gets \size{{\cal P}_i''} + {\rm Lap}(4/\varepsilon)$.\label{step:Lap} \end{enumerate} \item For each $i \in [k]: \quad $ Set $\hat{w}_i = \frac{\hat{n}_i}{\sum_j \hat{n}_j}$.\label{step:wi} \item Output $\hat{{\cal D}} = \set{(\hat{\mu}_1,\hat{\Sigma}_1,\hat{w}_1),\ldots,(\hat{\mu}_k,\hat{\Sigma}_k,\hat{w}_k)}$. \end{enumerate} \end{algorithm} \subsubsection{Properties of $\mathsf{PrivatekGMM}$} The following theorem summarizes the privacy guarantee of $\mathsf{PrivatekGMM}$. As a running example, fix the following target parameters: An accuracy parameter $\eta > 0$, a confidence parameter $\beta > 0$, privacy parameters $\varepsilon,\delta \in (0,1)$ and bounding parameters $R,\sigma_{\max},\sigma_{\min} > 0$. Also, think of the (non-private) labeling algorithm $\mathsf{A}$ as the one of \cite{AM05} that needs $s = \tilde{O}\paren{\frac{dk}{w_{\min}}}$ samples, think of the private (single) Gaussian learner $\mathsf{A}'$ as the $(\varepsilon/2,\delta/4)$-DP variant of the algorithm of \cite{KLSU19} that needs $\upsilon = \tilde{O}\paren{\frac{d^2}{\eta^2} + \paren{\frac{d^2}{\varepsilon \eta} + \frac{d^{3/2} \sqrt{\log \paren{\frac{\sigma_{\max}}{\sigma_{\min}}}} + \sqrt{d \log R}}{\varepsilon}} \cdot \sqrt{\log(1/\delta)}}$ samples, and think of algorithm $\mathsf{B}$ as our averages-estimator $\mathsf{PrivatekAverages}$ (\cref{alg:FindAverages}) that needs $t =\tilde{O}\paren{\frac{d k \cdot \log^{2.5}(1/\delta)\paren{\sqrt{\log(1/\delta)} + \log\paren{\Lambda/r_{\min}}}}{\varepsilon^2}}$ tuples. The values of $r_{\min}$ and $\Lambda$ that we should use are determined by our utility guarantee (\cref{thm:kGauss-utility}). This means that for the oracle $\mathsf{B}$ we actually should wrap $\mathsf{PrivatekAverages}$ such that if there is a tuple that contains a point which is not in $B(\pt{0},\Lambda)$, then $\mathsf{B}$ replaces it with some arbitrary fixed tuple (e.g., the all-zero tuple $\pt{0}^k$) We first state the privacy guarantee of $\mathsf{PrivatekGMM}$. \begin{theorem}[Privacy of $\mathsf{PrivatekGMM}$]\label{thm:kGauss-privacy} Let $\mathsf{A}$ be an (arbitrary, non-private) labeling algorithm, let $\mathsf{A}'$ be an $(\varepsilon/4,\delta/2)$-DP algorithm, and let $\mathsf{B}$ be an $(\varepsilon,\delta)$-differentially private algorithm for databases ${\cal T} \in (({\mathbb R}^d)^k)^t$ (i.e., of size $t$). Then for every $d,k,R,\sigma_{\max},\sigma_{\min},w_{\min} > 0$ and $\eta,\beta,\varepsilon,\delta, \gamma \in (0,1)$, algorithm $\mathsf{PrivatekGMM}^{\mathsf{A},\mathsf{A}',\mathsf{B}}(\cdot, k, s,t,\eta,\beta,\varepsilon, \delta,R, \sigma_{\max}, \sigma_{\min})$ is $(\varepsilon,\delta)$-differentially private for databases ${\cal P} \in \paren{{\mathbb R}^d}^*$. \end{theorem} \begin{proof} Assume for simplicity (and without loss of generality) that the input algorithm $\mathsf{A}$ is deterministic, let ${\cal P},\tilde{{\cal P}} \in \paren{{\mathbb R}^d}^{2n}$ be two neigboring databases, and consider two executions $\mathsf{PrivatekGMM}({\cal P})$ and $\mathsf{PrivatekGMM}(\tilde{{\cal P}})$ (both with the same input parameters and oracles). Let ${\cal P}'$, ${\cal P}''$, ${\cal T}$ be the multisets from the execution $\mathsf{PrivatekGMM}({\cal P})$, and let $\tilde{{\cal P}}'$, $\tilde{{\cal P}}''$, $\tilde{{\cal T}}$ be the corresponding multisets in the execution $\mathsf{PrivatekGMM}(\tilde{{\cal P}})$. If ${\cal P}'\neq \tilde{{\cal P}}'$ (i.e., neighboring), then assume w.l.o.g. that the two executions share the same randomness in Steps \ref{step:cM} (i.e., in the execution of $\mathsf{GenEmpiricalMeans}$), but use independent randomness in the execution of $\mathsf{B}$ in Step \ref{step:kAveragesOnM} and in the next steps of the algorithm. Therefore, ${\cal T}$ and ${\cal T}'$ differ by at most one $k$-tuple. Hence, by the privacy guarantee of $\mathsf{B}$ along with group privacy (\cref{fact:group-priv}) we obtain that the resulting outcome $\set{\hpa_1,\ldots,\hpa_k}$ in Step~\ref{step:kAveragesOnM} of both executions is $(\varepsilon,\delta)$-indistinguishable. Since ${\cal P}' \neq \tilde{{\cal P}}'$ implies that ${\cal P}'' = \tilde{{\cal P}}''$, we conclude by post-processing (\cref{fact:post-processing}) that the final outcome $\hat{{\cal D}}$ is also $(\varepsilon,\delta)$-indistinguishable. In the rest of the analysis we focus on the case that ${\cal P}' = \tilde{{\cal P}}'$ and ${\cal P}'' \neq \tilde{{\cal P}}''$ (i.e., neighboring). In this case, we assume that both executions share the same randomness up to (and including) Step~\ref{step:kAveragesOnM}, and use independent randomness from \ref{step:Gaussian:forloop} till the end. Therefore, the value of $\set{\hpa_1,\ldots,\hpa_k}$ in Step~\ref{step:kAveragesOnM} is identical in both executions. Let ${\cal P}''_1,\ldots,{\cal P}''_k$ be the multisets from Step~\ref{step:compute-clusters-kmeans-gaus} in the execution $\mathsf{PrivatekGMM}({\cal P})$, and let ${\tilde{{\cal P}}}''_1,\ldots,{\tilde{{\cal P}}}''_k$ be these multisets in the execution $\mathsf{PrivatekGMM}({\tilde{{\cal P}}})$. Since ${\cal P}''$ and ${\tilde{{\cal P}}}''$ are neighboring, there exists at most two values $i,j \in [k]$ such that ${\cal P}''_i \neq {\tilde{{\cal P}}}_i''$ and ${\cal P}''_j \neq {\tilde{{\cal P}}}_j''$, and in both cases the multisets are neighboring (in the other indices the multisets are equal). By the properties of the private algorithm $\mathsf{A}'$ and basic composition (\cref{thm:composition1}), the vector $((\hat{\mu}_1,\hat{\Sigma}_1),\ldots,(\hat{\mu}_k,\hat{\Sigma}_k))$ computed in Step~\ref{step:priv-single-Gauss-est} of both executions is $(2\cdot \frac{\varepsilon}{4},2 \cdot \frac{\delta}{2})$-indistinguishable. Moreover, by the properties of the Laplace Mechanism along with basic composition, the vector $(\hat{n}_1,\ldots,\hat{n}_k)$ is $(2\cdot \frac{\varepsilon}{4}, 0)$-indistinguishable. By applying again basic composition we deduce that both vectors together are $(\varepsilon,\delta)$-indistinguishable, and therefore we conclude by post-processing (\cref{fact:post-processing}) that the resulting $\hat{{\cal D}}$ in both execution is $(\varepsilon,\delta)$-indistinguishable. \end{proof} The following theorem summarizes the utility guarantee of $\mathsf{PrivatekGMM}$. \def\thmKGaussUtility{ Let $n,d,k,s,t,\upsilon \in {\mathbb N}$, $R,\sigma_{\max},\sigma_{\min},w_{\min}, \gamma > 0$, $\eta,\beta,\varepsilon,\delta \in (0,1)$, let $\Delta = 8 + 12/\gamma$, and let ${\cal D} = \set{(\mu_1,\Sigma_1,w_1), \ldots, (\mu_k,\Sigma_k,w_k)}$ be an $(R,\sigma_{\max},\sigma_{\min},w_{\min})$-bounded $(1+\gamma)h$-separated mixture of $k$ Gaussians in ${\mathbb R}^d$, for $h \geq 2\sqrt{2\log\paren{8n/\beta}}$. In addition, let $\mathsf{A}$ be a (non-private) $\paren{s,\frac{\beta}{8t}}$-labeling algorithm for ${\cal D}$ (\cref{def:LabelingAlg}), let $\mathsf{A}'$ be an $(\upsilon,\frac{\eta}2,\frac{\beta}{16k})$-learner for $(R,\sigma_{\max},\sigma_{\min})$-bounded Gaussians (\cref{def:LearnAlgSingleGaus}), and let $\mathsf{B}$ be an $(t,\text{ }\alpha=1,\text{ }r_{\min}=\frac{(1+\gamma) h}{\Delta}\cdot \sigma_{\min},\text{ } \beta/8,\text{ }\Delta,\text{ }\Lambda=R + \frac{(1+\gamma) h}{\Delta}\cdot \sigma_{\max})$-averages-estimator for $k$-tuple clustering (\cref{def:averages-estimator}). Assume that \begin{align*} s \geq \frac{4}{w_{\min}}\cdot \max\biggl\{\log\paren{8 k t/\beta}, \quad \frac{\Delta^2\paren{d + 2 \log\paren{16 k t/\beta}}}{(1+\gamma^2) h^2} \biggr\}, \end{align*} and that \begin{align*} n \geq \max \biggl\{s\cdot t, \quad \frac{2 \upsilon + \log(16k/\beta)}{w_{\min}}, \quad \frac{4k^2}{\varepsilon \eta} \cdot \log\paren{8k/\beta} \biggr\} \end{align*} Then with probability $1-\beta$, when sampling a database ${\cal P}$ of $2n$ i.i.d.\ samples from ${\cal D}$, the execution $\mathsf{PrivatekGMM}^{\mathsf{A},\mathsf{A}',\mathsf{B}}({\cal P},k,s,t,\varepsilon)$ outputs $\hat{{\cal D}}$ such that ${\rm d}_{\rm TV}({\cal D},\hat{{\cal D}}) \leq \eta$. } \begin{theorem}[Utility of $\mathsf{PrivatekGMM}$]\label{thm:kGauss-utility} \thmKGaussUtility \end{theorem} The proof of the theorem appears at \cref{missing-proof:thm:kGauss-utility}. Very roughly, the first term in the bound on $n$ is because $\mathsf{GenEmpiricalMeans}$ splits the $n$ samples into $t$ pieces, each contains $s$ samples. The second and third terms in the bound on $n$ are the number of samples that are needed for guaranteeing that with probability $1-\frac{\beta}4$, for each $i\in [k]$, the resulting $(\hat{\mu}_i,\hat{\Sigma}_i)$ in Step~\ref{step:priv-single-Gauss-est} satisfy ${\rm d}_{\rm TV}({\cal N}(\hat{\mu}_i,\hat{\Sigma}_i), {\cal N}(\mu_i,\Sigma_i)) \leq \frac{\eta}2$ and the resulting $\hat{w}_i$ in Step~\ref{step:wi} satisfy $\size{\hat{w}_i - w_i} \leq \frac{\eta}{k}$, which yields that ${\rm d}_{\rm TV}(\hat{{\cal D}},{\cal D}) \leq \eta$ (see \cref{fact:dTV-of-mixtures}). We remark that regardless of the non-private algorithm $\mathsf{A}$ that we are using and its assumption on ${\cal D}$, we only require that ${\cal D}$ is more than $2\sqrt{2\log\paren{\frac{8n}{\beta}}}$-separated, which follows by the projection argument in \cref{prop:separation}. \remove{ \begin{remark} \Enote{Add running time analysis} \end{remark} } \subsection{Remarks}\label{sec:Gaussians:remarks} It is tempting to think that our approach, which relies on the algorithm $\mathsf{B} = \mathsf{PrivatekAverages}$ for aggregating the non-private findings by a reduction to $k$-tuple clustering, requires that the distance between the means should be proportional to $\sqrt{d}$, because this is the distance of the samples from their means. However, recall that $\mathsf{PrivatekGMM}$ do not set the $k$-tuple to be some arbitrary $k$ samples from different Gaussians. Rather, it sets it to the \emph{averages} of the samples in each set (See Step~\ref{step:compute-emp-mean} in \cref{alg:genBalancedSamples}), which decreases the distance from the actual means. In particular, when there are $O(d)$ samples in each such set, the dependency in $d$ is eliminated and the reduction to the $k$-tuple clustering follows (even when the distance between the means is much smaller than $\sqrt{d}$, as we consider). Furthermore, note that our algorithm $\mathsf{PrivatekGMM}$ in Step~\ref{step:compute-clusters-kmeans-gaus} relies on the fact that the output $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$ of $\mathsf{PrivatekAverages}$ separates correctly fresh samples from the mixture. This might seem strange since even if $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$ is very close to the actual means $\set{\mu_1,\ldots,\mu_k}$, the distance of each sample from its mean is proportional to $\sqrt{d}$, while the assumed separation between the means is independent of $d$. This yields that when $d$ is large, then the samples are much far from their means compared to the distance between the means. Namely, if $\px$ is sampled from the $i$'th Gaussian and $\norm{\mu_i-\mu_j}$ is independent of $d$ (for large $d$), then $\norm{\px - \mu_i} \gg \norm{\mu_i - \mu_j}$. Yet, in our analysis we use a projection argument (see \cref{prop:separation}) which yields that w.h.p. it holds that $\norm{\px - \mu_i} < \norm{\px- \mu_j}$, even though $\norm{\px - \mu_i} \gg \norm{\mu_i - \mu_j}$. \subsection{Comparison to the Main Algorithm of \cite{KSSU19}}\label{sec:Gauss:comparison} The main private algorithm of \cite{KSSU19} mimics the approach of the (non-private) algorithm of \cite{AM05}, which is to use PCA to project the data into a low-dimensional space, and then clustering the data points in that low-dimensional space. This projection enable both algorithms to learn mixtures that have the following separation \begin{align}\label{eq:AM05-sep} \forall i,j\colon \quad \norm{\mu_i-\mu_j} \geq C \paren{\sqrt{k \log(nk/\beta)} + \frac1{\sqrt{w_i}} + \frac1{\sqrt{w_j}}} \cdot \max\set{\sigma_i,\sigma_j}, \end{align} for some constant $C > 0$ (albeit that the constant of \cite{KSSU19} is much larger, say $C=100$ instead of $C=4$ as in \cite{AM05}). But while \cite{AM05} use a simple Kruskal-based clustering method, \cite{KSSU19} developed alternative (and much more complicated) clustering methods that are more amenable to privacy. Finally, after the clustering phase, \cite{KSSU19} use a variant of the private algorithm of \cite{KLSU19} to learn the parameters of each Gaussian. Overall, the algorithm of \cite{KSSU19} learns an $(R,\sigma_{\max},\sigma_{\min},w_{\min})$-bounded mixture of Gaussian that is separated as in \cref{eq:AM05-sep}, with sample complexity \begin{align*} n \geq \paren{\frac{d^2}{\eta^2 w_{\min}} + \frac{d^2}{\varepsilon \eta w_{\min}} + \frac{{\rm poly}(k) d^{3/2}}{w_{\min} \varepsilon}} \cdot {\rm polylog}\paren{\frac{d k R \sigma_{\max}}{\eta \beta \varepsilon \delta \sigma_{\min}}} \end{align*} In the following, we compare between \cite{KSSU19}'s algorithm and ours (Algorithm $\mathsf{PrivatekGMM}$) in two different aspects: separation assumption and sample complexity. \subsubsection{Separation Assumption} The utility guarantee of $\mathsf{PrivatekGMM}$ (\cref{thm:kGauss-utility}) only requires a separation of slightly more than $h =2\sqrt{2 \log(8n/\beta)}$. Therefore, our algorithm can transform any non-private algorithm (in a modular way) that learns mixtures with separation $X$ into a private algorithm that learns with separation $\max\set{X, h}$. In particular, we can use \cite{AM05} as our non-private labeling algorithm $\mathsf{A}$ to learn mixtures with separation as in \cref{eq:AM05-sep} (with the small constant $C=4$), and we can also use any other non-private algorithm (like \cite{VW04,HSJ18,KPSJS18,diakonikolas18,RV17}) and inherent their separation assumption. In contrast, the approach of the main algorithm of \cite{KSSU19} may only be extended to methods that use statistical properties of the data (like PCA), and not to other algorithmic machineries such as the sum-of-squares that are used for reducing the separation assumption. \subsubsection{Sample Complexity} The main algorithm of \cite{KSSU19} learns an $(R,\sigma_{\max},\sigma_{\min},w_{\min})$-bounded mixture of Gaussians that is separated as in \cref{eq:AM05-sep}, with sample complexity (roughly) $\tilde{O}\paren{\frac{\upsilon}{w_{\min}} + \frac{k^9 d^{3/2}}{w_{\min} \varepsilon}}$ (ignoring logarithmic factors), where $\upsilon = \upsilon(d, \varepsilon,\delta,\eta,\beta,R,\sigma_{\max},\sigma_{\min}) = \tilde{O}\paren{\frac{d^2}{\eta^2} + \frac{d^2}{\varepsilon \eta}}$ is the sample complexity of \cite{KLSU19} for learning the parameters of a single Gaussian (ignoring logarithmic factors in $R,\sigma_{\max}/\sigma_{\min},1/\delta,1/\beta$). By \cref{thm:kGauss-utility}, the sample complexity of our algorithm is $\tilde{O}\paren{s \cdot t + \frac{t \cdot d}{w_{\min}} + \frac{\upsilon}{w_{\min}} + \frac{4k^2}{\varepsilon \eta}}$ (ignoring logarithmic factors), where $s$ is the sample complexity needed by the non-private algorithm $\mathsf{A}$ for labeling correctly the samples with confidence $\leq \frac{\beta}{8 t}$ (e.g., if we use the algorithm of \cite{AM05}, then $s = \tilde{O}\paren{\frac{dk}{w_{\min}}}$, and for simplifying the comparison, we assume that this is indeed the algorithm that we use). Since $t = \tilde{O}\paren{\frac{d k}{\varepsilon^2}}$, we obtain a sample complexity of (roughly) $\tilde{O}\paren{\frac{k^2 d^2}{\varepsilon^2 w_{\min}} + \frac{\upsilon}{w_{\min}} + \frac{4k^2}{\varepsilon \eta}}$, which might me larger than the one of \cite{KSSU19} if $d$ or $1/\varepsilon$ are very large (compared to $k$). Yet, we can easily improve the dependency in both $d$ and $\varepsilon$. Using sub-sampling, we can execute Step~\ref{step:cM} of $\mathsf{PrivatekGMM}$ on an $\varepsilon n$-size random subset of ${\cal P}'$ (for the small desired $\varepsilon$), but now we only need a constant $\varepsilon$ for these steps. This immediately reduces the $1/\varepsilon^2$ in our sample complexity into $1/\varepsilon$. In addition, as mentioned in \cref{sec:reducing-by-JL}, using the average algorithm of \cite{NSV16} in $\mathsf{PrivatekAverages}$ (instead of the average algorithm from \cref{prop:approx-aver-Rd}), we can reduce a factor of $\sqrt{d}$. For summary, using sub-sampling and the algorithm of \cite{NSV16}, we obtain an improved sample complexity of $\tilde{O}\paren{\frac{k^2 d^{3/2}}{\varepsilon w_{\min}} + \frac{\upsilon}{w_{\min}} + \frac{4k^2}{\varepsilon \eta}}$, which strictly improves the sample complexity of \cite{KSSU19}. \remove{ \subsubsection{Running-Time and Practicality} \Enote{TBD. add running time analysis to all our algorithms, and check whether \cite{KSSU19} provide concrete running time analysis. Also, mention that our algorithm uses in a black-box way the the labeling algorithm and private learning algorithm of a single Gaussian. And also, that our algorithm can be easily parallelized} } \remove{ \Enote{Consider mentioning also that our algorithm is much more simpler, probabily more efficient and practical, and also can be easily parallelized.} \Enote{ Consider adding the following discussion to the intro: Can we use JL transform for learning a mixture of Gaussian? Suppose we have two spherical Gaussians ${\cal G}_1 = {\cal N}(\mu_1,\sigma^2 {\mathbb I}_{d \times d})$ and ${\cal G}_2 ={\cal N}(\mu_2,\sigma^2 {\mathbb I}_{d \times d})$ that we would like to separate, where $\norm{\mu_1 - \mu_2}$ is large enough (but independent of $d$). In the JL transform, we choose $k = \log n$ vectors $\py_1,\ldots,\py_k \sim {\cal N}(0,{\mathbb I}_{d \times d})$ and we transform each $\px \in {\mathbb R}^d$ into $(\rm ip{\px,\py_1},\ldots,\rm ip{\px,\py_k})$. Note that each $\rm ip{\px,\py_i}$ is distributed according to the $1$-dimensional Gaussian ${\cal N}(0,d(\sigma^2+1))$, which yields that if $\pX \sim {\cal N}(\mu,\sigma^2 {\mathbb I}_{d \times d})$ then $f(\pX) \sim {\cal N}(\mu,\sigma^2 (d+1) {\mathbb I}_{k \times k})$. So the problem is that the variance of the new Gaussian depends on $d$, while the new separation between $\mu_i$ and $\mu_j$ is independent of $d$ (only increases by a factor of $\sqrt{k}$)! } } \subsection{Private $k$-Means under Separation Assumption}\label{sec:application} In this section we show that our stability assumption holds with high probability when the multiset ${\cal P}$ is separated according to \citet{OstrovskyRSS12}. Formally, a multiset of points ${\cal P}$ is \emph{$\phi$-separated} for $k$-means if ${\rm OPT}_k({\cal P}) \leq \phi^2 {\rm OPT}_{k-1}({\cal P})$. In \cref{def:sep-ost} we strength this definition of \cite{OstrovskyRSS12} to include also an additive separating term $\xi$. \begin{definition}[$(\phi,\xi)$-separated]\label{def:sep-ost} A multiset ${\cal P} \in ({\mathbb R}^d)^*$ is $(\phi,\xi)$-separated for $k$-means if \noindent ${\rm OPT}_k({\cal P}) + \xi \leq \phi^2\cdot {\rm OPT}_{k-1}({\cal P})$. Note that ${\cal P}$ is $\phi$-separated iff it is $(\phi,0)$-separated. \end{definition} We use the following theorem from \cite{OstrovskyRSS12} which states that when ${\cal P}$ is $\phi$-separated for $k$-means for sufficiently small $\phi$, then any set of $k$ centers that well approximate the $k$ means cost, must have the property that each of its centers is relatively close to an optimal center. \begin{theorem}[\cite{OstrovskyRSS12}]\footnote{The statement of this theorem was taken from \cite{ShechnerSS20}.}\label{thm:Ostrovsky} Let $\nu$ and $\phi$ be such that $\frac{\nu + \phi^2}{1-\phi^2} < \frac1{16}$. Suppose that ${\cal P} \in ({\mathbb R}^d)^*$ is $\phi$-separated for $k$-means. Let $C^* = \set{\pc_1^*,\ldots,\pc_k^*}$ be a set of \emph{optimal} centers for ${\cal P}$, and let $C= \set{\pc_1,\ldots,\pc_k}$ be centers such that ${\rm COST}_{{\cal P}}(C) \leq \nu \cdot {\rm OPT}_{k-1}({\cal P})$. Then for each $\pc_i$ there is a distinct optimal center, call it $\pc_i^*$, such that $\norm{\pc_i - \pc_i^*} \leq 2 \cdot \frac{\nu + \phi}{1 - \phi}\cdot D_i$, where $D_i = \min_{j \neq i}\norm{\pc_i^* - \pc_j^*}$. \end{theorem} The following lemma states that for suitable choices of $\phi$ and $\xi$, if ${\cal P}$ is $(\phi,\xi)$-separated for $k$-means, then with high probability, the event $E_{C^*}^{\gamma}$ over a random execution of $\mathsf{GenCenters}$ (\cref{def:event-ECgamma}) occurs, where $C^*$ is the optimal $k$-means for ${\cal P}$. \begin{lemma}[Bounding the stability probability]\label{lem:bounding-stability-under-sep} Let $n,d,k,s,t \in {\mathbb N}$, $\beta, \phi \in (0,1)$, $\gamma \in (0,1/16]$, be values such that $\frac{(1 + \omega) \phi^2}{1-\phi^2} < \frac1{16}$ and $\gamma \geq 2\cdot \frac{\omega \phi^2 + \phi}{1 - \phi}$. Let $\mathsf{A}$ be a (non-private) $\omega$-approximation algorithm for $k$-means, let ${\cal P} \in (B(\pt{0},\Lambda))^n$ and let $C^* = \set{\pc_1^*,\ldots,\pc_k^*} \in ({\mathbb R}^d)^k$ be the \emph{optimal} $k$-means for ${\cal P}$. Assume that ${\cal P}$ is $(\phi,\xi)$-separated for $k$-means, where $$\xi = \xi\paren{s, \beta/t} = \tilde{O}\paren{\Lambda^2 k d \log(n t/\beta) \cdot \frac{n}{s} + \Lambda \sqrt{k d \log(n t/\beta) \cdot \omega {\rm OPT}_{k}({\cal P}) \cdot \frac{n}{s}}}$$ is the function from \cref{prop:cost-of-sample-is-good}. Then when executing $\mathsf{GenCenters}^{\mathsf{A}}({\cal P},k,s,t)$, the event $E_{C^*}^{\gamma}$ (\cref{def:event-ECgamma}) occurs with probability at least $1-\beta$. \end{lemma} \begin{proof} For $j \in [t]$, let ${\cal S}_j$ and $\tilde{C}_j$ be the values in steps \ref{step:sample} and \ref{step:non-priv-centers} of $\mathsf{GenCenters}$ (respectively). Note that by \cref{prop:cost-of-sample-is-good} and the union bound, with probability at least $1-\beta$ it holds that \begin{align}\label{eq:small-cost} \forall j \in [t]: \quad {\rm COST}_{{\cal P}}(\tilde{C}_j) \leq \omega\cdot {\rm OPT}_k({\cal P}) + \xi \leq \omega \phi^2 {\rm OPT}_{k-1}({\cal P}), \end{align} where the last inequality holds by the assumption that ${\cal P}$ is $(\phi,\xi)$-separated for $k$-means and that $\omega \geq 1$. In the following, assume that (\ref{eq:small-cost}) occurs. Since ${\cal P}$ is (in particular) $\phi$-separated, and since the conditions of \cref{thm:Ostrovsky} hold with $\nu = \omega \phi^2$, we obtain from \cref{thm:Ostrovsky} that for every $i \in [k]$ and $j \in [t]$, there exists $\tpc_i^j \in \tilde{C}_j$ such that $\norm{\pc_i^* - \tpc_i^j} \leq \gamma D_i$, meaning that event $E_{C^*}^{\gamma}$ occurs, as required. \end{proof} As a corollary of \cref{claim:kMeans-utility,lem:bounding-stability-under-sep}, we obtain our main application of algorithm $\mathsf{PrivatekMeans}$. \begin{theorem}\label{cor:util-result} Let $n,s,t,k,d \in {\mathbb N}$, $\varepsilon,\delta,\beta \in (0,1]$, $\Lambda > 0$, let $\phi, {\cal P}, \mathsf{A}, \omega, \gamma$ as in \cref{lem:bounding-stability-under-sep}, and let $\zeta, \mathsf{A}',\mathsf{B}$ as in \cref{claim:kMeans-utility}. Then when executing $\mathsf{PrivatekMeans}^{\mathsf{A},\mathsf{A}',\mathsf{B}}({\cal P},s,t,k,\varepsilon,\delta,\beta,\gamma)$, with probability $1-2\beta$, the resulting centers $\hat{C} = \set{\hpc_1,\ldots,\hpc_k}$ satisfy \begin{align*} {\rm COST}_{{\cal P}}(\hat{C}) \leq (1 + 64\gamma) {\rm OPT}_{k}({\cal P}) + \zeta k (\zeta + 2\Lambda) \end{align*} \end{theorem} \begin{proof} The proof almost immediately holds by \cref{claim:kMeans-utility,lem:bounding-stability-under-sep} when applying them to the optimal $k$-means of ${\cal P}$, which we denote by $C^* = \set{\pc_1^*,\ldots,\pc_k^*}$. The only missing requirement is to show that $D^* := \min_{i \neq j} \norm{\pc_i^* - \pc_j^*} \geq 1/n$, as required by \cref{claim:kMeans-utility}. For proving this, note that on the one hand it holds that ${\rm OPT}_{k-1}({\cal P}) \leq D^* n + {\rm OPT}_{k}({\cal P})$, and on the other hand, since we assume that ${\cal P}$ is $(\phi,\xi)$-separated for $\phi \leq 1$ and $\xi \geq 1$ then it holds that ${\rm OPT}_k({\cal P}) + 1 \leq {\rm OPT}_{k-1}({\cal P})$. From the two inequalities we conclude that $D^* \geq 1/n$ and the corollary follows. \end{proof} We note that by the utility guarantee (\cref{claim:utility-kAverg}) of our $k$-tuple clustering $\mathsf{PrivatekAverages}$ (\cref{alg:FindAverages}), by choosing $\mathsf{B} = \mathsf{PrivatekAverages}(\cdot, \varepsilon/6, \delta/(4 e^{\varepsilon}), \beta/2, r_{\min}=\gamma/n)$ we obtain that $\mathsf{B}$ is an $\left(\frac{\varepsilon}{6},\frac{\delta}{4 e^{\varepsilon}}\right)$-differentially private $(t, \alpha=1, \: r_{\min}=\gamma/n, \: \beta/2, \: \Delta = 1/\gamma, \: \Lambda)$-averages-estimator for $k$-tuple clustering, where (ignoring ${\rm polylog}(n,d,k)$ factors) \begin{align*} t =\tilde{\Omega}\paren{\frac{d k \cdot \log^{2.5}(1/\delta)\paren{\sqrt{\log(1/\delta)} + \log\paren{\Lambda/r_{\min}}}}{\varepsilon^2}}. \end{align*} Hence, by taking $n = 2st$ we conclude that $\mathsf{PrivatekMeans}^{\mathsf{A}, \mathsf{A}', \mathsf{B}}(\cdot, k, s, t, \varepsilon,\delta,\beta,\gamma)$ is an $(\varepsilon,\delta)$-differentially private algorithm (\cref{claim:kMeans-privacy}) with the utility guarantee stated in \cref{cor:util-result}. In particular, when taking $n = 2st$ we obtain that our theorem holds for an additive error $\xi$ in the separation (see \cref{lem:bounding-stability-under-sep} for the definition of $\xi$), where (ignoring logarithmic factors) \begin{align*} \xi = \tilde{\Omega}\paren{\Lambda^2 k d t + \Lambda \sqrt{k d t \omega \cdot {\rm OPT}_{k}({\cal P})}} \end{align*} \section{Additional Preliminaries} \subsection{Additional Facts About Differential Privacy} \subsubsection{The Exponential Mechanism} We next describe the Exponential Mechanism of \citet{MT07}. Let ${\cal X}$ be a domain and ${\cal H}$ a set of solutions. Given a database ${\cal S} \in {\cal X}^*$, the Exponential Mechanism privately chooses a “good” solution $h$ out of the possible set of solutions ${\cal H}$. This “goodness” is quantified using a quality function that matches solutions to scores. \begin{definition}(Quality function) A quality function is a function $q\colon {\cal X}^* \times {\cal H} \mapsto {\mathbb R}$ that maps a database ${\cal S} \in {\cal X}^*$ and a solution $h \in {\cal H}$ to a real number, identified as the score of the solution $h$ w.r.t the database ${\cal S}$. \end{definition} Given a quality function $q$ and a database ${\cal S}$, the goal is to chooses a solution $h$ approximately maximizing $q({\cal S},h)$. The Exponential Mechanism chooses a solution probabilistically, where the probability mass that is assigned to each solution $h$ increases exponentially with its quality $q({\cal S},h)$: \begin{definition}(The Exponential Mechanism)\label{def:exp-mech} Given input parameter $\varepsilon$, finite solution set ${\cal H}$, database ${\cal S} \in {\cal X}^m$, and a sensitivity $1$ quality function $q$, choose randomly $h \in {\cal H}$ with probability proportional to $\exp(\varepsilon\cdot q({\cal S},h)/2)$. \end{definition} \begin{proposition}(Properties of the Exponential Mechanism)\label{prop:exp-mech} (i) The Exponential Mechanism is $\varepsilon$-differentially private. (ii) Let $\hat{e} := \max_{f \in {\cal H}}\set{q({\cal S},f)}$ and $\Delta > 0$. The Exponential Mechanism outputs a solution $h$ such that $q({\cal S},h) \leq \hat{e} - \Delta$ with probability at most $\size{{\cal H}}\cdot \exp\paren{-\varepsilon\Delta/2}$. \end{proposition} \subsubsection{Private Interior Point and Bounding Segment in ${\mathbb R}$}\label{sec:interior-point} \begin{proposition}[Finding an Interior Point in ${\mathbb R}$]\label{prop:interior-point} Let $\varepsilon \in (0,1)$, $\Lambda > 0$ and $g \in [0,\Lambda]$. There exists an efficient $\varepsilon$-differentially private algorithm that takes an $n$-size database ${\cal S}$ of numbers in the segment $[-\Lambda,\Lambda]$ and outputs a number $z \in [-\Lambda,\Lambda]$ that with probability $1 - 2(\Lambda/g + 1) \cdot \exp\paren{-\varepsilon n/4}$ it holds that $z \in [\min({\cal S}) - g, \max({\cal S}) + g]$. The algorithm runs in time $\tilde{O}\paren{n}$ (ignoring $\log\paren{\frac{n \Delta}{g}}$ factors). \end{proposition} \begin{proof} Define the grid $G = \set{-\Lambda, -\Lambda+g, \ldots, -\Lambda + \ceil{\frac{2\Lambda}{g}}\cdot g}$, and for every $x \in G$ let ${\rm left}(x) = - \Lambda + \floor{\frac{x + \Lambda}{g}} \cdot g$ (i.e., the closest grid point to $x$ from the left side) and ${\rm right}(x) = - \Lambda + \ceil{\frac{x + \Lambda}{g}} \cdot g$ (i.e., the closest grid point to $x$ from the right side). Now, apply the exponential mechanism (\ref{def:exp-mech}) with the quality function \begin{align*} \forall y \in G\colon \quad q({\cal S},y) = \min\set{\size{\set{x \in {\cal S} \colon {\rm left}(x) \leq y}}, \size{\set{x \in {\cal S} \colon {\rm right}(x) \geq y}}} \end{align*} For the utility analysis, let $m$ be the median of ${\cal S}$, and note that $q({\cal S},{\rm left}(m)), q({\cal S},{\rm right}(m)) \geq n/2$. Therefore, by \cref{prop:exp-mech}, with probability $\geq 1 - \size{G}\cdot \exp\paren{-\varepsilon n/4} \geq 1 - 2(\Lambda/g + 1) \cdot \exp\paren{-\varepsilon n/4}$, the mechanism outputs a point $z$ with $q(S,z) > 0$, which yields in particular that $z \in [\min({\cal S}) - g, \max({\cal S}) + g]$. For the running time analysis, we implement the sampling as follows: For $x \in {\cal S}$ we let $A_x = \set{{\rm left}(x)-g,{\rm left}(x),{\rm right}(x), {\rm right}(x) + g}$, and let $A = \cup_{x \in {\cal S}} A_x$. Note that for every consecutive grid points $y, y'=y+g \in G$ with $q({\cal S}, y) \neq q({\cal S}, y')$, it holds that $y,y' \in A$: If $q({\cal S}, y) > q({\cal S}, y')$, there must exist $x \in {\cal S}$ such that $x \in (y-g,y]$, yielding that $y \in [x,x+g) \implies y = {\rm right}(x), y' = {\rm right}(x) + g$. Otherwise (i.e., $q({\cal S}, y) < q({\cal S}, y')$), there must exist $x \in {\cal S}$ such that $x \in [y',y'+g)$, yielding that $y' \in (x-g,x] \implies y' = {\rm left}(x), y = {\rm left}(x) - g$. Then, we sort $A$ in time $\tilde{O}(n)$, and let $a_1 \leq \ldots \leq a_m$ be the sorted elements in $A$ (recall that $m = \size{A} \leq 4n$). For each $i \in [m+1]$, we compute $w({\cal S},a_i) = q({\cal S},a_i) \cdot \size{G \cap (a_{i-1},a_i]}$ (i.e., $w({\cal S},a_i)$ is the the original quality of $a_i$ times the number of grid points in $(a_{i-1},a_i]$, where $a_0 = -\Lambda-g$ and $a_{m+1} = \Lambda+g$), and choose a value $a_i$ with probability $\propto w({\cal S},a_i)$. Note that the computation of each $w({\cal S},a_i)$ can be done in time $\tilde{O}(1)$ using simple binary searches over the (sorted) multisets ${\cal S}_{{\rm left}} = \cup_{x \in {\cal S}} \set{{\rm left}(x)}$ and ${\cal S}_{{\rm right}} = \cup_{x \in {\cal S}} \set{{\rm right}(x)}$ (a ``multiset'' union, that includes duplications). Finally, given the chosen $a_i$ from the mechanism, it is left to sample a uniform point in $G \cap (a_{i-1},a_i]$ (since we know, by the property of $A$, that all the point there have the same value of $q({\cal S},\cdot)$). This can be easily implemented in time $O(\log \size{G}) = \tilde{O}(1)$. \end{proof} \begin{proposition}[Finding a Bounding Segment of Points in ${\mathbb R}$]\label{prop:bounding-seg} Let $\beta, \varepsilon \in (0,1)$, $\Lambda > 0$ and $g \in [0,\Lambda]$. There exists an efficient $\varepsilon$-differentially private algorithm that takes an $n$-size database ${\cal S}$ of numbers in the segment $[-\Lambda,\Lambda]$ and outputs a segment $[x,y]$ such that with probability at least $1-\beta$ the following holds: \begin{itemize} \item $\size{{\cal S} \cap [x,y]} \geq n - \frac{8}{\varepsilon} \log \paren{\frac{4\Lambda}{g \beta}} - 2$ (i.e., the segment contain most of the points in ${\cal S}$), and \item $y - x \leq \max({\cal S})-\min({\cal S})+ 4g$. \end{itemize} The algorithm runs in time $\tilde{O}\paren{n}$ (ignoring $\log\paren{\frac{n \Delta}{\varepsilon \beta g}}$ factors). \end{proposition} \begin{proof} In the following assume that $n \geq \frac{8}{\varepsilon} \log \paren{\frac{4\Lambda}{g \beta}} + 2$ (otherwise the proof trivially holds for any segment $[x,x]$). Let ${\cal S}_0$ be the smallest $\frac{4}{\varepsilon} \log \paren{\frac{4\Lambda}{g \beta}} + 1$ points in ${\cal S}$, and let ${\cal S}_1$ be the largest $\frac{4}{\varepsilon} \log \paren{\frac{4\Lambda}{g \beta}} + 1$ points in ${\cal S}$. For each $b \in \set{0,1}$ apply \cref{prop:interior-point} (interior point) on ${\cal S}_b$ for finding a number $z_b \in [-\Lambda,\Lambda]$ that belongs to $[\min({\cal S}_{b}) - g, \max({\cal S}_b) + g]$ with probability at least $1 - 2(\Lambda/g + 1) \cdot \exp\paren{-\varepsilon \size{{\cal S}_b}/4} \geq 1-\beta/2$. Therefore, by setting $x = z_0-g$ and $y = z_1+g$ we get that with probability $1-\beta$ it holds that: (1) $[\max({\cal S}_0), \min({\cal S}_1)] \subseteq [x,y]$ and that (2) $[x,y] \subseteq [\min({\cal S}_0)-2g, \max({\cal S}_1)+2g] = [\min({\cal S})-2g, \max({\cal S})+2g]$. By (1) we get that all points in ${\cal S}$ expect (at most) $(\size{{\cal S}_0} - 1) + (\size{{\cal S}_1} - 1) \leq \frac{8}{\varepsilon} \log \paren{\frac{4\Lambda}{g \beta}}$ are inside $[x,y]$, and by (2) we get that $y-x \geq \max({\cal S})-\min({\cal S}) + 4g$, as required. For the running time analysis, note that by sorting ${\cal S}$ we can determine ${\cal S}_0$ and ${\cal S}_1$ in time $\tilde{O}(n)$, and the cost of executing the algorithm from \cref{prop:interior-point} on each ${\cal S}_b$ is $\tilde{O}\paren{\frac1{\varepsilon}} = \tilde{O}\paren{n}$. \end{proof} \subsubsection{Estimating the Average of Points}\label{sec:approx-aver} \begin{proposition}[Estimating the Average of Bounded Points in ${\mathbb R}$]\label{prop:approx-aver-R} Let $\beta, \varepsilon,\delta \in (0,1)$, $\Lambda > 0$ and $r_{\min} \in [0,\Lambda]$. There exists an efficient $(\varepsilon,\delta)$-differentially private algorithm that takes an $n$-size database ${\cal S}$ of numbers in the segment $[-\Lambda,\Lambda]$ and satisfy the following utility guarantee: If $n \geq \frac{16}{\varepsilon} \log \paren{\frac{4\Lambda}{r_{\min} \beta}} +4$, then with probability $1-\beta$, the algorithm outputs a number $\hat{a} \in {\mathbb R}$ such that \begin{align*} \size{\hat{a} - {\rm Avg}({\cal S})} \leq O\paren{\frac{\max\set{r,r_{\min}}}{\varepsilon n} \paren{\sqrt{\log(1/\delta) \log(1/\beta)} + \log \paren{\frac{\Lambda}{r_{\min} \beta}}}}, \end{align*} where $r = \max({\cal S}) - \min({\cal S})$. The algorithm runs in time $\tilde{O}(n)$ (ignoring $\log\paren{\frac{n \Delta}{r_{\min} \varepsilon \beta}}$ factors). \end{proposition} \begin{proof} The algorithm does the following: (1) Privately find a bounding segment $[x,y]$ using \cref{prop:bounding-seg} with parameters $\beta/2,\varepsilon/2,g = r_{\min},\Lambda$, let $\hat{r} = y-x$ and let ${\cal S}' = {\cal S} \cap [x,y]$ (2) Use the ($1$-dimensional) Gaussian mechanism (\cref{fact:Gaus}) with $\lambda = \frac{\hat{r}}{\size{{\cal S}'}}$ and parameters $\beta/2,\varepsilon/2, \delta$ for computing a noisy average $\hat{a}$ of ${\cal S}'$ (see \cref{obs:Gaus-aver}). By the properties of the Gaussian mechanism (see \cref{remark:Gaus-add-del}) along with basic composition it holds that the above algorithm is $(\varepsilon,\delta)$-differentially private. For the utility analysis, note that with probability $1-\beta$, the segment $[x,y]$ satisfies the conditions of \cref{prop:bounding-seg} and the noise added to the average in the second step is at most $O\paren{\frac{\hat{r}}{\varepsilon \size{{\cal S}'}} \sqrt{\log(1/\delta) \log(1/\beta)}}$. In the rest of the analysis we assume that this event occurs. Now, by definition of $r$, it holds that \begin{align*} \size{{\rm Avg}(S) - {\rm Avg}({\cal S}')} \leq \frac{r \size{{\cal S} \setminus {\cal S}'}}{n} \leq \frac{8 r}{\varepsilon n} \log \paren{\frac{2\Lambda}{r_{\min} \beta}} +\frac{2 r}{n} \end{align*} Moreover, it holds that \begin{align*} \size{\hat{a} - {\rm Avg}({\cal S}')} \leq O\paren{\frac{\hat{r}}{\varepsilon \size{{\cal S}'}} \sqrt{\log(1/\delta) \log(1/\beta)}} \leq O\paren{\frac{\max\set{r,r_{\min}}}{\varepsilon n} \sqrt{\log(1/\delta) \log(1/\beta)}}, \end{align*} where the second inequality holds since $\hat{r} \leq r + 4r_{\min}$ and $\size{{\cal S}'} \geq n/2$ by the assumption on $n$. The proof now follow by the above two inequalities. For the running time analysis, step (1) takes $\tilde{O}(n)$ time (\cref{prop:bounding-seg}). Step (2) that executes the Gaussian Mechanism, takes $\tilde{O}(n)$ time for computing the average, and $\tilde{O}(1)$ for sampling a number from a single one-dimensional. \end{proof} \begin{proposition}[Estimating the Average of Bounded Points in ${\mathbb R}^d$ (Restatement of \cref{prop:approx-aver-Rd})] \propEstAvgInRd \end{proposition} \begin{proof} The algorithm does the following: For each $i \in [d]$, let ${\cal S}_i = \set{x_i \colon (x_1,\ldots,x_d) \in {\cal S}}$ and compute an estimation $\hat{a}_i$ of ${\rm Avg}({\cal S}_i)$ (in time $\tilde{O}(n)$) by applying \cref{prop:approx-aver-R} with parameters $r_{\min},\Lambda$, $\tilde{\varepsilon} = \frac{\varepsilon}{2\sqrt{2d \log(2/\delta)}}$, $\tilde{\delta} = \frac{\delta}{d}$, $\tilde{\beta} = \frac{\beta}{d}$. Finally, output $\hpa = (\hat{a}_1,\ldots, \hat{a}_d)$. It is clear by advanced composition (\cref{thm:composition2}) that the algorithm is $(\varepsilon,\delta)$-differentially private. For the utility guarantee, note that with probability at least $1-\beta$, for every $i \in [d]$ it holds that \begin{align*} \size{\hat{a}_i - {\rm Avg}({\cal S}_i)} &\leq O\paren{\frac{r}{\tilde{\varepsilon} n} \paren{\sqrt{\log(1/\tilde{\delta}) \log(1/\tilde{\beta})} + \log \paren{\frac{\Lambda}{r_{\min} \tilde{\beta}}}}}\\ &= O\paren{\frac{r \sqrt{d \log(1/\delta)}}{\varepsilon n} \paren{\sqrt{\log(d/\delta) \log(d/\beta)} + \log \paren{\frac{\Lambda d}{r_{\min} \beta}}}}, \end{align*} and hence \begin{align*} \norm{\hpa - {\rm Avg}({\cal S})} &= \sqrt{\sum_{i=1}^d (\hat{a}_i - {\rm Avg}({\cal S}_i))^2}\\ &\leq O\paren{\frac{r d \sqrt{\log(1/\delta)}}{\varepsilon n} \paren{\sqrt{\log(d/\delta) \log(d/\beta)} + \log \paren{\frac{\Lambda d}{r_{\min} \beta}}}} \end{align*} \end{proof} \begin{remark}\label{remark:bound-aver-add-del} The above two algorithms guarantee differential-privacy whenever two neighboring databases have equal size. However, they can be easily extended to a more general case in which the privacy guarantee also holds in cases of addition and deletion of a point, by extending the Gaussian mechanism used in \cref{prop:approx-aver-R} (see \cref{remark:Gaus-add-del}) with essentially the same noise magnitude. \end{remark} \section{$k$-Tuples Clustering} We first introduce a new property of a collection of (unordered) $k$-tuples \Hnote{k-sets (shorter and more accurate) \Enote{Do we really want to change ``tuples'' to ``sets''?}} $\set{\px_1,\ldots,\px_k} \in ({\mathbb R}^d)^k$, which we call \emph{partitioned by $\Delta$-far balls}. \begin{definition}[$\Delta$-far balls]\label{def:far-balls} A set of $k$ balls ${\cal B} = \set{B_i = B(\pc_i,r_i)}_{i=1}^k$ over ${\mathbb R}^d$ is called \textbf{$\Delta$-far balls}, if for every $i \in [k]$ it holds that $\norm{\pc_i - \pc_j} \geq \Delta \cdot \max\set{r_i,r_j}$ (i.e., the balls are relatively far from each other). \end{definition} \begin{definition}[partitioned by $\Delta$-far balls]\label{def:sep-balls} \Hnote{add picture} A $k$-tuple $X \in ({\mathbb R}^d)^k$ is partitioned by a given set of $k$ $\Delta$-far balls ${\cal B} = \set{B_1,\ldots,B_k}$, if for every $i \in [k]$ it holds that $\size{X \cap B_i} = 1$. A multiset of $k$-tuples ${\cal T} \in (({\mathbb R}^d)^k)^*$ is \textbf{partitioned by} ${\cal B}$, if each $X \in {\cal T}$ is partitioned by ${\cal B}$. We say that ${\cal T}$ is \textbf{partitioned by $\Delta$-far balls} if such a set ${\cal B}$ of $k$ $\Delta$-far balls exists. \end{definition} In some cases we want to use a notion of a multiset ${\cal T}$ \emph{almost} partitioned by $\Delta$-far balls. This is defined below using the additional parameter $\ell$. \begin{definition}[$\ell$-nearly partitioned by $\Delta$-far balls] A multiset ${\cal T} \in (({\mathbb R}^d)^k)^*$ is \textbf{$\ell$-nearly partitioned by} a given set of $\Delta$-far balls ${\cal B} = \set{B_1,\ldots,B_k}$, if there are at most $\ell$ tuples in ${\cal T}$ that are not partitioned by ${\cal B}$. We say that ${\cal T}$ is \textbf{$\ell$-nearly partitioned by $\Delta$-far balls} if such a set of $\Delta$-far balls ${\cal B} = \set{B_1,\ldots,B_k}$ exists. \end{definition} For a database of $n$ $k$-tuples ${\cal T} \in (({\mathbb R}^d)^k)^*$, we let ${\rm Points}({\cal T})$ be the collection of all the points in all the $k$-tuples in ${\cal T}$. \begin{definition}[The points in a collection of $k$-tuples] For ${\cal T} = \set{\set{\px_{1,j}}_{j=1}^k,\ldots,\set{\px_{n,j}}_{j=1}^k} \in (({\mathbb R}^d)^k)^n$, we define ${\rm Points}({\cal T}) = \set{\px_{i,j}}_{i\in [n], j \in [k]} \in ({\mathbb R}^d)^{kn}$. \end{definition} The following proposition states that if ${\cal T}$ is partitioned by $\Delta$-far balls for $\Delta > 3$, then each choice of $\Delta$-far balls that partitions ${\cal T}$ induces the same partition. \begin{proposition}\label{prop:unique-partition} Let ${\cal T} \in (({\mathbb R}^d)^k)^*$ be a multiset that is partitioned by a set of $\Delta$-far balls ${\cal B} = \set{B_1,\ldots,B_k}$ for $\Delta > 3$. Then for every $k$-tuple $X = \set{\px_1,\ldots,\px_k} \in {\cal T}$ and for every $i \in [k]$, there exists a ball in ${\cal B}$ (call it $B_i$), such that ${\rm Points}({\cal T}) \cap B_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \px_j}}$. \end{proposition} \begin{proof} Let $X = \set{\px_1,\ldots,\px_k} \in {\cal T}$, and for every $i \in [k]$ let $B_i = B(\pc_i,r_i) \in {\cal B}$ be the ball that contains $\px_i$. We prove the proposition by showing that for every $i$ and every $\px \in {\rm Points}({\cal T}) \cap B_i$, it holds that $i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \px_j}$. In the following, fix $\px \in {\rm Points}({\cal T}) \cap B_i$. On the one hand, since $\px \in B_i$, it holds that $\norm{\px - \px_i} \leq r_i$. On the other hand, for any $j \neq i$ it holds that \begin{align*} \norm{\px - \px_j} \geq \norm{\pc_i - \pc_j} - \norm{\pc_i - \px} - \norm{\pc_j - \px_j} > 3\max\set{r_i,r_j} - r_i - r_j \geq r_i, \end{align*} where the strict inequality holds since $B_i,B_j$ are $\Delta$-far balls for $\Delta > 3$. Namely, we deduce that $\norm{\px - \px_i} < \norm{\px - \px_j}$, as required. \end{proof} \remove{ \ECnote{Perhaps there is even a simpler proof with $k$-tuples? Isn't it the case that in any partition to far balls, each point from one tuple is in the same ball with the closest point to it from each other tuple? Also, for this purpose it might be enough to use "4" instead of "6" in the far balls def (not sure what we need later).} \begin{proof} Fix a $k$-tuple $X = \set{\px_1,\ldots,\px_k} \in {\cal T}$, and let ${\cal P}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j}\norm{\px-\px_j}}$. The proof trivially holds for $k=1$. Therefore, in the following we assume that $k \geq 2$. Assume towards a contradiction that there exist $\px,\py \in {\rm Points}({\cal T})$ such that $\px, \py \in B_i = B(\pc_i,r_i)$ (i.e., belong to the same ball in ${\cal B}$) but $\px \in B_s' = B(\pc_s',r_s')$ and $\py \in B_{t}' = B(\pc_t',r_t')$ for $s \neq t$ (i.e., belong to different balls in ${\cal B}'$). We next fix $\pz \in \paren{B_{s}' \cup B_{t}'} \cap {\rm Points}({\cal T})$ and prove that $\pz \in B_i$ (see \cref{fig1}). \begin{figure}[htbp] \centerline{\includegraphics[scale=.2]{figure1.png}} \caption{An example of $\px,\py,\pz \in {\cal P}$ such that $\px, \py \in B_i$, $\px \in B_s'$, $\py \in B_{t}'$ and $\pz \in B_{s}' \cup B_{t}'$.} \label{fig1} \end{figure} \noindent Since both ${\cal B}$ and ${\cal B}'$ are sets of far balls, the assumptions yield that \begin{align*} 4 \max\set{r_s',r_t'} < \norm{\pc_s' - \pc_t'} - \norm{\px - \pc_s'} - \norm{\py - \pc_t'} < \norm{\px - \py} \leq 2 r_i. \end{align*} Therefore, it holds that \begin{align}\label{eq:pz-px-py} \min\set{\norm{\pz - \px}, \norm{\pz - \py}} \leq 2\max\set{r_s',r_t'} < r_i, \end{align} which yields that \begin{align}\label{eq:pz-pc_i} \norm{\pz - \pc_i} &\leq \min\set{\norm{\pz - \px} + \norm{\px - \pc_i}, \norm{\pz - \py} + \norm{\py - \pc_i}}\nonumber\\ &\leq \min\set{\norm{\pz - \px}, \norm{\pz - \py}} + r_i\nonumber\\ &< 2r_i, \end{align} where the second inequality holds since $\px,\py \in B_i$ and the last one by \cref{eq:pz-px-py}. Note that \cref{eq:pz-pc_i} immediately yields that $\pz \in B_i \cap {\rm Points}({\cal T})$ since ${\cal T}$ is partitioned by ${\cal B}$, and therefore, $\pz$ cannot belong to a different ball in ${\cal B}$ since it is too close to $\pc_i$. In summary, we proved that \begin{align}\label{eq:contain-two-balls} {\rm Points}({\cal T}) \cap \paren{B_{s}' \cup B_{t}'} \subseteq {\rm Points}({\cal T}) \cap B_i. \end{align} Now fix some $k$-tuple $\set{\px_1,\ldots,\px_k} \in {\cal T}$. Since ${\cal B}'$ partitions ${\cal T}$, there exists a permutation $\pi$ of $[k]$ such that $\px_{\pi(s)} \in B_{s}'$ and $\px_{\pi(t)} \in B_{t}'$. Therefore, we deduce by \cref{eq:contain-two-balls} that both $\px_{\pi(s)}$ and $\px_{\pi(t)}$ belong to the same ball $B_i$ in ${\cal B}$, in contradiction to the assumption that ${\cal B}$ partitions ${\cal T}$. \end{proof} } We now formally define the partition of a database ${\cal T} \in (({\mathbb R}^d)^k)^*$ which is partitioned by $\Delta$-far balls for $\Delta > 3$. \begin{definition}[${\rm Partition}({\cal T})$]\label{def:clusters-rel} Given a multiset ${\cal T} \in (({\mathbb R}^d)^k)^*$ which is partitioned by $\Delta$-far balls for $\Delta > 3$, we define the partition of ${\cal T}$, which we denote by ${\rm Partition}({\cal T}) = \set{{\cal P}_1,\ldots,{\cal P}_k}$, by fixing an (arbitrary) $k$-tuple $X = \set{\px_1,\ldots,\px_k} \in {\cal T}$ and setting ${\cal P}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \px_j}}$. \end{definition} By \cref{prop:unique-partition}, this partition is well defined (i.e., is independent of the choice of the $k$-tuple $X$). We now define the $k$-tuple clustering problem. \begin{definition}[$k$-tuple clustering]\label{def:ktupleclustering} The input to the problem is a database ${\cal T} \in (({\mathbb R}^d)^k)^n$ and a parameter $\Delta > 3$. The goal is to output a $k$-tuple $Y = \set{\py_1,\ldots,\py_k} \in ({\mathbb R}^d)^k$ such that the following holds: If ${\cal T}$ is partitioned by $\Delta$-far balls, then for every $i \in [k]$, there exists a cluster in ${\rm Partition}({\cal T})$ (call it ${\cal P}_i$) such that ${\cal P}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \py_j}}$. \end{definition} Namely, in the $k$-tuple clustering problem, the goal is to output a $k$-tuple $Y$ that partitions ${\cal T}$ correctly. We remark that without privacy, the problem is completely trivial, since any $k$-tuple $X \in {\cal T}$ is a good solution by definition. We also remark that for applications, we are also interested in the quality of the solution. Namely, how small is the distance between $\py_i$ and ${\cal P}_i$, compared to the other clusters in ${\rm Partition}({\cal T})$. This is captured in the following definition. \begin{definition}[good and good-averages solutions]\label{def:gamma-good} \Hnote{Better to separate the "goodness" and the requirement that all radii are at least some minimum value}\Enote{I'm not sure it's better} Let ${\cal T} \in (({\mathbb R}^d)^k)^n$ and $\alpha, r_{\min} \geq 0$. We say that a $k$-tuple $Y = \set{\py_1,\ldots,\py_k} \in ({\mathbb R}^d)^k$ is an \emph{$(\alpha,r_{\min})$-good solution} for clustering ${\cal T}$, if there exists a set of $\Delta$-far balls (for $\Delta > 3$) ${\cal B} = \set{B_i = B(\pc_i,r_i)}_{i=1}^k$ that partitions ${\cal T}$ such that for every $i \in [k]$ it holds that \begin{align*} \norm{\py_i - \pc_i} \leq \alpha \cdot \max\set{r_i,r_{\min}} \end{align*} If such ${\cal B}$ exists with $r_i \geq r_{\min}$ for every $i \in [k]$, we say that $Y$ is an \emph{$\alpha$-good-average} solution.\Hnote{How does this relate to average ? it is also still related to $r_{\min}$} In a special case where such set of balls exists for $\pc_i = {\rm Avg}({\cal P}_i)$ where $\set{{\cal P}_1,\ldots,{\cal P}_k} = {\rm Partition}({\cal P})$, we say that $Y$ is an \emph{$(\alpha,r_{\min})$-good-averages} solution \end{definition} We remark that the additional parameter $r_{\min}$ is usually needed when considering differentially private algorithms, even for simpler problems like estimating the average of points (e.g., see \cref{prop:approx-aver-Rd}). In addition, note that the quality of the solution is measured by how small is $\alpha$. The following claim states that if ${\cal T}$ is partitioned by $\Delta$-far balls for $\Delta > 3$, then any $\alpha$-good solution according to \cref{def:gamma-good} for $\alpha < \Delta/2 - 1$ is also a $k$-tuples clustering solution according to \cref{def:ktupleclustering}. \begin{claim}\label{claim:good-sol-is-valid} If ${\cal T} \in (({\mathbb R}^d)^k)^n$ is partitioned by $\Delta$-far balls for $\Delta > 3$, and $Y \in ({\mathbb R}^d)^k$ is an $\alpha$-good solution for clustering ${\cal T}$ for $\alpha < \Delta/2 - 1$, then for every $i \in [k]$, there exists a cluster in ${\rm Partition}({\cal T})$ (call it ${\cal P}_i$) such that ${\cal P}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \py_j}}$. \end{claim} \begin{proof} Since $Y$ is an $\alpha$-good solution, there exists a set of $\Delta$-far balls ${\cal B} = \set{B_i = B(\pc_i,r_i)}_{i=1}^k$ such that for every $i \in [k]$ it holds that \begin{align*} \norm{\py_i - \pc_i} \leq \alpha \cdot r_i. \end{align*} Now denote by ${\cal P}_i$ the cluster ${\rm Points}({\cal T}) \cap B_i \in {\rm Partition}({\cal T})$. It remains to prove that for every $\px \in {\cal P}_i$ and $j \neq i$ it holds that $\norm{\px - \py_i} < \norm{\px - \py_j}$. In the following, fix such $\px$ and $j$. On the one hand, it holds that \begin{align*} \norm{\px - \py_i} \leq \norm{\px - \pc_i} + \norm{\py_i - \pc_i} \leq (1 + \alpha) r_i. \end{align*} On the other hand, we have \begin{align*} \norm{\px - \py_j} \geq \norm{\pc_i - \pc_j} - \norm{\px-\pc_i} - \norm{\py_j - \pc_j} \geq \Delta \cdot \max\set{r_i,r_j} - r_i - \alpha \cdot r_j \geq (\Delta - 1 - \alpha) r_i. \end{align*} Hence, we conclude that $\norm{\px - \py_i} < \norm{\px - \py_j}$ whenever $\alpha < \Delta/2 - 1$, as required. \end{proof} For applications, we focus on a specific type of algorithms for the $k$-tuple clustering problems, that outputs a good-averages solution. \begin{definition}[averages-estimator for $k$-tuple clustering]\label{def:averages-estimator} Let $\mathsf{A}$ be an algorithm that gets as input a database in $(({\mathbb R}^d)^k)^*$. We say that $\mathsf{A}$ is an \emph{$(n,\alpha,r_{\min},\beta,\Delta,\Lambda)$-averages-estimator\Hnote{I do not think these carrying all these parameters all the time is good. You can fix n to denote the size of the dataset and the diameter of the domain maybe even $\Delta$. Do it once and don't carry them in the notation if the are fixed throughout} for $k$-tuple clustering}, if for every ${\cal T} \in (B(\pt{0},\Lambda)^k)^n \subseteq (({\mathbb R}^d)^k)^n$ that is partitioned by $\Delta$-far balls, $\mathsf{A}({\cal T})$ outputs w.p. $1-\beta$ an $(\alpha,r_{\min})$-good-averages solution $Y \in ({\mathbb R}^d)^k$ for clustering ${\cal T}$. \end{definition} Note that we allow the algorithm to handle only tuples over $B(\pt{0},\Lambda)$. If the algorithm can handle arbitrary tuples over ${\mathbb R}^d$, we omit the last parameter $\Lambda$. \subsection{Additional Facts} In this section we prove some facts about $\Delta$-far balls for $\Delta > 6$. The following proposition states that if ${\cal B}=\set{B_i}_{i=1}^k$ and ${\cal B}' = \set{B_i'}_{i=1}^k$ are two sets of $\Delta$-far balls for $\Delta > 6$, and $\px$ is a point that belongs to either $B_i$ or $B_i'$ for some $i \in [k]$, such that $B_i$ and $B_i'$ intersect each other, then the center of $B_i$ is closest to $\px$ among all the centers of all the balls in ${\cal B}$ (and the same holds w.r.t. $B_i'$ and ${\cal B}'$). \begin{proposition}\label{prop:close-sets-of-far-balls} Let ${\cal B} = \set{B_i = B(\pc_i,r_i)}_{i=1}^k$ and ${\cal B}' = \set{B_i' = B(\pc_i',r_i')}_{i=1}^k$ be two sets of $\Delta$-far balls for $\Delta > 6$ s.t. for every $i \in [k]$ it holds that $B_i \cap B_i' \neq \emptyset$. Then for every $i \in [k]$ and every $\px \in B_i \cup B_i'$, it holds that $i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \pc_j}$. \end{proposition} \begin{proof} Fix $i \in [k]$ and $\px \in B_i \cup B_i'$. If $\px \in B_i$, the proof trivially follows. Therefore, in the following we assume that $\px \notin B_i$, and therefore, $\px \in B_i'$. Note that on the one hand, it holds that \begin{align}\label{eq:upbound-px-pc_i} \norm{\px - \pc_i} \leq \norm{\px - \pc_i'} + \norm{\pc_i' - \pc_i} \leq r_i' + (r_i + r_i') = 2r_i' + r_i \end{align} On the other hand, fix $j \neq i$, and note that \begin{align}\label{eq:lowbound-px-pc_j-1} \norm{\px - \pc_j} &\geq \norm{\pc_i - \pc_j} - \norm{\px - \pc_i}\\ &> 6\max\set{r_i,r_j} - (2r_i' + r_i)\nonumber\\ &\geq 5\max\set{r_i,r_j} - 2r_i',\nonumber \end{align} where the second inequality holds by \cref{eq:upbound-px-pc_i} along with the fact that ${\cal B}$ are $\Delta$-far balls for $\Delta > 6$. Therefore, if $\max\set{r_i,r_j} \geq r_i'$, we deduce by \cref{eq:upbound-px-pc_i,eq:lowbound-px-pc_j-1} that $\norm{\px - \pc_i} < \norm{\px - \pc_j}$. Otherwise (i.e., $\max\set{r_i,r_j} < r_i'$), note that \begin{align}\label{eq:lowbound-px-pc_j-2} \norm{\px - \pc_j} &\geq \norm{\pc_i' - \pc_j'} - \norm{\px - \pc_i'} - \norm{\pc_j' - \pc_j}\\ &> 6\max\set{r_i',r_j'} - r_i' - (r_i' + r_i)\nonumber\\ &> 3r_i'.\nonumber \end{align} Hence, we deduce by \cref{eq:upbound-px-pc_i,eq:lowbound-px-pc_j-2} that $\norm{\px - \pc_i} < \norm{\px - \pc_j}$ also in this case, which concludes the proof of the proposition. \end{proof} We next prove that if ${\cal T}$ is partitioned by $\Delta$-far balls for $\Delta > 6$, and ${\cal B}$, a set of $\Delta$-far balls, partitions at least one tuple in ${\cal T}$, then by partitioning the points in ${\rm Points}({\cal T})$ w.r.t. the centers of the balls in ${\cal B}$, we obtain exactly ${\rm Partition}({\cal T})$. \begin{proposition}\label{prop:from-almost-par-to-evenly-par} Let ${\cal T} \in (({\mathbb R}^d)^k)^n$ be a multiset that is partitioned by $\Delta$-far balls for $\Delta > 6$, let ${\cal B} = \set{B_1,\ldots,B_k}$ be a set of $\Delta$-far balls that partitions at least one $k$-tuple of ${\cal T}$, and let $\pc_1,\ldots,\pc_k$ be the centers of $B_1,\ldots,B_k$, respectively. In addition, for every $i \in [k]$ let ${\cal Q}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \pc_j}}$. Then $\set{{\cal Q}_1,\ldots,{\cal Q}_k} = {\rm Partition}({\cal T})$. \end{proposition} \begin{proof} Let $X = \set{\px_1,\ldots,\px_k} \in {\cal T}$ be the assumed $k$-tuple that is partitioned by ${\cal B}$, let ${\cal B}^* = \set{B_1^*,\ldots,B_k^*}$ be a set of $\Delta$-far balls that partitions (all of) ${\cal T}$, and assume w.l.o.g. that $\px_i \in B_i \cap B_i^*$ for every $i \in [k]$. \cref{prop:close-sets-of-far-balls} yields that for every $i \in [k]$ and $\px \in B_i^*$ it holds that $\px \in {\cal Q}_i$, yielding that $B_i^* \cap {\rm Points}({\cal T}) \subseteq {\cal Q}_i$. Since both sets $\set{B_i^*}_{i=1}^k$ and $\set{{\cal Q}_i}_{i=1}^k$ consist of disjoints sets that cover all the points in ${\rm Points}({\cal T})$, we conclude that $\set{{\cal Q}_1,\ldots,{\cal Q}_k} = {\rm Partition}({\cal T})$. \end{proof} \remove{ In the following we describe a simple algorithm $\Algg{\rm BBBBBBBBBBBBBBBB}$ that takes a multiset ${\cal T} \in (({\mathbb R}^d)^k)^n$ and distinguishes between the case that ${\cal T}$ is partitioned by \textbf{very} far balls, and the case that ${\cal T}$ is \textbf{not} partitioned by $k$ far balls. In the former case it also outputs a set of $k$ far balls that partitions ${\cal T}$. The algorithm is described in \cref{fig:IsPartitioned}. \begin{figure}[thb!] \begin{center} \noindent\fbox{ \parbox{.95\columnwidth}{ \begin{center}{ \bf Algorithm $\Algg{\rm IsWeaklyPartitioned}$}\end{center} \textbf{Input:} A multiset ${\cal T} \in (({\mathbb R}^d)^k)^*$. \begin{enumerate} \item Choose an arbitrary tuple $(\px_1,\ldots,\px_k) \in {\cal T}$, and initialize ${\cal T}_1,\ldots,{\cal T}_k = \emptyset$. \item For $(\px_1',\ldots,\px_k') \in {\cal T}$:\label{step:for-loop-tuple} \begin{enumerate} \item For $i=1$ to $k$:\label{step:for-loop-i} \begin{enumerate} \item Define $\pi(i) = \operatorname*{argmin}_{j \in [k]} \norm{\px_i - \px_j'}$. \item ${\cal T}_i = {\cal T}_i \cup \set{\px_{\pi(i)}'}$ (a multiset union). \end{enumerate} \item If $\pi$ is not a permutation of $[k]$, output $(\text{``NO''},\perp)$. \end{enumerate} \item Output $(\text{``YES''},(\px_1,\ldots,\px_k))$. \end{enumerate} }} \end{center} \caption{A non-private algorithm that tests whether ${\cal T}$ can be partitioned.\label{fig:IsPartitioned}} \end{figure} The following proposition summarizes the properties of $\Algg{\rm BBBBBBBBBBBBBBBB}$. \def\propIsPartitioned{ On inputs ${\cal T} \in (({\mathbb R}^d)^k)^n$, Algorithm $\Algg{\rm BBBBBBBBBBBBBBBB}$ satisfies the following guarantees: \begin{itemize} \item If ${\cal T}$ is partitioned by \textbf{very} far balls, then the algorithm outputs $(\text{``YES''},{\cal B})$ where ${\cal B}$ is a set of $k$ far balls that partitions ${\cal T}$. \item If ${\cal T}$ is \textbf{not} partitioned by far balls, then the algorithm outputs $(\text{``NO''},\perp)$. \end{itemize} The algorithm runs in time $O(d n k^2)$. } \begin{proposition}\label{prop:IsPartitioned} \propIsPartitioned \end{proposition} \begin{proof} Consider an execution of $\Algg{\rm BBBBBBBBBBBBBBBB}({\cal T})$. If ${\cal T}$ is \textbf{not} partitioned by far balls, then by definition, the output of the execution is $(\text{``NO''},\perp)$. In the rest of the analysis we assume that ${\cal P}$ is partitioned by $k$ \textbf{very} far balls. By construction, the resulting multisets $\set{{\cal T}_1,\ldots,{\cal T}_k}$ in the for-loop (Step~\ref{step:for-loop-tuple}) are exactly ${\rm Partition}({\cal T})$. Let ${\cal B} = \set{B_i = B(\px_i, r_i)}_{i=1}^k$ be the set of $k$ balls from Step~\ref{step:resulting-balls}, and let ${\cal B}^* = \set{B_i^* = B(\px_i^*, r_i^*)}_{i=1}^k$ be a set of $k$ \textbf{very} far balls that partitions ${\cal T}$. The proof of the proposition now follows since for every $i \neq j$ it holds that \begin{align*} \norm{\px_i - \px_j} &\geq \norm{\px_i^* - \px_j^*} - \norm{\px_i - \px_i^*} - \norm{\px_j - \px_j^*}\\ &> 14 \max\set{r_i^*,r_j^*} - r_i^* - r_j^*\\ &\geq 12 \max\set{r_i^*,r_j^*}\\ &\geq 6 \max\set{r_i,r_j}, \end{align*} where the last inequality holds since $r_i \leq 2 r_i^*$ and $r_j \leq 2 r_j^*$ by construction. \end{proof} } \section{Preliminaries} \subsection{Notation} In this work, a $k$-tuple $X = \set{\px_1,\ldots,\px_k}$ is an \emph{unordered} set of $k$ vectors $\px_i \in {\mathbb R}^d$. For $\px \in {\mathbb R}^d$, we denote by $\norm{\px}$ the $\ell_2$ norm of $\px$. For $\pc \in {\mathbb R}^d$ and $r > 0$, we denote $B(\pc,r) := \set{\px \in {\mathbb R}^d \colon \norm{\px - \pc} \leq r}$. For a multiset ${\cal P} \in ({\mathbb R}^d)^*$ we denote by ${\rm Avg}({\cal P}) := \frac1{\size{{\cal P}}}\cdot \sum_{\px \in {\cal P}} \px$ the average of all points in ${\cal P}$. Throughout this work, a database ${\cal D}$ is a multiset. For two multisets ${\cal D} = \set{x_1,\ldots,x_n}$ and ${\cal D}' = \set{x_1',\ldots,x_m'}$, we let ${\cal D} \cup {\cal D}'$ be the multiset $\set{x_1,\ldots,x_n,x_1',\ldots,x_m'}$. For a multiset ${\cal D} = \set{x_1,\ldots,x_n}$ and a set $S$, we let ${\cal D} \cap S$ be the multiset $\set{x_i}_{i \in {\cal I}}$ where ${\cal I} = \set{i \in [n] \colon x_i \in S}$. All logarithms considered here are natural logarithms (i.e., in base $e$). \subsection{Indistinguishability and Differential Privacy} \begin{definition}[Neighboring databases]\label{def:neighboring} Let ${\cal D} = \set{x_1,\ldots,x_n}$ and ${\cal D}' = \set{x_1',\ldots,x_n'}$ be two databases over a domain ${\cal X}$. We say that ${\cal D}$ and ${\cal D}'$ are \textbf{neighboring} if there is exactly one index $i \in [n]$ with $x_i \neq x_i'$. \end{definition} \begin{definition}[$(\varepsilon,\delta)$-indistinguishable]\label{def:indis} Two random variable $X,X'$ over a domain ${\cal X}$ are called $(\varepsilon,\delta)$-indistinguishable, iff for any event $T \subseteq {\cal X}$, it holds that $\pr{X \in T} \leq e^{\varepsilon} \cdot \pr{X' \in T} + \delta$. If $\delta = 0$, we say that $X$ and $X'$ are $\varepsilon$-indistinguishable \end{definition} \begin{definition}[$(\varepsilon,\delta)$-differential privacy \cite{DworkMNS06}]\label{def:DP} An algorithm $\cA$ is called $(\varepsilon,\delta)$-differentially private, if for any two neighboring databases ${\cal D},{\cal D}'$ it holds that $\cA({\cal D})$ and $\cA({\cal D}')$ are $(\varepsilon,\delta)$-indistinguishable. If $\delta = 0$ (i.e., pure privacy), we say that $\cA$ is $\varepsilon$-differentially private. \end{definition} \begin{lemma}[\cite{BS16}]\label{lem:indis} Two random variable $X,X'$ over a domain ${\cal X}$ are $(\varepsilon,\delta)$-indistinguishable, iff there exist events $E, E' \subseteq {\cal X}$ with $\pr{X \in E},\pr{X' \in E'} \geq 1-\delta$ such that $X|_{E}$ and $X'|_{E'}$ are $\varepsilon$-indistinguishable. \end{lemma} \subsubsection{Basic Facts} The following fact is a corollary of \cref{lem:indis}. \begin{fact}\label{fact:indis-cor} Let $X,X'$ be two random variables over a domain ${\cal X}$, and let $E, E' \subseteq {\cal X}$ be two events. If $X|_E$ and $X'|_{E'}$ are $(\varepsilon,\delta_1)$-indistinguishable and $\pr{X \in E},\pr{X' \in E'} \geq 1 - \delta_2$, then $X$ and $X'$ are $(\varepsilon,\delta_1 + \delta_2)$-indistinguishable. \end{fact} \begin{proof} Since $X|_E$ and $X'|_{E'}$ are $(\varepsilon,\delta_1)$-indistinguishable, we deduce by \cref{lem:indis} that there exists events $F \subseteq E$ and $F' \subseteq E'$ with $\pr{X \in F \mid E}, \pr{X' \in F' \mid E'} \geq 1-\delta_1$ such that $X|_F$ and $X'|_{F'}$ are $(\varepsilon,0)$-indistinguishable. In addition, note that \begin{align*} \pr{X \in F} = \pr{X \in E}\cdot \pr{X \in F \mid E} \geq (1-\delta_2)(1-\delta_1) \geq 1 - (\delta_1 + \delta_2). \end{align*} Similarly, it holds that $ \pr{X' \in F'} \geq 1 - (\delta_1 + \delta_2)$. Therefore, by applying the opposite direction of \cref{lem:indis} on the events $F$ and $F'$, we deduce that $X$ and $X'$ are $(\varepsilon, \delta_1 + \delta_2)$-indistinguishable. \end{proof} In addition, we use the following facts. \begin{fact}\label{fact:conditioning} Let $X,X'$ be two $\varepsilon$-indistinguishable random variables over a domain ${\cal X}$, and let $E, E' \subseteq {\cal X}$ be two events with $\pr{X \in E},\pr{X' \in E'} \geq 1-\delta$. Then $X|_{E}$ and $X'|_{E'}$ are $(\varepsilon - \ln(1-\delta), \: \frac{e^{\varepsilon} \delta }{1-\delta})$-indistinguishable. \end{fact} \begin{proof} Fix a subset $T \subseteq {\cal X}$ and compute \begin{align*} \pr{X \in T \mid E} \leq \frac{\pr{X \in T }}{\pr{E}} \leq \frac{e^{\varepsilon} \cdot \pr{X' \in T}}{1-\delta} &\leq \frac{e^{\varepsilon}}{1-\delta} \cdot \paren{\pr{X' \in T \mid E'} + \pr{X' \notin E'}}\\ &\leq e^{\varepsilon -\ln(1-\delta)} \cdot \pr{X' \in T \mid E'} + \frac{e^{\varepsilon} \delta}{1-\delta} \end{align*} where the last inequality holds since $\pr{X' \notin E'} \leq \delta$ by assumption. \end{proof} \begin{fact}\label{prop:similar-E} Let $X,X'$ be two random variables over a domain ${\cal X}$. Assume there exist events $E,E' \subseteq {\cal X}$ such that the following holds: \begin{itemize} \item $\pr{X \in E} \in e^{\pm \varepsilon}\cdot \pr{X' \in E'}$, and \item $X|_{E}$ and $X'|_{E'}$ are $(\varepsilon^*,\delta)$-indistinguishable, and \item $X|_{\neg E}$ and $X'|_{\neg E'}$ are $(\varepsilon^*,\delta)$-indistinguishable. \end{itemize} Then $X,X'$ are $(\varepsilon + \varepsilon^*,\delta e^{\varepsilon})$-indistinguishable. \end{fact} \begin{proof} Fix an event $T \subseteq {\cal X}$ and compute \begin{align*} \lefteqn{\pr{X \in T} = \pr{X \in T \mid E}\cdot \pr{X \in E} + \pr{X \in T \mid \neg E}\cdot \pr{X \notin E}}\\ &\leq \paren{e^{\varepsilon^*}\cdot \pr{X' \in T \mid E'} + \delta}\cdot e^{\varepsilon}\cdot \pr{X' \in E'} + \paren{e^{\varepsilon^*}\cdot \pr{X' \in T \mid \neg E'} + \delta}\cdot e^{\varepsilon}\cdot \pr{X' \notin E'}\\ &= e^{\varepsilon + \varepsilon^*} \cdot \pr{X' \in T} + \delta e^{\varepsilon}. \end{align*} \end{proof} \subsubsection{Group Privacy and Post-Processing} \begin{fact}[Group Privacy]\label{fact:group-priv} If $\cA$ is $(\varepsilon,\delta)$-differentially private, then for all pairs of databases ${\cal S}$ and ${\cal S}'$ that differ by $k$ points it holds that $\cA({\cal S})$ and $\cA({\cal S}')$ are $(k\varepsilon, k e^{k\varepsilon} \delta)$-indistinguishable. \end{fact} \begin{fact}[Post-processing]\label{fact:post-processing} If $\cA$ is $(\varepsilon,\delta)$-differentially private, then for every (randomized) function $F$ it holds that $F \circ \cA$ is $(\varepsilon,\delta)$-differentially private. \end{fact} \subsubsection{Composition} \begin{theorem}[Basic composition, adaptive case \cite{DRV10}]\label{thm:composition1} If $\cA_1$ and $\cA_2$ satisfy $(\varepsilon_1,\delta_1)$ and $(\varepsilon_2,\delta_2)$ differential privacy (respectively), then any algorithm that adaptively uses $\cA_1$ and $\cA_2$ (and does not access the database otherwise) ensures $(\varepsilon_1+\varepsilon_2,\delta_1+\delta_2)$-differential privacy. \end{theorem} \begin{theorem}[Advanced composition~\cite{DRV10}]\label{thm:composition2} Let $0<\varepsilon_0,\delta'\leq1$, and let $\delta_0\in[0,1]$. An algorithm that adaptively uses $k$ algorithms that preserve $(\varepsilon_0,\delta_0)$-differential privacy (and does not access the database otherwise) ensures $(\varepsilon,\delta)$-differential privacy, where $\varepsilon=\sqrt{2k\ln(1/\delta')}\cdot\varepsilon_0+2k\varepsilon_0^2$ and $\delta = k\delta_0+\delta'$. \end{theorem} \subsubsection{The Laplace Mechanism} \begin{definition}[Laplace distribution] For $\sigma \geq 0$, let ${\rm Lap}(\sigma)$ be the Laplace distribution over ${\mathbb R}$ with probability density function $p(z) = \frac1{2 \sigma} \exp\paren{-\frac{\size{z}}{\sigma}}$. \end{definition} \begin{fact}\label{fact:laplace-concent} Let $\varepsilon > 0$. If $X \sim {\rm Lap}(1/\varepsilon)$ then for all $t > 0: \quad \pr{\size{X} > t/\varepsilon} \leq e^{-t}$. \end{fact} \begin{definition}[Sensitivity] We say that a function $f \colon {\cal U}^n \rightarrow {\mathbb R}$ has sensitivity $\lambda$ if for all neigboring databases ${\cal S}, {\cal S}'$ it holds that $\size{f({\cal S}) - f({\cal S}')} \leq \lambda$. \end{definition} \begin{theorem}[The Laplace Mechanism \cite{DworkMNS06}]\label{fact:laplace} Let $\varepsilon > 0$, and assume $f \colon {\cal U}^n \rightarrow {\mathbb R}$ has sensitivity $\lambda$. Then the mechanism that on input ${\cal S} \in {\cal U}^n$ outputs $f({\cal S}) + {\rm Lap}(\lambda/\varepsilon)$ is $\varepsilon$-differentially private. \end{theorem} \subsubsection{The Gaussian Mechanism} \begin{definition}[Gaussian distribution] For $\mu \in {\mathbb R}$ and $\sigma \geq 0$, let ${\cal N}(\mu,\sigma^2)$ be the Gaussian distribution over ${\mathbb R}$ with probability density function $p(z) = \frac1{\sqrt{2\pi}} \exp\paren{-\frac{(z-\mu)^2}{2 \sigma^2}}$. \end{definition} \begin{fact}\label{fact:one-gaus-concent} Let $\pX = (X_1,\ldots,X_d)$, where the $X_i$'s are i.i.d. random variables, distributed according to $ {\cal N}(0,\sigma^2)$. Then for all $\beta > 0: \quad \pr{\norm{\pX} \leq \paren{\sqrt{d} + \sqrt{2 \log(1/\beta)}} \cdot \sigma} \geq 1-\beta$. \end{fact} \begin{definition}[$\ell_2$-sensitivity] We say that a function $f \colon {\cal U}^n \rightarrow {\mathbb R}^d$ has $\ell_2$-sensitivity $\lambda$ if for all neigboring databases ${\cal S}, {\cal S}'$ it holds that $\norm{f({\cal S}) - f({\cal S}')} \leq \lambda$. \end{definition} \begin{theorem}[The Gaussian Mechanism \cite{DKMMN06}]\label{fact:Gaus} Let $\varepsilon,\delta \in (0,1)$, and assume $f \colon {\cal U}^n \rightarrow {\mathbb R}^d$ has $\ell_2$-sensitivity $\lambda$. Let $\sigma \geq \frac{\lambda}{\varepsilon}\sqrt{2 \log(1.25/\delta)}$. Then the mechanism that on input ${\cal S} \in {\cal U}^n$ outputs $f({\cal S}) + \paren{{\cal N}(0,\sigma^2)}^d$ is $(\varepsilon,\delta)$-differentially private. \end{theorem} \begin{observation}\label{obs:Gaus-aver} For the case that ${\cal S} \in ({\mathbb R}^d)^n$ and $f({\cal S}) = {\rm Avg}({\cal S})$, if we are promised that each coordinate of the points is bounded by a segment of length $\Lambda$, then the sensitivity is bounded by $\lambda = \Lambda/n$, and therefore, by taking $\sigma = O(\frac{\Lambda}{\varepsilon n} \sqrt{\log(1/\delta)})$ we get by \cref{fact:one-gaus-concent} that with probability $1-\beta$, the resulting point $\pz$ of the mechanism satisfies $\norm{\pz - {\rm Avg}({\cal S})} \leq \frac{\Lambda \sqrt{\log(1.25/\delta)}}{\varepsilon n} \paren{\sqrt{d} + \sqrt{2\log(1/\beta)}}$. \end{observation} \begin{remark}\label{remark:Gaus-add-del} \cref{fact:Gaus} guarantees differential-privacy whenever two neighboring databases have equal size. However, it can be easily extended to a more general case in which the privacy guarantee also holds in cases of addition and deletion of a point, with essentially the same noise magnitude (e.g., see Appendix A in \cite{NSV16}). \end{remark} The following proposition states the following: Assume that $\pX \sim \mu + ({\cal N}(0,\sigma^2))^d$ for some $\mu \in {\mathbb R}^d$, and let $\py \in {\mathbb R}^d$ such that $\norm{\py - \mu}$ is ``large enough'' (i.e., larger than $\Omega\paren{\sigma \sqrt{\log(1/\beta)}}$). Then with probability $1-\beta$ (over $\pX$) it holds that $\norm{\pX - \mu} < \norm{\pX - \py}$. Note that such an argument is trivial when $\norm{\py - \mu}$ is at least $\Omega(\sigma \sqrt{d \log(1/\beta)})$, but here we are aiming for a distance that is independent of $d$. The proof of the proposition, which appears at \cref{missing-proof:thm:kGauss-utility} as a special case of \cref{prop:separation}, is based on a standard projection argument. \begin{proposition}\label{prop:separation-spherical-case} Let $\pX \sim \mu + ({\cal N}(0,\sigma^2))^d$ and let $\py \in {\mathbb R}^d$ with $\norm{\py - \mu} > 2\sqrt{2\log\paren{\frac1{\beta}}} \cdot \sigma$. Then with probability $1-\beta$ (over the choice of $\pX$), it holds that $\norm{\pX - \mu} < \norm{\pX-\py}$. \end{proposition} \subsubsection{Estimating the Average of Points}\label{sec:prelim:est-aver} As mentioned in \cref{obs:Gaus-aver}, the Gaussian mechanism (\cref{fact:Gaus}) allows for privately estimating the average of points in $B(\pt{0},\Lambda) \subseteq {\mathbb R}^d$ within $\ell_2$ error of $\approx \frac{\Lambda \sqrt{d}}{\varepsilon n}$. In some cases, we could relax the dependency on $\Lambda$. For example, using the following proposition. \def\propEstAvgInRd{ Let $\varepsilon \in (0,1)$, $d, \Lambda > 0$ and let $r_{\min} \in [0,\Lambda]$. There exists an efficient $(\varepsilon,\delta)$-differentially private algorithm that takes an $n$-size database ${\cal S}$ of points inside the ball $B(\pt{0},\Lambda)$ in ${\mathbb R}^d$ and satisfy the following utility guarantee: Assume that $n \geq \frac{32\sqrt{2d \log(2/\delta)}}{\varepsilon} \log\paren{\frac{4d\Lambda}{r_{\min} \beta}} + 4$, and let $r >0$ be the minimal radius of a $d$-dimensional ball that contains all points in ${\cal S}$. Then with probability $1-\beta$, the algorithm outputs $\hpa \in {\mathbb R}^d$ such that \begin{align*} \norm{\hpa - {\rm Avg}({\cal S})} \leq O\paren{\max\set{r,r_{\min}}\cdot \frac{d \sqrt{\log(1/\delta)}}{\varepsilon n} \paren{\sqrt{\log(d/\delta) \log(d/\beta)} + \log \paren{\frac{\Lambda d}{r_{\min} \beta}}}}. \end{align*} The algorithm runs in time $\tilde{O}(d n)$ (ignoring logarithmic factors). } \begin{proposition}[Estimating the Average of Bounded Points in ${\mathbb R}^d$]\label{prop:approx-aver-Rd} \propEstAvgInRd \end{proposition} \cref{prop:approx-aver-Rd} can be seen as a simplified variant of \cite{NSV16}'s private average algorithm. The main difference is that \cite{NSV16} first uses the Johnson Lindenstrauss (JL) transform \cite{JL84} to randomly embed the input points in ${\mathbb R}^{d'}$ for $d' \approx \log n$, and then estimates the average of the points in each axis of ${\mathbb R}^{d'}$. As a result, they manage to save a factor of $\sqrt{d}$ upon \cref{prop:approx-aver-Rd} (at the cost of paying a factor of $\log n$ instead). However, for simplifying the construction and the implementation, we chose to omit the JL transform step, and we directly estimate the average along each axis of ${\mathbb R}^{d}$. For completeness, we present the full details of \cref{prop:approx-aver-Rd} in \cref{sec:approx-aver}. \Enote{maybe mention other methods like CoinPress, KV, etc, that are developed for Gaussians, but can be used here as well.} \subsubsection{Sub-Sampling} \begin{lemma}[\cite{BKN10,KLNRS11}]\label{lem:subsampling} Let ${\cal A}$ be an $(\varepsilon^*,\delta^*)$-differentially private algorithm operating on databases of size $m$. Fix $\varepsilon \leq 1$, and denote $n = \frac{m}{\varepsilon}(3 + \exp(\varepsilon^*))$. Construct an algorithm ${\cal B}$ that on an input database ${\cal D} = (z_i)_{i=1}^n$, uniformly at random selects a subset ${\cal I} \subseteq [n]$ of size $m$, and executes ${\cal A}$ on the multiset ${\cal D}_{{\cal I}} = (z_i)_{i \in {\cal I}}$. Then ${\cal B}$ is $(\varepsilon,\delta)$-differentially private, where $\delta = \frac{n}{4m}\cdot \delta^*$. \end{lemma} The following lemma states that switching between sampling with replacement and without replacement has only a small effect on privacy. \begin{lemma}[\cite{BNSV15}]\label{lem:DP-with-replacement} Fix $\varepsilon \leq 1$ and let ${\cal A}$ be an $(\varepsilon,\delta)$-differentially private algorithm operating on databases of size $m$. For $n \geq 2m$, construct an algorithm ${\cal A}'$ that on input a database ${\cal D}$ of size $n$, subsamples (with replacement) $m$ rows from ${\cal D}$, and runs ${\cal A}$ on the result. Then ${\cal A}'$ is $(\varepsilon',\delta')$-differentially private for $\varepsilon' = 6 \varepsilon m/n$ and $\delta' = \exp\paren{6 \varepsilon m/n} \cdot \frac{4m}{n}\cdot \delta$. \end{lemma} \remove{ \subsection{Preliminaries from Learning Theory} A concept $c:{\cal X}\rightarrow \{0,1\}$ is a predicate that labels {\em examples} taken from the domain ${\cal X}$ by either 0 or 1. A \emph{concept class} ${\cal C}$ over ${\cal X}$ is a set of concepts (predicates) mapping ${\cal X}$ to $\{0,1\}$. \begin{definition}[VC dimension] Let ${\cal C}$ be a concept class over ${\cal X}$ and let ${\cal S} = \set{x_1,\ldots,x_m} \subseteq {\cal X}$. We say that ${\cal S}$ is shattered by ${\cal C}$ if $\size{\set{(c(x_1),\ldots,c(x_m)) \colon c \in {\cal C}}} = 2^m$. The VC dimension of ${\cal C}$, which is denoted by ${\rm VC}({\cal C})$, is the maximal size of a set ${\cal S}$ that is shattered by ${\cal C}$. \end{definition} \begin{theorem}[VC bounds \cite{VC}]\label{thm:vc-bounds} Let ${\cal H} = \set{h \colon {\cal X} \rightarrow \set{0,1}}$ be a concept class, let $c \colon {\cal X} \rightarrow \set{0,1}$ be a function, let $\mu$ be a distribution over ${\cal X}$ and let ${\cal S}$ be a set of $m$ i.i.d. samples from $\mu$. Then with probability $1-\delta$ (over the choice of ${\cal S}$), for any $h \in {\cal H}$ with ${\rm error}_{{\cal S}}(c,h) = \ppr{x \gets {\cal S}}{h(x) \neq c(x)} = 0$ (realizable case) it holds that \begin{align*} {\rm error}_{\mu}(c,h) \leq \frac{8 {\rm VC}({\cal H}) \log \frac{2m}{{\rm VC}({\cal H})} + 4\log \frac{4}{\delta}}{m} \end{align*} where ${\rm error}_{\mu}(c,h) = \ppr{x \sim \mu}{h(x) \neq c(x)}$. In general (agnostic case), with probability $1-\delta$, for every $h \in {\cal H}$ it holds that \begin{align*} {\rm error}_{\mu}(c,h) \leq {\rm error}_{{\cal S}}(c,h) + \sqrt{\frac{{\rm VC}({\cal H})\paren{\log \frac{2m}{{\rm VC}({\cal H})}+1}+ \log \frac{4}{\delta}}{m}}, \end{align*} \end{theorem} In the following, fix a parameter $d \in {\mathbb N}$ and let $\cC_{\text{ball}}$ be the class of all $d$-dimensional balls in ${\mathbb R}^d$. Namely, $\cC_{\text{ball}} = \set{h_{\pt{c},r} \colon {\mathbb R}^d \rightarrow \set{0,1}}_{\pc \in {\mathbb R}^d, r \geq 0}$, where $h_{\pt{c},r}(\px) = 1 \iff \px \in B(\pc,r)$. \begin{fact}[\cite{Dud79}]\label{fact:vc-of-ball} The VC-dimension of $\cC_{\text{ball}}$ is $d+1$. \end{fact} \begin{fact}[\cite{BlumerEhHaWa89}]\label{fact:k-fold} For any concept class ${\cal C}$, the VC-dimension of ${\cal C}^{k \cup}$, the $k$-fold union of ${\cal C}$, is at most $3 {\rm VC}({\cal C}) k \log (3k)$, where ${\cal C}^{k \cup} := \set{c_1 \cup \ldots \cup c_k \colon c_1,\ldots,c_k \in {\cal C}}$. \end{fact} \cref{fact:vc-of-ball,fact:k-fold} imply the following corollary. \begin{corollary}\label{cor:vc-of-k-ball} The VC-dimension of $\cC_{k\text{-balls}}$, the class of all $k$-fold union of balls in ${\mathbb R}^d$, is at most $3 (d+1) k \log (3k)$. \end{corollary} } \remove{ \subsection{The Johnson Lindenstrauss transform}\label{sec:JL} \begin{definition}[The JL random projection from ${\mathbb R}^d$ to ${\mathbb R}^m$]\label{def:JL} Let $f \colon {\mathbb R}^d \rightarrow {\mathbb R}^m$ be the projection that works as follows: Pick $m$ vectors $\pz_1,\ldots,\pz_m$ from a standard $d$-dimensional Gaussian distribution with density $p(\px) = \frac{1}{(2 \pi)^{d/2}} \exp(-\norm{\px}^2/2)$. For any vector $\px \in {\mathbb R}^d$, define $f(\px) = (\rm ip{\px,\pz_1}, \ldots, \rm ip{\px,\pz_m})$ (where $\rm ip{\px,\py} = \sum_{i=1}^d x_i y_i$). \end{definition} \begin{theorem}[\cite{JL84}]\label{thm:JL} Let $f \colon {\mathbb R}^d \rightarrow {\mathbb R}^m$ be the random projection from \cref{def:JL}, and let $n \in {\mathbb N}$, $\varepsilon > 0$. Assuming that $m = \Omega\paren{\frac{1}{\varepsilon^2} \cdot \log\paren{n/\beta}}$, then with probability $1-\beta$ it holds that \begin{align*} \forall \px,\py \in {\cal P}: \quad \norm{f(\px)-f(\py)} \in (1 \pm \varepsilon) \sqrt{m} \norm{\px - \py} \end{align*} \end{theorem} } \subsection{Concentration Bounds} \begin{fact}[Hoeffding's inequality]\label{fact:Hoeffding} Let $X_1,\ldots,X_n$ be independent random variables, each $X_i$ is strictly bounded by the interval $[a_i,b_i]$, and let $\bar{X} = \frac1n\sum_{i=1}^n X_i$. Then for every $t \geq 0$: \begin{align*} \pr{\size{\bar{X} - \ex{\bar{X}}} \geq t} \leq 2\exp\paren{-\frac{2n^2 t^2}{\sum_{i=1}^n (b_i-a_i)^2}} \end{align*} \end{fact} \begin{fact}[{\cite[Theorem 5.3]{AminCO}}]\label{fact:binom_concentration} Let $X \sim {\rm Bin}(n,p)$, then for all $t \geq 0$: \begin{enumerate} \item $\pr{X \geq \ex{X} + t} \leq \exp\paren{-\frac{t^2}{2\left(np + t/3\right)}}$. \item $\pr{X \leq \ex{X} - t} \leq \exp\paren{-\frac{t^2}{2np}}$. \end{enumerate} \end{fact} \section{Introduction} Related work: Mean estimation: \url{https://arxiv.org/abs/2006.06618} We do (some of) this non-parametrically. No need to know or privately estimate spread. Need to read carefully also for relevant work. Enclosing ball: \url{https://arxiv.org/abs/1707.04766} Somewhat different problem. Large constants. More complex. Worst asymptotics for our setting?? \section{The friendly elements problem} The input is a set of elements $T$ of size $|T|=n$. We have a symmetric predicate $\text{like}$ $x \leftrightarrow y$ on pairs of elements. We are interested in an algorithm with the following properties: (i) the output is either a "fail" or "success". If "success," the output also includes a set $T_G$ of "good elements." The set $T_G$ must include all {\em perfect} elements (a perfect element likes all elements) and may contain only elements that like more than half of elements. (ii) When all elements are perfect, the success probability is $1$. In addition, we have the following requirements for $(\varepsilon,\delta)$ and $\Delta>1$. We say that two datasets $T$ and $T'$ are neighbors if they differ in at most one element. (iii) The fail/success bit is $(\varepsilon,\delta)$-indistinguishable for any two neighboring datasets. Namely, if $p$ and $p'$ are the success probability of $T$ and $T'$ then $p \leq e^\varepsilon p' + \delta$ and $(1-p) \leq e^\varepsilon (1-p') + \delta$. (iv) The algorithm is randomized so that each element in $T$ has an independent probability to be included in $T_G$ (perfect elements have probability $1$ and elments with $n/2$ or fewer likes have probability $0$). If $p$ and $p'$ are the vectors of probabilities of two neighboring datasets then $\norm{p-p'}_1 \leq \Delta$. We present two solutions for friendly elements. The first one performs ${n \choose 2}\approx n^2$ like queries. The second (that provides high probability guarantees for requirements (ii) and (iv)) performs $O(n\log n)$ like queries. Note that in terms of asymptotic dependence on $n$, this is the best we can hope for simply satisfying properties (i)-(ii). The effect of requirements (iii)-(iv) and the privacy parameters $(\varepsilon,\delta)$ and $\Delta$ is that they imply a minimum value on $n$ that is needed to support these specifications. [To do: For the more efficient $O(n\log n)$ method, we need to refine the hard bound in (iv) on $\norm{p-p'}_1$ with allowing for higher values and lower success probability.] We first describe how we apply friendly-elements within a sample-and-aggregate framework. We then proceed with solutions, starting with some basic tools that we use. \section{Applications} Elements are points in a metric space (or pseudo metric). We are interested in a "center" point. With DP, typically there is an additive error that depends on the diameter of the space $\Lambda$. For example with DP averaging the error is proportional to $\Lambda \sqrt{d}/(n \varepsilon)$. But suppose we are only interested in a "center" when all points are within a distance $r\ll \Lambda$ except perhaps for a few outliers. The friendly elements is a way to do this. Two elements are friends if their "distance" is at most $r$. The output (if "success") are elements $T_G$ with guaranteed max distance $2r$ between any pair. Therefore, we can apply any "centering" method with $\Lambda=r$. For applications we may need to also return $r$ that is within say a small factor from the smallest one that yields "success." So the output space can only include $2^i r_{\min}$ for some integral $i$. A naive way to do this is by sequentially doubling $r$ until there is success. This results in $\log(r/r_{\min})$ checks. A better way is to do a binary search by doubling $i$ first. This gives us $\log\log(r/r_{\min})$ since we search over $\log(r/r_{\min})$ values. Sparse vector might improve the asymptotics further. [Comment: On real datasets we can expect $\log\log(r/r_{\min}) \leq 8$ but still this is a factor on the number of elements. There should be a better way. ] \Enote{I didn't follow it...}\ECnote{Yes, you are right. I erased What was there as it does not work. There is also a lower bound of $\log^* |X|$...) }. \subsection{Sample-and-aggregate framework} Sample-and-aggregate \cite{} is a framework for DP solution of problems on instances where a solution for a small random sample of the data is very likely to be a good solution for the full dataset. We use friendly-elements as a component in a sample-and-aggregate framework. For a dataset of size $N$, the smallest sample size $s$ that is needed for this to hold is a property of the dataset. When this holds, we can get $n = N/s$ disjoint random samples. The framework applies a non-private algorithm to each of the $n$ samples and then privately "aggregates" the results. Solutions that work with smaller $n$ are better as they apply to more datasets. To apply the frameworks we need \begin{itemize} \item A non-private algorithm $A$ that inputs a dataset $D$ of points and returns a solution $x \gets A(D)$. \item A similarity predicate between solutions $x_i \leftrightarrow x_j$. Similarity is reflexive -- we have $x \leftrightarrow x$ for all $x$. Informally, similarity means that the solutions are interchangeable (one is almost as good as the other with respect to $D$). \item An $(\varepsilon,\delta)$-DP aggregator $C(X)$: Takes an input a set $T_G$ of at least $|T_G|\geq 0.9n$ solutions so that for any $x,y \in T_G$ either $x \leftrightarrow y$ or there exists $z$ such that $x \leftrightarrow z$ and $z \leftrightarrow y$. Aggregator returns a private solution $x^* \gets C(X)$. Informally, the interpretation is that $x^*$ is 2-hops "similar" to any of the $x_i$'s. \end{itemize} Note that in the original sample-and-aggregate formulation, the aggregator needs to be "robust." It is applied directly to the solutions from all samples. That set is allowed to contain some "bad" solutions. Our friendly-elements module allows for the use of a simpler aggregator when all solutions are "good." \begin{enumerate} \item Set $D$ of $N$ data points, $n$ \item Randomly partition $D$ into $n$ equal-size sets $D_i$. \item Apply the non-private $A$ to each part to obtain $x_i \gets A(D_i)$. Note that from neighboring inputs $D$ and $D'$ (differ on one data point) we obtain neighboring sets $T=\{x_i\}$ and $T'=\{x'_i\}$. \item Apply friendly-elements to the set $T$. We either fail or obtain a subset $T_G$ with almost all of $T$ that satisfies the input requirements of the aggregator. Recall (property of friendly-elements) that this probabilistic output $T_G$ is stable. \item Return $C(T_G)$ \end{enumerate} When the dataset has the property that the $n$ solutions are similar, we succeed and return a private solution that is similar to them. \section{Preliminaries: Tools} \subsection{Tool: optimal DP thresholding} Let $A$ be a function that inputs a dataset $X$ and returns an integer $A(X)$. We have the property that $A$ has sensitivity $1$: On ``neighboring'' datasets $X$ and $X'$, $|A(X)-A(X')| \leq 1$. We seek an $(\epsilon,\delta)$-DP thresholding predicate as follows: When $A(X) \geq \tau$ the output is $1$. Otherwise, when $A(x) <\tau$, the probability of $1$ is minimum. [Comment: The problem can be solved with truncated Laplace noise, but not optimally. This roughly by adding $(1/\varespilon) \ln(1/\delta)$ plus Laplace $[1/\varespilon]$ noise (truncated to remove $\delta$ tails).] The optimal DP thresholding scheme \cite{} is as follows: Let \begin{equation}\label{Ldef:eq} L(\epsilon,\delta) := \frac{1}{\varepsilon} \ln\left( \frac{e^\varepsilon -1 +2\delta}{\delta(e^\varepsilon +1)} \right) \approx \frac{1}{\varepsilon} \ln\left(\frac{\min\{1,\varepsilon\}}{2\delta} \right) \end{equation} we assume that $\epsilon$ and $\delta$ are such that $L$ is an integer. We define$(\pi^*_i)_{i\geq 1}$ as follows: \Enote{So the $L$ is chosen to be the value such that $\pi_{L+1}^*$ is the same in both cases? i.e., $\delta \frac{e^{\varepsilon (L+1)}-1 }{e^\varepsilon -1} = 1- \delta \frac{e^{\varepsilon (2L+2-(L+1))} -1}{e^{\varepsilon} -1}$?} \begin{equation} \label{pistar:eq} \pi^*_i = \left\{ \begin{array}{ll} 0 &\; \text{\small $ i \leq 0$ }\\ \delta \frac{e^{\varepsilon i}-1 }{e^\varepsilon -1} &\; \text{\small $0\leq i\leq L+1$ }\\ 1- \delta \frac{e^{\varepsilon (2L+2-i)} -1}{e^{\varepsilon} -1} &\; \text{\small $L+1 \leq i \leq 2L+1$ }\\ 1 &\; \text{\small $i \geq 2L+2$ } \end{array}\right. \end{equation} Optimal DP thresholding for $\tau, \varepsilon, \delta$: \begin{enumerate} \item $i \gets A(x)$ \item Return $1$ ("pass") with probability $p(i) :=\pi^*_{i-\tau +2L+2}$. Return $0$ otherwise (probability $q(i) := 1-p(i)$. \end{enumerate} Note that the DP thresholding always returns $0$ when $A(X) \leq \tau-2L-2$ and as required always returns $1$ when $A(X) \geq \tau$. We will use the following property of $\pi^*_i$: \begin{equation} \label{ratioprop:eq} \max\left\{\frac{\pi^*_i - \delta}{\pi^*_{i-1}}, \frac{1-\pi^*_{i-1} - \delta}{1-\pi^*_{i}}\right\} \leq e^\varepsilon \end{equation} \paragraph{Reverse threshold:} The mechanism can be flipped to provide a "reversed" guarantee of passing with probability $1$ when $A(x) \leq \tau$. This is provided with pass probabilities: \[ p(i) := \pi^*_{\tau - i +2L+2}\ . \] \paragraph{Probabilisitc $A(x)$:} The formulation generalizes to when $A(X)$ returns values according to a distribution. In this case sensitivity $1$ informally means that for any $T$, $\Pr[A(X')\leq T-1]\leq \Pr[A(X)\leq T]\leq \Pr[A(X')\leq T+1] $. That is, we can map outcomes of $A(X)$ to outcomes of $A(X')$ with difference at most $1$. Note that in this case the threshold mechanism may no longer be optimal, as it does not account for the randomization in $A$. For example, that randomization might already provide a private threshold. For our purposes however this suffices. \paragraph{Continuous $i$:} Formulation works when $i$ is continuous. We still require sensitivity $1$. \subsection{Tool: DP Thresholding with a varying local sensitivitiy bound} We now consider a situation where we have a function $B(X) \geq 0$ with local sensitivity bound of the form $B(X') \leq c + e^\nu B(X) $. Equivalently, $B(X')-B(X) \leq c + (e^\nu-1) B(X)$. We want to apply DP thresholding so that if $B(X)=0$, pass probability is $1$ and otherwise pass probability is minimum. We compute a monotone mapping $b^{-1}()$ of values so that the function $b^{-1}\circ B(X)$ has sensitivity at most $1$. \begin{lemma} Let $B()\geq 0$ be such that on any two neighboring datasets $X$ and $X'$, $B(X') \leq c + e^\nu B(X)$. Define \[ b^{-1}(y) := \frac{1}{\nu}\ln \left(1+ y \frac{e^\nu -1}{c}\right)\ . \] Then the function $b^{-1}\circ B(X)$ has sensitivity 1. That is, on any two neighboring datasets, $b^{-1}\circ B(X') \leq 1 + b^{-1}\circ B(X)$. Also, $B(X)= 0$ if and only if $b^{-1}\circ B(X)=0$. \end{lemma} \begin{proof} \ECnote{Replaced my "proof" with Eliad's proof.} \begin{align*} b^{-1} \circ B(X') &= \frac1{\nu} \ln\paren{1 + B(X')\cdot \frac{e^{\nu}-1}{c}}\\ &\leq \frac1{\nu} \ln\paren{1 + (c+e^{\nu}B(X))\cdot \frac{e^{\nu}-1}{c}}\\ &= \frac1{\nu} \ln\paren{e^{\nu} + e^{\nu}B(X) \cdot \frac{e^{\nu}-1}{c}}\\ &= 1 + \frac1{\nu} \ln\paren{1 + B(X)\cdot \frac{e^{\nu}-1}{c}}\\ &= 1 + b^{-1} \circ B(X) \end{align*} \end{proof} To DP threshold $B(X) \leq 0$, we apply $(\varepsilon,\delta)$-DP-thresholding $\leq 0$ to $b^{-1}\circ B(X)$. When $B(X)=0$ (and $b^{-1}\circ B(X)=0$), we pass with probability $1$ and otherwise the pass probability is minimum. We now ask what is the maximum possible $B(X)$ that yields a nonzero probability of passing. The maximum pass value in terms of $b^{-1}\circ B$ is $2L(\epsilon,\delta)+2$, where $L(\epsilon,\delta) \approx \frac{1}{\varepsilon} \ln\left(\frac{\varepsilon}{2\delta} \right)$. We then have \[ B_{\max} \gets b(2 L(\epsilon,\delta) +2) \leq c \frac{e^{y \nu}-1}{e^\nu -1}, \] where $y\leq 2(1+ \frac{1}{\varepsilon} \ln\left(\frac{\varepsilon}{2\delta} \right))$. In the regime $y \nu < 1$ we get \begin{equation} \label{Bmax:eq} B_{\max}\leq \approx c y \approx 2 c(1+ \frac{1}{\varepsilon} \ln\left(\frac{\varepsilon}{2\delta} \right)) \end{equation} In our application we will use $\nu = \frac{2\ln(1/(2\eta))}{n}$, where $\eta \ll 1/n$ (but does not need to be smaller than $1/n^2$) and is discussed later. The condition $y\nu < 1$ gives as a bound on $n$: \Enote{So, we assume in this part that $\nu = \frac{2\ln(1/(2\delta))}{n}$?}\ECnote{I replaced one $\delta$ with $\eta$ that is between $1/n$ and $1/n^2$ and is sufficient. Essentially we want $n\eta$ to be very small since $c=1+n\eta$. This is different than the requirements dictating choice of $\delta$. In principle like in the tuples, the $n$ (number of elements) is much smaller than the number of points in the dataset. And the $\delta$ is determined by dataset size. So it makes sense to separate $\delta$ and $\eta$} \[ \frac{2\ln(1/(2\eta))}{n} 2(1+ \frac{1}{\varepsilon} \ln\left(\frac{\varepsilon}{2\delta} \right) < 1 \] To make this happen we need roughly \[ \frac{n}{\ln n} > 4 \frac{1}{\varepsilon} \ln (1/(2\delta)\] So for $\delta \ll 1/n$ we get $n> 4 \frac{1}{\varepsilon} \ln (1/(2\delta) (\ln(4/\varepsilon) + \ln\ln (1/\delta) $ [Comment: for a more refined analysis we need to consider the probability of passing with each $y$ $p(y) := \pi^*_{\tau - y +2L+2}$. This allows us to account for larger $B$'s that occur with lower probability. ] \subsection{Tool: Generalized group privacy} The following is a sketch of a generalized group privacy lemma. {\bf To Do:} For the $O(n\log n)$, for pure DP, or for tighter analysis we need to extend it to allow larger $\Delta$ mitigated with lower success probability (rather than fixed bound on $\Delta$). \begin{lemma} Let $A(X)$ be a randomized algorithm on sets $X$ such that when $X$ and $X'$ differ in one element then $A(X)$ and $A(X')$ are $(\varepsilon,\delta)$-indistinguishable. [We use a discrete universe of elements of size $n$, to simplify presentation] Consider now a vector of probabilities $(p_1,\ldots,p_n)$ and the algorithm $A^*(p)$ that constructs $X$ by drawing each $i\in [n]$ independently with probability $p_i$ and returns $A(X)$. Consider $p$ and $p'$ such that $\norm{p-p'}_1 = \Delta$. Then $A^*(p)$ and $A^*(p')$ are $(\Delta\varepsilon, \Delta e^{\Delta\varepsilon} \delta)$-indistinguishable. [Comment the above is not precise, we lose a little more, but not much more. This with respect to $p$ being a 0/1 vector (standard group privacy).] \end{lemma} \begin{proof} Sketch: Without loss of generality we can treat $p$ as the $0$ vector and $p'$ to be a vector with L1 norm $\Delta$. This because the set difference can be viewed as independent of the particular outcome of $p$. More formally, we can consider all randomizations (say draw a random value for each element $i$ and include if below $p_i$) that resulted in a fixed draw with $p$. Then and the respective possibilities from $p'$ and the respective distribution on set differences size. If the $L1$ norm is $\leq \Delta$ then, roughly, the probability that we get a set difference of $i\Delta$ is bounded by $1/(e i!)$ using the Poisson approximation to binomial distribution (good bound when $\Delta=1$), noting that binomial with $pn=1$ is worst case for the spread. \Enote{so again, you assume that each element is chosen w.p. $p = \frac{\Delta}{n}$ (since this should be the worst case), and that $Bin(n,p = \frac{\Delta}{n}) \approx Poisson(\Delta)$.} [note: The above will be helpful also when we incorporate success probabilities. as set difference dist holds when conditioned on a fixed outcome of $p$, including outcomes that result in "success"] We now do group privacy analysis. First fixing the outcome on $p$. Then considering the possible set differences and their probabilities. For each set difference, we can apply the known standard group privacy bound. The calculation below is for pure differential privacy $\delta=0$. For that the standard bound is that $\varepsilon$ increases by a multiplicative factor of set difference. We get the effective privacy parameter $\varepsilon^*$ so that \[ e^{\varepsilon^*} \leq \frac{1}{e} \sum_{i\geq 0} \frac{1}{i!}e^{i\Delta\varepsilon} \] (summing over probability of set difference $i\Delta$ times the group privacy bound for that set difference (multiplier $e^{i\Delta\varepsilon}$)) To Do: Do the calculation with $\delta$. Note that as the function $e^x$ is concave, so we are losing a little over standard group privacy with $\Delta$. But since the values are fairly concentrated -- due to independence -- and the $1/i!$ drop -- we should not lose much. Without independence we would be forced to use Markov and would get $1/i$ that does not drop fast enough. To Do: Some extension needed for scenario with sampling. We don't have a hard bound $\Delta$. We have possibility of larger $\Delta$ but combined with lower success probabilities. So $\Delta$ is not bounded. But the probability of reporting decreases sharply with $\Delta$. This should also similarly work. \end{proof} \section{$O(n^2)$ Good elements algorithm} The good elements algorithms has two components. The first is to identify a set $T_G$ of good elements by testing each element. We also compute the expected value $B:= E[|T_G|]$ of the number of good tuples. The second is to decide, based on the $B$, if to fail (report nothing) or succeed and report $T_G$. \paragraph{Computing set of good elements $T_G$} The input is a set of elements $T$ and a "like" predicate $x\sim y$. For each element $x$ we consider the number of elements in $T$ that like $x$: \[A(x) := \sum_{y\in T} I_{x\sim y}\ .\] \begin{enumerate} \item Input: A set of elements $T$ with $|T|=n$. A predicate on elements $x\sim y$. \item Output: A set of good elements $T_G\subset T$ that must include all perfect elements $A(x)=n$, and may not include any bad element $A(x)\leq n/2$. Also compute the value $B :- E[|T_G|]$ for that data set. \item $B\gets 0$ (initialize value of $E[|T_G|]$) \item Set $L'$ such that $2L'+2 = n/2$ \item Set $\eta \ll 1/n$ and choose $\nu$ to be smallest such that $L(\nu,\eta) = L'$ (We have $\nu \approx \leq 2 \ln(1/(2\eta))/n$.) \item For each tuple $x \in T$: \begin{enumerate} \item $A(x) \gets \sum_{y\in T} I_{x\sim y}$. \item If $(\nu,\eta)$-DP thresholding of $A(x) \geq \tau=n$ then $T_G \gets T_G \cup \{x\}$ (element $x$ is good). \item $B \gets B+ \pi^*_{n - A(x) +2L+2}$ (probability of $x$ being labeled good by DP-threshold) \end{enumerate} \item $T_B \gets T\setminus T_G$. Return $T_G$ and $B$ \end{enumerate} \subsection{Local sensitivity analysis} The good elements set $T_G$ is drawn according to a vector of probabilities \[ r(T) := (p(A(x))_x = (\pi^*_{n - A(x) +2L+2})_{x}\ .\] Recall that the probabilities and $L$ depend on $(\nu,\eta)$ used in the DP thresholding algorithm. (For convenience we use vector notation while treating these vectors as sparse over the universe of elements. Keeping in mind that the universe might be continuous) Recall that $E[|T_G|] = \norm{r(T)}_1$. For two neighboring datasets $T$ and $T'$ ($|T\setminus T'|\leq 1$ and vice versa). We can consider the vectors $r(T)$ and $r(T')$. We bound the extent in which the expected number of bad elements can increase between neighboring datasets. We also bound the L1 distance of the probability vectors. \begin{lemma} Let $T$ and $T'$ be neighboring. Then \begin{align} \norm{r(T')}_1 &\leq 1+e^\nu \norm{r(T)}_1+ n\eta \\ \norm{r(T') - r(T)}_1 &\leq 1+ (e^\nu-1) \norm{r(T)}_1+ n\eta \end{align} \end{lemma} \begin{proof} Consider $x\in T\cap T'$. We have $A_T(x) = A_{T'}(x) \pm 1$ and $q(A_{T'}(x)) \leq q(A_T(x)) e^\nu + \eta$ and $p(A_{T'}(x)) \leq p(A_T(x)) e^\nu + \eta$ (holds by \cref{ratioprop:eq}). \begin{align*} E[|T'_B|] &= \sum_{x\in T'} q(A_{T'}(x)) \leq 1 + \sum_{x\in T'\cap T} q(A_{T'}(x)) \leq 1 + \sum_{x\in T'\cap T} q(A_{T}(x)-1) \\ &\leq 1+ e^\nu \sum_{x\in T'\cap T} q(A_T(x)) + n\eta \leq 1 + e^\nu E[|T_B|] + n\eta \end{align*} This because the element that is different can contribute at most $1$ and for all other tuples $A(x)$ changed by at most $1$ and we use~\eqref{ratioprop:eq}. Similarly \begin{align*} \norm{r(T') - r(T)}_1 &\leq 1+ \sum_{x\in T\cap T'} q(A_{T'}(x))-q(A_{T}(x)) \\ &\leq 1+ (e^\nu-1)\sum_{x\in T} q(A_{T}(x)) + n \eta = 1+ (e^\nu-1) \norm{r(T)}_1+ n\eta \end{align*} Comment: Note that for $q > 1/2$, we can use a tighter bound. This is relevant if we use $T_G$, that is large. We can bound $E[|T'_G|] - E[|T_G]]$ it in terms of the smaller of $T_B$ or $T_G$ or more finely, by considering $q$. We get \[ E[|T'_B|] - E[|T_B]] \leq 1+n\eta + (e^\nu-1)\min\{E[|T_B|],E[|T_G|] \} \] \end{proof} [Comment. We would want to balance $\eta$ and $\nu$ given $L$ as to minimize the L1 distance in our regime of interest] \subsection{putting it together} Comment: Need to set privacy parameters so it composes to what we want. We apply DP thresholding with varying local sensitivity to $E[|T_B|]$ , with $c=1+n\eta$. \begin{enumerate} \item Apply the good elements subroutine to compute the set $T_G$ and $y \gets E[|T_B|] = \sum_{x\in T} q(A_{T}(x)$ [With that subroutine we need to use $\eta \ll 1/n$ and choose $\nu$ as low as we can given that and $n$. Recall that we get $\nu \approx\leq 2 \ln(1/(2\eta))/n$] \item Recall that the local sensitivity of $E[|T_B|]$ is $(1+n\eta) +e^\nu E[|T_B|]$. We apply thresholding with varying local sensitivity, using $\nu$ and $c=1+n\eta$: We set $m \gets b^{-1}(y)$ \Enote{has sensitivity $1$}, apply $(\varepsilon,\delta)$ DP thresholding with $\leq 0$. If we fail, we return $\bot$. Otherwise, we return $T_G$.\Enote{So by thresholding you mean that we compute $\hat{m} = m + {\rm Lap}(1/\varepsilon)$, and we pass the test if $\hat{m} \leq 0$?}\ECnote{Yes. Can use Laplace or truncated Laplace. Only that this is lossy and wanted to squeeze the constants. So we use a precise optimal thresholding} By design, the threshold "pass" bit is $(\epsilon,\delta)$ DP.\Enote{Do we need the $\delta$ here?}\ECnote{We could remove it. It seems. I did not check carefully. But then we need to work with high probability. Which we will need to anayway for the sampling.... And the analysis is not completely clean 0/1. So it is cleaner to first use $\delta$.} \item We obtain that a pass is possible (see \eqref{Bmax:eq}) only if $y\leq B_{\max} = 2(1+n\eta)(1+ \frac{1}{\varepsilon}\ln (\varepsilon/(2\delta))$. This means that the $L1$ distance when passing between neighboring datasets is at most \[\Delta \leq c + (e^\nu-1) B_{\max} \approx 1+ n\eta + \nu B_{\max} .\] (approximation holds when $\nu\ll 1$, that is, $2\ln(1/(2\eta) \ll n$ which holds for small values of $n$). Now note that $\Delta$ should be close to $1$ when $\eta \ll 1/n$ and $\nu B_{\max} \ll 1$. Substituting the bounds we have on $\nu$ and $B_{\max}$ we get \[ n \gg 2(1+n\eta)(1+ \frac{1}{\varepsilon}\ln (\min\{1,\varepsilon\}/(2\delta)) 2 \ln(1/(2\eta)) \approx 4 \frac{1}{\varepsilon}\ln n \ln(1/(2\delta) \] (for say $\eta = 1/(n\ln n)$. We apply the generalized group privacy with $\Delta$ to obtain the claimed property. \end{enumerate} Comment: We can optimize a bit more the minimum $n$ (factor of 2) by not using the maximum $B_{\max}$ and accounting in the privacy analysis for the lower reporting probability when $b^{-1} B$ increases. Comment: We can use coordinated sampling techniques to have a non-negatively correlated instead of independent choice so that the number of bad elements is very close to its expectation and the actual difference between neighboring datasets is even more concentrated around the L1 distance. But not sure it is worth the work. \section{$O(n\log n)$ solution for friendly elements } Incorporating sampling: Now we want to be efficient. Instead of counting exactly the number of liking tuples, for each $x$ we sample $S$ tuples. We then compute $A(x)$ as the number of tuples in $S$ that like $x$. (better with different sample for each $x$ for independence). \paragraph{Sample size:} The sample size $s$ should be large enough so that say $2/3$ likes on the sample imply with very high probability that there are $> n/2$ likes on the full set. We need the sample to be at least $a \log(n)$. We then do DP thresholding on the stretch with $2L''+2 = s/3$ . And then $\nu'$ the solution of $L(\nu,\delta) = L''$. We get $\nu' \approx 3\ln(1/2\delta)/s$. The sampling will decrease the ratio of neighboring $q(i)$ by $s/n$, so we get the guarantees we need. So the only constraint on sample size is ensuring that $2/3$ filters out tuples with $\leq n/2$ friends. With the crude multiplicative Chernoff bound $\delta=1/3$ and we get $s \approx 72\ln(n)$ to guarantee that probability $1/n^2$ of passing a tuple with $\leq n/2$ friends. But this constant can be tightened by using the raw Chernoff bounds. \paragraph{thresholding by $|T_B|$ and not its expectation} Thresholding the actual number of bad tuples $T_B$ and not its expectation. Now L1 norm of neighboring and also worst-case local sensitivity can increase. But we don't need to account for worst case as this is mitigated with higher fail probability when $E[|T_B|]$ is larger. We need to do the computation but it should balance out. Actually might also reduce the factor 2 due to "largest" $E[|T_B|]$ that can pass the threshold. Instead when mitigating by likelihood it should help. \section{Comments on application of private friendly elements} In the applications for clustering, each element is a $k$-tuple obtained by applying a clustering algorithm on a part of the data. Comments: If we can assume that the algorithm that returns the tuples exposes privacy of points at random (return a random member of the cluster) we can integrate this into the privacy analysis which will allow for a larger $\delta$ (in terms of number of inverse (poly) number of tuples rather than numbers of points). The number of tuples needed does not grow with the number of points in the datasets. We bound sensitivity in terms of neighboring tuples. If the algorithm that generates tuples has the property that one member of the tuple changes on neighboring point sets then we can save in the group privacy argument. The solution can be modified to problem specs where elements are considered perfect if the like all except for $a$ elements and require success when at most $b$ elements are not perfect. This extends the applications. In application to clustering. We still can proabbly avoid solving $n$ small problems. In the non-private setting, one small problem suffices. What we can do is emulate. Solve one problem. Then process and "emulate" output of $n$ problems. This involves discarding all ambiguous points. Then aggregate. \printbibliography \section{Introduction} Points for intro: \begin{itemize} \item Friendly Elements Problem \item Tradeoff between input size and "stability" \item Explain stability in terms of an L1 norm between output probabilities. We extend group privacy analysis to this setting (may have other applications) \item Structure of Friendly Elements solution: Returned elements and Private Success bit: Allows for a very high stability and also guarantee that when success we remove only few points, the minimum needed for private success bit. \item Sample complexity (input size): The bottleneck is the private success bit. There is a counting "lower bound" \[ \ell(\varepsilon,\delta,\beta) := \frac{1}{\varepsilon}\ln(\frac{\varepsilon}{2\delta\max\{\beta,\delta\}})\] The sample complexity we obtain for FriendlyCore is a small constant factor on that. In particular, no dependencies on dimension or particulars of the metric space. \item Two common input models: Swap model (points get replaced but their number is known non-privately) and Add/Delete. The literature has generic "reductions" between the models, but these reductions are lossy in terms of constants. We analyse both to avoid that. The set we return contains almost all point except for few as needed for DP \item Instead of specifying $r$, can search for "right" $r$ cheaply....(quantify) Some applications need that. Input size bottleneck then come from that search. \item Applications: Friendly Elements paradigm. Averaging. Elaborate: Sample-and-aggregate (e.g. clustering, we get tuples). \item Important point: \end{itemize} Extensions: \begin{itemize} \item Computation. Current presented for $n^2$ "$f$" computations. Can be reduced to $n\log n$. \item Can be used in other regimes. Specified number of "outliers" (with DP counting below that). This for at most $n/2$ outliers. Also can be used without "success" bit: No restriction on size of output set $T_G$. Set is still stable but L1 can grow to a small constant. \end{itemize} \subsection{Related work} {\bf Enclosing/densest ball methods:} \url{https://arxiv.org/abs/1707.04766} Solves our problem by computing a bounding ball that fits the input. The private ball can then be used to return a "stable" set of points (all points inside the ball). But these methods are impractical due to algorithmic complexity and large constant factors and the approach of computing a private ball implies additional dependencies on the dimension. Some methods are limited to Euclidean spaces in that they integrate dimensionality reduction and locality sensitive hashing. The downstream tasks may not exhibit dependencies on the dimension at all or may use other metric spaces (e.g. within some sample-and-aggregate methods) or may do it with much lower constant factors overheads (e.g., averaging). The computation of a center of a ball is a more complex task with additional asymptotic dependencies on the dimension. The methods are limited to spaces such as Euclidean that support dimensionality reduction or locality sensitive hashing. While the downstream applications may tasks in applications sometimes dependence in the dimension is necessary for downsteam aggregation tasks, it can be by also performing an aggregation (finding a Euclidean ball that contains many points). The ball can be then used to return a stable set. But the problem of returning a stable set can be solved more efficiently and as we show, without dependence on the dimension. Somewhat different problem. Large constants. More complex. Worst asymptotics for our setting?? In practice, clipping norms and winsorizing are used to limit the diameter of the input domain. These are classical techniques in statistics to control empirical variance. But to apply clipping effectively we also need to know a "center" point, which is sometimes the problem we are out to solve. {\bf Mean estimation}, where it is assumed that data originates from a distribution. Karwa and Vadhan \url{https://arxiv.org/abs/1711.03908} proposed methods for mean estimation. In particular, for Gaussians with known veriance they proposed partitioning the interval to segments of length $\sigma$ and using a private sparse histogram to identify the densest bin. The scaling to multi-variate setting (higher dimentiosn) is not efficient. Steinke and Bun proposed a trimmed mean approach through smooth sensitivity in concentrated DP \url{https://arxiv.org/abs/1906.02830}. It is not comparable. CoinPress \url{https://arxiv.org/pdf/2006.06618.pdf} based on \url{https://arxiv.org/abs/2001.02285} considers multi-variate Gaussians and propose and iterative search that (again) computes an enclosing ball, trimms points, and computes a private average using the smaller radius. Coinpress is practical and outperforms prior methods. It demonstrates little privacy loss for estimating Gaussian parameters. Coinpress performs the diameter reduction in an entangled way with the harder problem of mean estimation. This makes sense when the latter is the only application. We show that diameter reduction is an easier problem with a faster solution and a helpful tool for a variety of downstream tasks that may or may not be dimension-dependent. Moreover, our solution applies in general (pseudo) metric spaces. We circumvent the need to compute a "center" by using pairwise distances. Our approach surprisingly reduces diameter reduction to a one dimensional problem. \ECnote{Need to see whether or not we obtain better results than CoinPress for Gaussian mean estimation} \section{The friendly elements problem} The input is a set of elements $T$ of size $|T|=n$. We have a symmetric predicate $\text{like}$ $x \leftrightarrow y$ on pairs of elements. We are interested in an algorithm with the following properties: (i) the output is either a "fail" or "success". If "success," the output also includes a set $T_G$ of "good elements." The set $T_G$ must include all {\em perfect} elements (a perfect element likes all elements) and may contain only elements that like more than half of elements. (ii) When all elements are perfect, the success probability is $1$. In addition, we have the following requirements for $(\varepsilon,\delta)$ and $\Delta>1$. We say that two datasets $T$ and $T'$ are neighbors if they differ in at most one element. (iii) The fail/success bit is $(\varepsilon,\delta)$-indistinguishable for any two neighboring datasets. Namely, if $p$ and $p'$ are the success probability of $T$ and $T'$ then $p \leq e^\varepsilon p' + \delta$ and $(1-p) \leq e^\varepsilon (1-p') + \delta$. (iv) The algorithm is randomized so that each element in $T$ has an independent probability to be included in $T_G$ (perfect elements have probability $1$ and elments with $n/2$ or fewer likes have probability $0$). If $p$ and $p'$ are the vectors of probabilities of two neighboring datasets then $\norm{p-p'}_1 \leq \Delta$. We present two solutions for friendly elements. The first one performs ${n \choose 2}\approx n^2$ like queries. The second (that provides high probability guarantees for requirements (ii) and (iv)) performs $O(n\log n)$ like queries. Note that in terms of asymptotic dependence on $n$, this is the best we can hope for simply satisfying properties (i)-(ii). The effect of requirements (iii)-(iv) and the privacy parameters $(\varepsilon,\delta)$ and $\Delta$ is that they imply a minimum value on $n$ that is needed to support these specifications. Our goal is to understand this limit and design a method that works for small $n$. [To do: For the more efficient $O(n\log n)$ method, we need to refine the hard bound in (iv) on $\norm{p-p'}_1$ with allowing for higher values and lower success probability. Specifically, we consider the distribution of $\Delta$ and respective probabilities of success with this $\Delta$. Larger $\Delta$ is allowed with smaller success probabilities. ] We first describe potential applications of friendly-elements. We then proceed with solutions, starting with some basic tools that we use. \section{Applications} Elements $T$ are points in a metric space (or pseudo metric). 1. DP outlier removal: For given $r$, test if "almost all" pairs are within distance $r$. Return a "stable core" $T_g\subset T$ of points with diameter $2r$ or fail. For this applications we might want to tweak requirements to imply success probability $1$ also with few outliers. 2. More accurate DP "center" point. With DP, typically there is an additive error that depends on the diameter of the space $\Lambda$. For example with DP averaging the error is proportional to $\Lambda \sqrt{d}/(n \varepsilon)$. But suppose we are only interested in a "center" when all points are within a distance $r\ll \Lambda$ except perhaps for a few outliers. The friendly elements is a way to do this. Two elements are friends if their "distance" is at most $r$. The output (if "success") are elements $T_G$ with guaranteed max distance $2r$ between any pair. Therefore, to the output $T_G$ we can apply any "centering" method with $\Lambda=2r$. 3. Some applications, we do not have a target $r$. We are interested in returning $r_{eff}$ that is within say a small factor than the smallest one that yields "success." (imprecise). So the output space can only include $2^i r_{\min}$ for some integral $i$. A naive way to do this is by sequentially testing $2^i r$ until there is success. Naively using group privacy, this results in $\log(r_{eff}/r_{\min})$ checks and loss. A better way is to do a binary search over $i$. We first double $i$ until "success" to determine essentially $\log(r_{eff}/r_{\min})$ within a factor of $2$. We then do a binary search on that domain. Overall, the group privacy overhead is $\log\log(r_{eff}/r_{\min})$. We still did not specify how the "decisions" are made in the search. Also, group privacy here seems too coarse as there is a fine structure to exploit. [Comment: On real datasets we can expect $\log\log(r/r_{\min}) \leq 8$ but still this is a factor on the number of elements. There should be a better way. ] \Enote{I didn't follow it...}\ECnote{Yes, you are right. I erased What was there as it does not work. There is also a lower bound of $\log^* |X|$...) }. \subsection{Sample-and-aggregate framework} Sample-and-aggregate \cite{} is a framework for DP solution of problems on instances where a solution for a small random sample of the data is very likely to be a good solution for the full dataset. We use friendly-elements as a component in a sample-and-aggregate framework. For a dataset of size $N$, the smallest sample size $s$ that is needed for this to hold is a property of the dataset. When this holds, we can get $n = N/s$ disjoint random samples. The framework applies a non-private algorithm to each of the $n$ samples and then privately "aggregates" the results. Solutions that work with smaller $n$ are better as they apply to more datasets. To apply the frameworks we need \begin{itemize} \item A non-private algorithm $A$ that inputs a dataset $D$ of points and returns a solution $x \gets A(D)$. \item A similarity predicate between solutions $x_i \leftrightarrow x_j$. Similarity is reflexive -- we have $x \leftrightarrow x$ for all $x$. Informally, similarity means that the solutions are interchangeable (one is almost as good as the other with respect to $D$). \item An $(\varepsilon,\delta)$-DP aggregator $C(X)$: Takes an input a set $T_G$ of at least $|T_G|\geq 0.9n$ solutions so that for any $x,y \in T_G$ either $x \leftrightarrow y$ or there exists $z$ such that $x \leftrightarrow z$ and $z \leftrightarrow y$. Aggregator returns a private solution $x^* \gets C(X)$. Informally, the interpretation is that $x^*$ is 2-hops "similar" to any of the $x_i$'s. \end{itemize} Note that in the original sample-and-aggregate formulation, the aggregator needs to be "robust." It is applied directly to the solutions from all samples. That set is allowed to contain some "bad" solutions. Our friendly-elements module allows for the use of a simpler aggregator when all solutions are "good." \begin{enumerate} \item Set $D$ of $N$ data points, $n$ \item Randomly partition $D$ into $n$ equal-size sets $D_i$. \item Apply the non-private $A$ to each part to obtain $x_i \gets A(D_i)$. Note that from neighboring inputs $D$ and $D'$ (differ on one data point) we obtain neighboring sets $T=\{x_i\}$ and $T'=\{x'_i\}$. \item Apply friendly-elements to the set $T$. We either fail or obtain a subset $T_G$ with almost all of $T$ that satisfies the input requirements of the aggregator. Recall (property of friendly-elements) that this probabilistic output $T_G$ is stable. \item Return $C(T_G)$ \end{enumerate} When the dataset has the property that the $n$ solutions are similar, we succeed and return a private solution that is similar to them. \section{Preliminaries: Tools} \subsection{Tool: optimal DP thresholding} Let $A$ be a function that inputs a dataset $X$ and returns a real number $A(X)$. We have the property that $A$ has sensitivity $1$: On ``neighboring'' datasets $X$ and $X'$, $|A(X)-A(X')| \leq 1$. We seek an $(\epsilon,\delta)$-DP thresholding predicate as follows: When $A(X) \geq \tau$ the output is "pass". Otherwise, when $A(x) <\tau$, the probability of "pass" is minimum. [Comment: The problem can be solved with truncated Laplace noise, but not optimally. This roughly by adding $(1/\varespilon) \ln(1/\delta)$ plus Laplace $[1/\varepsilon]$ noise (truncated to remove $\delta$ tails).] The optimal DP thresholding scheme \cite{} is as follows: Let \begin{equation}\label{Ldef:eq} L(\epsilon,\delta) := \frac{1}{\varepsilon} \ln\left( \frac{e^\varepsilon -1 +2\delta}{\delta(e^\varepsilon +1)} \right) \approx \frac{1}{\varepsilon} \ln\left(\frac{\min\{1,\varepsilon\}}{2\delta} \right) \end{equation} we assume that $\epsilon$ and $\delta$ are such that $L$ is an integer. We define$(\pi^*_i)_{i\geq 1}$ as follows: \Enote{So the $L$ is chosen to be the value such that $\pi_{L+1}^*$ is the same in both cases? i.e., $\delta \frac{e^{\varepsilon (L+1)}-1 }{e^\varepsilon -1} = 1- \delta \frac{e^{\varepsilon (2L+2-(L+1))} -1}{e^{\varepsilon} -1}$?}\ECnote{This works for continuous $i$. There was also some typo $+2$ to $+1$ in the exponent that I fixed. On the points $i = L,L+1$ $\pi^*_L = 1 - \pi^*_{L+1}$.}\ECnote{This is simply the optimal (maximum) solution of the DP constraintes $\pi^*_i \leq e^\varepsilon \pi^*_{i-1} + \delta$ and $(1-\pi^*_i) \leq e^\varepsilon (1-\pi^*_{i+1}) + \delta$}\Enote{Why is it the optimal solution?}\ECnote{It is the optimal solution when $i$ is restricted to be an integer (prior paper). Making values as large as possible given that $\pi^*_0=0$. It is just solving the system of equations $\pi^*_i = \min\{e^\epsilon \pi^*_{i-1}+\delta, e^{-varepsilon}(\pi^*_{i-1}+\delta-1)+1 \}$. We can then extend it to continuous. This is because of the perhaps unclean definition of neighboring $<1$. If we require that closer datasets than $1$ distance are more similar (depends on distance) we get the nicer continuous opt. But for our purposes we can work with the step form. } \begin{equation} \label{pistar:eq} \pi^*_i = \left\{ \begin{array}{ll} 0 &\; \text{\small $ i \leq 0$ }\\ \delta \frac{e^{\varepsilon i}-1 }{e^\varepsilon -1} &\; \text{\small $0\leq i\leq L+1$ }\\ 1- \delta \frac{e^{\varepsilon (2L+1-i)} -1}{e^{\varepsilon} -1} &\; \text{\small $L+1 \leq i \leq 2L+1$ }\\ 1 &\; \text{\small $i \geq 2L+1$ } \end{array}\right. \end{equation} {\bf Extension to continuous (discrete)} The solution extends to $\pi^{c*}_x$ for a continuous $x\geq 0$: For $x\in [0,2L+1]$ we define $\pi^{c*}_x = \pi^*_{\lceil x \rceil}$. This is the (simultaneous) pointwise maximum solution at $x\geq 0$ for the constraints \begin{align*} \pi*_0 & = 0\\ \pi^*_x &\leq e^\varepsilon \pi^*_{x'} + \delta\, \; \forall |x-x'|\leq 1 \\ (1-\pi^*_x) &\leq e^\varepsilon (1-\pi^*_{x'}) + \delta\, \; \forall |x-x'|\leq 1 \end{align*} Explanation: since $\pi^*$ is non-decreasing wlog, it suffices to consider $\pi*_x = 0$ for $x\leq 0$, $\pi^*_x \leq e^\varepsilon \pi^*_{x-1} + \delta$ and $(1-\pi^*_i) \leq e^\varepsilon (1-\pi^*_{i+1}) + \delta$, solve only for integral values to get $\pi^*_i$, and verify that the extended solution holds for real values. {\bf Extension to continuous (smooth)} An alternative solutions that is continuous and differentiable and does not make assumption on integrality of $L$ is the following. This is also nicer to work with when $n$ is not given and we work in the deletion/addition model. This is not optimal at all points \Enote{What do we actually lose here? Why \cref{ratioprop:eq} holds around the middle (say, $x = M - 1/2$?)}\ECnote{I just verified it} \Enote{Ok. Another question: Last meeting we wanted to consider a stronger privacy. That is, the neighboring databases may have different size (by at most 1). In that case, the resulting $M$, $\varepsilon$ and $\delta$, which are a function of $n$, may vary in the two executions. Do you have any hint how we should handle it? Should we estimate the databse size by computing $\tilde{n} = n + {\rm Lap}(1/\varepsilon)$ and working with it? Or is there a better solution?} \ECnote{It seems that we do not need to noise $n$ even in the deletion/addition model. We are not explicitly using $n$ in the output. What really matters is how $n-A(x)$ changes between neighboring datasets. And for all but the "different" element it should still be $1$ (there might be a tiny diff in $\pi$ because $n/2$ changes also). } \begin{equation}\label{M:eq} M(\varepsilon,\delta) := \frac{1}{\varepsilon} \ln(\frac{1}{2\delta} (e^\varepsilon-1) +1) \end{equation} \begin{equation} \label{pistarcont:eq} \pi^*_x = \left\{ \begin{array}{ll} 0 &\; \text{\small $ x \leq 0$ }\\ \delta \frac{e^{\varepsilon x}-1 }{e^\varepsilon -1} &\; \text{\small $ x \in [0,M]$ }\\ 1- \delta \frac{e^{\varepsilon (2M-x)}-1 }{e^\varepsilon -1} &\; \text{\small $x \in [M,2M]$}\\ 1 &\; \text{\small $x \geq 2M$} \end{array}\right. \end{equation} The various $\pi^*$ (discrete, continuous) satisfy the following \begin{equation} \label{ratioprop:eq} \max\left\{\frac{\pi^*_i - \delta}{\pi^*_{i-1}}, \frac{1-\pi^*_{i-1} - \delta}{1-\pi^*_{i}}\right\} \leq e^\varepsilon \end{equation} {\bf Application: Specifying $M$} In our main application we specify $M$. We parametrize with $\gamma$ so that $\delta = 1/(\gamma M)$. We then solve \eqref{M:eq} for $\varepsilon$. We get $\varepsilon = C/M$ where $C$ is the solution of $C = \ln\left(\frac{\gamma}{2} C +1\right)$. This approximation holds for all $M$ such that $M \gg C$, that is, $\varepsilon \ll 1$. \ECnote{In the application we use $n = 4M$ so we get that we need $n \gg 4C$ from this requirement (say $n>50$)} Some values of $\gamma$ and corresponding $C$: \begin{equation}\label{gammaC:eq} \begin{array}{rr} \gamma & C \\ \hline 3.4 & 1 \\ 10 & 2.6 \\ 10^2 & 6 \\ 10^3 & 8 \\ 10^4 & 11\\ 10^5 & 13.5 \end{array} \end{equation} {\bf Application: Optimal DP thresholding for $\tau, \varepsilon, \delta$}: \begin{enumerate} \item $y \gets A(x)$ \item Return "pass" with probability $p(y) :=\pi^*_{y-\tau +2M(\varepsilon,\delta)}$. Return "fail" otherwise (probability $q(y) := 1-p(y)$). \end{enumerate} Note that the DP thresholding always returns "fail" when $A(x) \leq \tau-2M$ and as required always returns "pass" when $A(X) \geq \tau$. DP follows from property \eqref{ratioprop:eq}. \paragraph{Reverse threshold:} The mechanism can be flipped to provide a "reversed" guarantee of passing with probability $1$ when $A(x) \leq \tau$. This is provided with pass probabilities: \[ p(i) := \pi^*_{\tau - i +2M}\ . \] \paragraph{Probabilisitc $A(x)$:} The formulation generalizes to when $A(X)$ returns values according to a distribution. In this case sensitivity $1$ informally means that for any $T$, $\Pr[A(X')\leq T-1]\leq \Pr[A(X)\leq T]\leq \Pr[A(X')\leq T+1] $. That is, we can map outcomes of $A(X)$ to outcomes of $A(X')$ with difference at most $1$. Note that in this case the threshold mechanism may no longer be optimal, as it does not account for the randomization in $A$. For example, that randomization might already provide a private threshold. For our purposes however this suffices. \subsection{Tool: DP Thresholding with a varying local sensitivitiy bound} We now consider a situation where we have a function $B(X) \geq 0$ with local sensitivity bound of the form $B(X') \leq c + e^\nu B(X) $. Equivalently, $B(X')-B(X) \leq c + (e^\nu-1) B(X)$. We want to apply DP thresholding so that if $B(X)=0$, pass probability is $1$ and otherwise pass probability is minimum. We compute a monotone mapping $b^{-1}()$ of values so that the function $b^{-1}\circ B(X)$ has sensitivity at most $1$. \begin{lemma} Let $B()\geq 0$ be such that on any two neighboring datasets $X$ and $X'$, $B(X') \leq c + e^\nu B(X)$. Define \[ b^{-1}(y) := \frac{1}{\nu}\ln \left(1+ y \frac{e^\nu -1}{c}\right)\ . \] Then the function $b^{-1}\circ B(X)$ has sensitivity 1. That is, on any two neighboring datasets, $b^{-1}\circ B(X') \leq 1 + b^{-1}\circ B(X)$. Also, $B(X)= 0$ if and only if $b^{-1}\circ B(X)=0$. \end{lemma} \begin{proof} \ECnote{Replaced my "proof" with Eliad's proof.} \begin{align*} b^{-1} \circ B(X') &= \frac1{\nu} \ln\paren{1 + B(X')\cdot \frac{e^{\nu}-1}{c}}\\ &\leq \frac1{\nu} \ln\paren{1 + (c+e^{\nu}B(X))\cdot \frac{e^{\nu}-1}{c}}\\ &= \frac1{\nu} \ln\paren{e^{\nu} + e^{\nu}B(X) \cdot \frac{e^{\nu}-1}{c}}\\ &= 1 + \frac1{\nu} \ln\paren{1 + B(X)\cdot \frac{e^{\nu}-1}{c}}\\ &= 1 + b^{-1} \circ B(X) \end{align*} \end{proof} To DP threshold $B(X) \leq 0$, we apply $(\varepsilon,\delta)$-DP-thresholding $\leq 0$ to $b^{-1}\circ B(X)$. When $B(X)=0$ (and $b^{-1}\circ B(X)=0$), we pass with probability $1$ and otherwise the pass probability is minimum. For the analysis we consider the following: \begin{itemize} \item We now ask what is the maximum possible $B(X)$ that yields a nonzero probability of passing. The maximum pass value in terms of $b^{-1}\circ B$ is $2M(\epsilon,\delta)$, where $M(\epsilon,\delta) \approx \frac{1}{\varepsilon} \ln\left(\frac{\varepsilon}{2\delta} +1\right)$. We then have \[ B_{\max} \gets b(2 M(\epsilon,\delta)) \leq c \frac{e^{2M(\epsilon,\delta) \nu}-1}{e^\nu -1}. \] In the regime $2 M(\epsilon,\delta) \nu < 1$ we get \begin{equation} \label{Bmax:eq} B_{\max}\leq \approx 2 c M(\epsilon,\delta) \end{equation} The approximation $2 M(\epsilon,\delta) \nu < 1$ gives as a bound on $n$ (when we need this approximation). In our application $n\nu = 3C$ ($4C$ in the swap neighboring model). And $C$ is small (say $3$--$10$ see Table \eqref{gammaC:eq}). So we get $n> 6C M(\varepsilon,\delta)$. This is $20\times$ to $60\times$ $M(\varespsilon,\delta)$. \item The probability of "pass" for each value of $B\in[0, B_{\max}]$. This is needed for a more refined privacy analysis. For larger $B$ the probability of pass is lower. When $y = b^{-1}\circ B$ it is $p(y) := \pi^*_{\tau - y +2M}$. We want to use these lower probabilities to tighten the analysis. In the generalized group privacy analysis. The value of $B$ impacts the probability difference between neighboring datasets. But larger $B$ also has a lower pass probability. In particular, the pass probability with $y=M$ ($\approx B = B_{\max}/2$) is $0.5$. \ECnote{Potentially we can save up to a factor $\times 2$ in $n$ in this route.} \end{itemize} \subsubsection{Addition/deletion model} Here we have the relations (Eliad's notation). $\mu' \leq e^{c/m}\mu + \frac{2c}{\lambda}1.05 +1$. (this assuming $m>10c$ so $e^{c/m}-1 \leq 1.05 c/m +1$ We use $k := \frac{2c}{\lambda}1.05 +1$. \ECnote{Per below, we will have $c$ "small" and $m$ at least as large as $s_{\max}/2$, so with too small an $m$ we "fail".} The growth in $\mu$ is largest when we increase $m$. When we go the other way around (a point is deleted) and $m$ decreases, the mutiplicative factor is lower and $k$ is smaller by $1$. So to minimize steps always want to start with lower $m$ for same $q$. We are interested in $\omega(q,m)$. This is the smallest number of hops (through neighbors) that we can get to dataset $\omega(q,m)$ from a dataset with $q=0$ (and some $m_0$) (where $m_0$ has "success" with probability clost to $1$ (or $1-\beta$). This function by its definition and the properties above has sensitivity $1$. So the relation we use allows for the smallest possible number of hops (allowing $\mu$ to grow as fast as possible). We can treat this in a discrete way \[ \mu_{i+1} = e^{\frac{c}{m_0 +i/2}} \mu_i +k\ . \] This is an upper bound on $\mu$ that can be reached in $i$ steps when we start with data with $q=0$ and $m=m_0$. We can use the differential equation \[ \frac{\partial \mu}{\partial s} = (e^{c/(m_0 + s/2} -1)) \mu + k \] The solution has no closed form (uses exponential integrals) but can be approximated numerically. In our use, we would want to DP threshold according to $\omega$ with $0$ having probability $1$. We can upper bound $\omega(q,m)$. One way to grossly approximate it (upper bound) is by "fixing" $m_0$ on its initial value, which makes for larger increase. We get $\mu_{i+1} = e^{\frac{c}{m_0}} \mu_i +k$ The solution is \[ \mu_s = k \frac{e^{s c/m_0} -1}{ e^{c/m_0} -1} \] The smallest $m_0$ can be for $s$ steps is $m-s/2$. So we get \[ \mu_s = k \frac{e^{s c/(m-s/2)} -1}{ e^{c/(m-s/2)} -1} \] So we set $\omega(q,m)$ to be the solution for $s$ of \[ q = k \frac{e^{s c/(m-s/2)} -1}{ e^{c/(m - s/2)} -1} \] Let $s_{\max}$ be the maximum possible number of steps, roughly, \[s_{\max} = \frac{1}{\varepsilon}\ln(1/(2\beta\delta))\ .\] An even coarser bound for $s$ is the solution for $s$ of \[ q = k \frac{e^{s c/(m-s_{\max}/2)} -1}{ e^{c/(m - s_{\max}/2)} -1} \] That is, \[ s = \frac{m-s_{\max}/2}{c}\ln\left( \frac{1}{k} q \left(e^{c/(m - s_{\max}/2)} - 1\right)+1\right) \] The regime \[ s_{\max} c \ll m - s_{\max}/2 \implies m \gg S_{\max}(c+1/2)} \] Means that $s \approx q/k$. If $m$ is large we should not loose "privacy budget" to test that and then we apply success probability according to $s$. But here we pay multiplicative $c$ on $s_{\max}$ for the size of $m$. Can we do better? Perhaps we can handle smaller $m$ that is closer to $s_{\max}/2$. With larger $q$. \subsection{Tool: Generalized group privacy} The following is a sketch of a generalized group privacy lemma. {\bf To Do:} For the $O(n\log n)$, for pure DP, or for tighter analysis we need to extend it to allow larger $\Delta$ mitigated with lower success probability (rather than fixed bound on $\Delta$). \begin{lemma} Let $A(X)$ be a randomized algorithm on sets $X$ such that when $X$ and $X'$ differ in one element then $A(X)$ and $A(X')$ are $(\varepsilon,\delta)$-indistinguishable. [We use a discrete universe of elements of size $n$, to simplify presentation] Consider now a vector of probabilities $(p_1,\ldots,p_n)$ and the algorithm $A^*(p)$ that constructs $X$ by drawing each $i\in [n]$ independently with probability $p_i$ and returns $A(X)$. Consider $p$ and $p'$ such that $\norm{p-p'}_1 = \Delta$. Then $A^*(p)$ and $A^*(p')$ are $(\Delta (e^\varepsilon-1)), \Delta e^{\Delta(e^\varepsilon-1)} \delta)$-indistinguishable. \end{lemma} \begin{proof} Let $V$ be drawn from Binomial $p$ and $V'$ from binomial $p'$. Let $\Delta = \| p-p'\|_1$. Consider a joint probability space of $V$ and $V'$ as follows. The joint space is a product space of the following over coordinates $i$. We draw $u_i\sim U[0,1]$ and set $V_i=1$ if and only if $u_i \leq p_i$ and similarly $V'_i=1$ iff $u_i \leq p'_i$. Note that when $p_i \leq p'_i$ there are three possible outcomes for $V_i V'_i$ that are $11$, $01$, $00$. And symmetrically outcomes $00$, $11$, and $10$ when $p_i > p'_i$. The probability of outcomes where $V_i\not= V'_i$ is $\Delta_i = |p_i-p'_i$. We now consider a partition of the joint probability space. The partition is also product over independent coordinates. Each coordinate $i$ has two possible subparts. In a subpart for coordinate $i$, a piece has a fixed outcome for either $V_i$ or $V'_i$ as follows. If $p_i < p'_i$ there are two possible subparts with probabilities $\tau_i,1-\tau_i$, where $\tau_i := \frac{p}{1-(p'-p)}$. \[ \begin{array}{cc} V'_i = 1 & u_i \leq \tau_i\\ V_i = 0 & u_i > \tau_i \end{array} \] Note that $\tau_i < p'$ and hence $V'_i=1$ for all outcomes in the first subpart (and possibly some outcomes in the second component....). This because $p < p'$ iff $p(1-p') < p' (1-p')$ iff $p < p'- p'^2 + pp'$ iff $p < p'(1-p'+p)$. Also note that trivially $\tau_i > p_i$ and hence $V_i=0$ for all outcomes in the second subpart. Symmetrically, if $p_i > p'_i$ we use $\tau_i := \frac{p'}{1-(p-p')}$ and there are two possibly subparts \[ \begin{array}{cc} V_i = 1 & u_i \leq \tau_i \\ V'_i = 0 & u_i > \tau_i \end{array} \] The subparts have the property that there is a "fixed point" either the value of $V_i$ or the value of $V'_i$ are the same for all outcomes in the subpart. \begin{lemma} For each $i$ and subpart, the probability of $V_i\not= V_i$, conditioned on the subpart, is exactly $\Delta_i = |p'_i-p_i|$. \end{lemma} \begin{proof} Consider the first subpart above with $V'_i=1$. We have $V_i=1$ when $u_i<p$. The conditional probability that $V_i = V'_i = 1$ is $\frac{p_i}{\frac{p_i}{1-(p_i'-p_i)} }= 1 - (p_i'-p_i)$. Hence the conditional probability that $V_i \not= V'_i$ is $\Delta_i = p'_i-p_i$ \end{proof} We work with the partition of the joint probability space that is a product space of one of the two subparts from each coordinate. We now get to the group privacy analysis. For possible outputs $T$ of Algorithm $A$ we relate the probabilities that $A^*(p)\in T$ and that of $A^*(p')\in T$. Note that \[ \Pr[A^*(p)\in T] = \sum_{F\in parts} \Pr[F] \Pr_{(V,V') \sim F} [A(V) \in T]\ . \] And symmetrically for $p'$. \[ \Pr[A^*(p')\in T] = \sum_{F\in parts} \Pr[F] \Pr_{(V,V') \sim F} [A(V') \in T]\ . \] The following Claim will complete the proof \begin{claim} Within each part $F$, \[ \Pr_{(V,V') \sim F} [A(V') \in T] \leq e^{\Delta(e^\varepsilon-1)}} \Pr_{(V,V') \sim F} [A(V) \in T] + \Delta e^{\Delta(e^\varepsilon-1)} \delta \] \end{claim} \begin{proof} We consider part $F$. Let $C$ be the center vector of the part. It has some fixed coordinates $I\subset [n]$ of $V$ and some fixed coordinates $I' = [n]\setminus I$ of $V'$. We now relate the probability $\Pr_{(V,V')\sim F} A(V) \in T$ and $\Pr[A(C)\in T$. This depends on the coordinates $I'$ where $V$ is different than $C$. Note that on all coordinates where the fixed point is from $V$, there is no difference that is, no contribution to hamming distance. On coordinates $I'$ where the fixed point is from $V'$ the difference is Binomial from $\Delta_i$. The relevant L1 distance is $\Delta' := \sum_{i\in I'} \Delta_i$. Using the argument for L1, we get For pure something like $\Pr[A(V)\in T] \leq \Pr[A(C)\in T] e^{\Delta'(e^\varepsilon-1)}$. Note that the reverse inequality also holds. We should have $\Pr[A(C)\in T] \leq \Pr[A(V)\in T] e^{\Delta'(e^\varepsilon-1)}$. We similarly relate the probability that a vector $V'$ from the piece has $A(V') \in T$ to the probability that $A(C)\in T$. We similarly consider its hamming distance from $C$. Similarly, the distribution behaves like Binomials of $\Delta_i$ on the coordinates $I$. We denote $\Delta'' = \sum_{i\in I} \Delta_i$. We get $\Pr[A(V')\in T] \leq \Pr[A(C)\in T] e^{\Delta''(e^\varepsilon-1)}$. Note that $\Delta'+\Delta'' = \Delta$. Now we combine the two inequalities to obtain \[\Pr[A(V')\in T] \leq \Pr[A(C)\in T] e^{\Delta''(e^\varepsilon-1)} \leq \Pr[A(V)\in T] e^{\Delta'(e^\varepsilon-1)} e^{\Delta''(e^\varepsilon-1)} = \Pr[A(V)\in T] e^{\Delta(e^\varepsilon-1)} \] \end{proof} We sum this over all the pieces $F$ of the joint space with the respective probabilities of the pieces to get the group privacy claim. \end{proof} The following is analysis with respect to a fixed vector. Group privacy within a piece. \begin{proof} Sketch: Without loss of generality we can treat $p$ as the $0$ vector and $p'$ to be a vector with L1 norm $\Delta$. This because the set difference can be viewed as independent of the particular outcome of $p$. More formally, we can consider all randomizations (say draw a random value for each element $i$ and include if below $p_i$) that resulted in a fixed draw with $p$. Then and the respective possibilities from $p'$ and the respective distribution on set differences size. If the $L1$ norm is $\leq \Delta$ then, roughly, the probability that we get a set difference of $i\Delta$ is bounded by $1/(e i!)$ using the Poisson approximation to binomial distribution (good bound when $\Delta=1$), noting that binomial with $pn=1$ is worst case for the spread. \Enote{so again, you assume that each element is chosen w.p. $p = \frac{\Delta}{n}$ (since this should be the worst case), and that $Bin(n,p = \frac{\Delta}{n}) \approx Poisson(\Delta)$.} [note: The above will be helpful also when we incorporate success probabilities. as set difference dist holds when conditioned on a fixed outcome of $p$, including outcomes that result in "success"] We now do group privacy analysis. First fixing the outcome on $p$. Then considering the possible set differences and their probabilities. For each set difference, we can apply the known standard group privacy bound. The calculation below is for pure differential privacy $\delta=0$. For that the standard bound is that $\varepsilon$ increases by a multiplicative factor of set difference. We get the effective privacy parameter $\varepsilon^*$ so that \[ e^{\varepsilon^*} \leq \frac{1}{e} \sum_{i\geq 0} \frac{1}{i!}e^{i\Delta\varepsilon} \] (summing over probability of set difference $i\Delta$ times the group privacy bound for that set difference (multiplier $e^{i\Delta\varepsilon}$)) To Do: Do the calculation with $\delta$. Note that as the function $e^x$ is concave, so we are losing a little over standard group privacy with $\Delta$. But since the values are fairly concentrated -- due to independence -- and the $1/i!$ drop -- we should not lose much. Without independence we would be forced to use Markov and would get $1/i$ that does not drop fast enough. To Do: Some extension needed for scenario with sampling. We don't have a hard bound $\Delta$. We have possibility of larger $\Delta$ but combined with lower success probabilities. So $\Delta$ is not bounded. But the probability of reporting decreases sharply with $\Delta$. This should also similarly work. \end{proof} \section{Bounding change in probabilities} \subsection{Replacement model} In this model the number $n$ of elements is fixed for all datasets and neighboring datasets $T$ and $T'$ differ by substituting one element with another element. We denote by $A_T(x)$ the number of friends in $T$ of element $x$. We would like $x$ to be good with probability $1$ if $A_T(x)=|T|=n$ and with probability $0$ when $A_T(X) \leq |T|/2$. We use $M=n/4$. Let $z_i = A_T(x_i) - n/2$. We use the probabilities $p_T(x) = \pi^*_{M,z}$. Consider an element $x\in T \cap T'$. We have $A_{T'}(x) = A_T(x) +\{0,1,-1\}$. Hence $z' = z +\{0,1,-1\}$. We can use \eqref{ratioprop:eq} to get the bound \begin{equation} \label{diffbound:eq} |p_T(x) - p_{T'}(x)| \leq (e^\varepsilon -1) \min\{ \min\{ p_T(x), p_{T'}(x) \}, 1- \max\{ p_T(x), p_{T'}(x) \}\} + \delta \end{equation} \subsection{Addition/Deletion model} Two neighboring datasets have $|T\setminus T' \cup T'\setminus T|=1$. In particular, the number of elements has $||T|-|T'||=1$. Consider an element in the intersection $x\in T\cap T'$. If $|T'|=|T|+1$ we have $A_{T'}(x)-A_T(x) \in \{0,1\} $. We use $z= A_T(x_i) - |T|/2$ and $M = |T|/4$. We fix $\gammma$ and use $\delta = 1/(\gamma M)$ and $\varepsilon = C/M$. We assume $M \gg C$ so $e^\varepsilon -1$ is very closely approximated by $\varepsilon$. We then have $p_T(x) \gets \pi^*_{M,z}$. \begin{equation} \label{pistarcont:eq} p_T(x) \gets \pi^*_{M,z} = \left\{ \begin{array}{ll} 0 &\; \text{\small $ z \leq 0$ }\\ \frac{1}{\gamma C} \left( e^{C z/M}-1\right) &\; \text{\small $ z \in [0,M]$ }\\ 1- \frac{1}{\gamma C} \left( e^{C (2M-z)/M}-1 \right) &\; \text{\small $z \in [M,2M]$}\\ 1 &\; \text{\small $z \geq 2M$} \end{array}\right. \end{equation} For neighboring datasets we have $z' -z = \pm 1/2$ and $M' - M = \pm 1/4$ (all four combinations possible). We want to bound $|p_T(x) - p_{T'}(x)|$ similarly to \eqref{diffbound:eq}. We consider $\pi^*_{M+1/4,z-1/2} - \pi^*_{M,z}$ (The other combinations need to be considered and also differences of $(1-\pi^*)$). We bound separately the variation in $z$ and in $M$. For the variation in $z$ we have \begin{align*} \pi^*_{M,z+1/2} - \pi^*_{M,z} &\leq (e^{\varepsilon/2}-1) \min\{\pi^*_{M,z}, 1- \pi^*_{M,z+1/2}\} + \delta \frac{1}{e^{\varepsilon/2} +1} \\ &\leq \approx \frac{C}{2M} \min\{\pi^*_{M,z}, 1- \pi^*_{M,z+1/2}\} +\frac{1}{2M\gamma} \end{align*} (noting that $\pi^*_{M,z+1/2} \geq \pi^*_{M,z}$) We now consider the variation in $M$. Note that $\frac{\partial e^{\frac{Cz}{M} } }{\partial M} < 0$ and that $\frac{\partial^2 e^{\frac{Cz}{M} } }{\partial^2 M} > 0$ Therefore $\pi^*_{M,z}$ is decreasing in $M$ but the rate of decrease is decreasing. Thus for $z\in [0,M]$ \[ \pi^*_{M,z} - \pi^*_{M+1/4,z} \leq -\frac{1}{4} \frac{\partial \pi^*_{y,z}}{\partial y}(y=M) = -\frac{1}{4 C\gamma} \frac{\partial e^{\frac{C}{M} z} }{\partial M} = \frac{z}{4M^2\gamma}e^{\frac{C}{M} z} \] \[ = \frac{z}{4M^2\gamma} (\gamma C \pi^*_{M,z} +1) = \frac{C}{4M}\frac{z}{M} \pi^*_{M,z} + \frac{z}{M} \frac{1}{4M\gamma} \] \ECnote{Need to also consider $z\in [M,2M]$ and the patch area} For $z\in [0,M]$, \[\pi^*_{M,z} = \frac{1}{\gamma M} \frac{e^{\frac{C}{M} z} -1}{e^{\frac{C}{M}} -1} \approx \frac{1}{C\gamma}(e^{\frac{C}{M} z} -1) \] Combining we obtain (we can use this for all combinations) \[ \pi^*_{M,z+1/2} - \pi^*_{M+1/4,z} \leq \frac{3}{4} \frac{C}{M} \pi^*_{M,z} + \frac{3}{4}\frac{1}{\gamma M} \] \ECnote{We should be able to replace $\pi^*_{M,z}$ in the r.h.s. with its minimum with $1-\pi^*_{M,z}$} \ignore{ ***************** Note that $(A_T(x)-|T|/2) - (A_{T'}(x)-|T'|/2) \in \pm\tfrac{1}{2}$. In the good elements algorithm, we use $\eta = 1/(\gamma n)$, set $M(\eta,\nu)= n/2$ and get that $n \nu = C(\gamma)$. Where $C(\gamma)$ is the solution of $C = 2\ln(\frac{\gamma C}{2} +1)$. Consider the respective $\pi^*_z$ with $(\nu,\delta)$ \eqref{pistarcont:eq}. With respect to fixed $\gamma$ and varying $n$ we use the notation $\pi^*_{n,z}$. An element $x$ gets probability \[ p_T(x) = \pi^*_{2A(x)-n} .\] We now consider two neighboring datasets and $x\in T\cap T'$ and $p_T(x)$ and $p_{T'}(x)$. We consider thw two values that can change separately: $2A(x)-n$ and $n$. The latter also determines $\eta,\nu,M$. Both values can change by $\pm 1$ (all combinations are possible). \ECnote{Trying to gain the X2. But might not be able to and resort if change due to $n$ is not of a smaller order.} Suppose if only $2A(x)-n$ changes (this is hypothetical. $n$ must change also... but for analysis of variation). Then we can use \eqref{ratioprop:eq} as is. We get $p' \leq e^\nu p + \eta$ and $(1-p') \leq e^\nu (1-p) + \eta$. $\pi^*_{n,z} - \pi^*_{n,z+1} \leq \nu \pi^*_{n,z} + \eta$ (and same for complements etc). Suppose $2(A(x))-n$ stays the same and $n$ changes by $1$. We get $\eta'= \frac{n}{n+1}\eta$ and $\nu'= \frac{n}{n+1}\nu$. We can assume small $\nu$ so \[\pi^*_z \approx \frac{\eta}{\nu} (e^{\nu z}-1) = \frac{1}{C \gamma} (e^{Cz/n}-1)\] ($z = 2A(x)-n$ varies from $0$ to $n$). \[ \pi^*_{n,z} - \pi^*_{n+1,z} = \frac{1}{C\gamma}(e^{Cz/n} - e^{Cz/(n+1)}) \approx -\frac{1}{C\gamma} \frac{\partial e^{Cz/n}}{\partial{n}} = \frac{z}{n^2 \gamma} e^{Cz/n} \] \[ = \frac{z}{n^2 \gamma} \left( C\gamma \pi^*_{z,n} +1\right) = \frac{z}{n} \nu \pi^*_{z,n} + \frac{z}{n} \eta \] } \section{$O(n^2)$ Good elements algorithm} The good elements algorithms has two components. The first is to identify a set $T_G$ of good elements by testing each element. We also compute the expected value $B:= E[|T_G|]$ of the number of good tuples. The second is to decide, based on the $B$, if to fail (report nothing) or succeed and report $T_G$. \paragraph{Computing set of good elements $T_G$} The input is a set of elements $T$ and a "like" predicate $x\sim y$. For each element $x$ we consider the number of elements in $T$ that like $x$: \[A(x) := \sum_{y\in T} I_{x\sim y}\ .\] \begin{enumerate} \item Input: A set of elements $T$ with $|T|=n$. A predicate on elements $x\sim y$. \item Output: A set of good elements $T_G\subset T$ that must include all perfect elements $A(x)=n$, and may not include any bad element $A(x)\leq n/2$. Also compute the value $B := E[|T_G|]$ for that data set. \item $B\gets 0$ (initialize value of $E[|T_G|]$) \item Set $M\gets n/4$ and $\gamma$. \item For each element $x \in T$: \begin{enumerate} \item $A(x) \gets \sum_{y\in T} I_{x\sim y}$. \item Include $x$ in $T_G$ with probability $\pi^*_{M,A(x)-n/2}$ (probability is $1$ when $A(x)=n$ and is $0$ when $A(x)\leq n$). \item $B \gets B+ \pi^*_{M, A(x) -n/2}$ (probability of $x$ being labeled good by DP-threshold) \end{enumerate} \item $T_B \gets T\setminus T_G$. Return $T_G$ and $B$ \end{enumerate} \subsection{Local sensitivity analysis} The good elements set $T_G$ is drawn according to a vector of probabilities \[ r(T) := (p(A(x))_x = (\pi^*_{M, A(x)-n/2})_{x}\ .\] (For convenience we use vector notation while treating these vectors as sparse over the universe of elements. Keeping in mind that the universe might be continuous) Recall that $E[|T_G|] = \norm{r(T)}_1$. For two neighboring datasets $T$ and $T'$ ($|T\setminus T'|\leq 1$ and vice versa). We can consider the vectors $r(T)$ and $r(T')$. We bound the extent in which the expected number of bad elements can increase between neighboring datasets. We also bound the L1 distance of the probability vectors. \begin{lemma} \label{localsenseitivity:lemma} Let $T$ and $T'$ be neighboring. Then \begin{align} \norm{r(T') - r(T)}_1 &\leq 1+ (3C/n) \norm{r(T)}_1+ 3/\gamma \end{align} in the addition/deletion model. The bound is $1+ (4C/n) \norm{r(T)}_1+ 4/\gamma$ in the swap model. \end{lemma} \ECnote{This can be tightened to $\min\{r, r', 1-r, 1-r'\}$ in the r.h.s. Entries over $1/2$ change proportionally to $1-r()$} \ignore{ \begin{proof} \ECnote{Needs to be changed to new notation} Consider $x\in T\cap T'$. We have $A_T(x) = A_{T'}(x) \pm 1$ and $q(A_{T'}(x)) \leq q(A_T(x)) e^\nu + \eta$ and $p(A_{T'}(x)) \leq p(A_T(x)) e^\nu + \eta$ (holds by \cref{ratioprop:eq}). \begin{align*} E[|T'_B|] &= \sum_{x\in T'} q(A_{T'}(x)) \leq 1 + \sum_{x\in T'\cap T} q(A_{T'}(x)) \leq 1 + \sum_{x\in T'\cap T} q(A_{T}(x)-1) \\ &\leq 1+ e^\nu \sum_{x\in T'\cap T} q(A_T(x)) + n\eta \leq 1 + e^\nu E[|T_B|] + n\eta \end{align*} This because the element that is different can contribute at most $1$ and for all other tuples $A(x)$ changed by at most $1$ and we use~\eqref{ratioprop:eq}. \ECnote{ The argument is nearly identical for deletion/addition. We consider the difference with the different element (not in $x \not\in T \cap T'$) removed. We then see that for the common element $x \in T \cap T'$ $|T|-A_T(x)$ and $|T'|-A_{T'}(x)$ differ by at most $1$. Then everything else is the same. } Similarly \begin{align*} \norm{r(T') - r(T)}_1 &\leq 1+ \sum_{x\in T\cap T'} q(A_{T'}(x))-q(A_{T}(x)) \\ &\leq 1+ (e^\nu-1)\sum_{x\in T} q(A_{T}(x)) + n \eta = 1+ (e^\nu-1) \norm{r(T)}_1+ n\eta \end{align*} Comment: Note that for $q > 1/2$, we can use a tighter bound. This is relevant if we use $T_G$, that is large. We can bound $E[|T'_G|] - E[|T_G]]$ it in terms of the smaller of $T_B$ or $T_G$ or more finely, by considering $q$. We get \[ E[|T'_B|] - E[|T_B]] \leq 1+n\eta + (e^\nu-1)\min\{E[|T_B|],E[|T_G|] \} \] \end{proof} [Comment. We would want to balance $\eta$ and $\nu$ given $L$ as to minimize the L1 distance in our regime of interest] } \subsection{putting it together} Comment: Need to set privacy parameters so it composes to what we want. We apply DP thresholding with varying local sensitivity to $E[|T_B|]$ , with $c=1+n\eta$. \begin{enumerate} \item Apply the good elements subroutine to compute the set $T_G$ and $y \gets E[|T_B|] = \sum_{x\in T} (1- p_T(x))$ \item Recall that the local sensitivity of $E[|T_B|]$ is $(1+3/\gamma) +e^{3C/n} E[|T_B|]$ (Lemma~\ref{localsensitivity:lemma}). (there is "$4$" instead of "$3$" in swap model). We apply thresholding with varying local sensitivity, using $\nu = 3C/n$ and $c=1+3/\gamma$: We set $m \gets b^{-1}(y)$ which has sensitivity $1$. We apply $(\varepsilon,\delta)$ DP thresholding with $\leq 0$. If we fail, we return $\bot$. Otherwise, we return $T_G$.\Enote{So by thresholding you mean that we compute $\hat{m} = m + {\rm Lap}(1/\varepsilon)$, and we pass the test if $\hat{m} \leq 0$?}\ECnote{Yes. Can use Laplace or truncated Laplace. Only that this is lossy and wanted to squeeze the constants. So we use a precise optimal thresholding} By design, the threshold "pass" bit is $(\epsilon,\delta)$ DP.\Enote{Do we need the $\delta$ here?}\ECnote{We could remove it. It seems. I did not check carefully. But then we need to work with high probability. Which we will need to anayway for the sampling.... And the analysis is not completely clean 0/1. So it is cleaner to first use $\delta$.} \item We obtain that a pass is possible (see \eqref{Bmax:eq}) only if $E[|T_B|] \leq B_{\max} \approx 2(1+ 3/\gamma) M(\varepsilon,\delta). The $L1$ distance between two neighboring datasets is at most \[ 1 + 3\frac{C}{n} B + 3/\gamma \] If we use $B_{\max}$, we get L1 distance \[ 1 + 6C (1+3/\gamma)\frac{1}{n} M(\varepsilon,\delta) + 3/\gamma \] \ECnote{The "$1$" comes from the different element. In the others we have an undertanding on the difference per attribute} Using values from Table \eqref{gammaC:eq} we get that with $n \geq 3C B_{\max} = 6C(1+3/\gamma) M(\varepsilon,\delta)$ the distance is at most $2+3/\gamma$. So $\gamma,C = 3.4,1$ we get distance $<3$ and $n=12 M(\varepsilon,\delta)$. With $\gamma,C = 10 ,2.6$ we get distance $2.3$ for $n= 90 M(\varepsilon,\delta)$ and distance $1.8$ for $n= 180 M(\varepsilon,\delta)$ \ignore{ \[\Delta \leq c + (e^\nu-1) B_{\max} \approx 1+ n\eta + \nu B_{\max} .\] (approximation holds when $\nu\ll 1$. We have that $n \nu < 30$ (for $\gamma = 100$), so this holds for small values of $n$, say $n<100$). We want $\Delta$ close to $1$ but also small $n$. We use the relation between $\gamma = 1/(\eta n)$ and $(n\nu)$ as a function of $\gamma$ (see \eqref{gammannu:eq}). Define \[\ell(\varepsilon,\delta) = (1+ \frac{1}{\varepsilon} \ln (\min\{1,\varepsilon\}/(2\delta)) \] We get \[ \Delta \leq 1 + 1/\gamma + 2(1+1/\gamma)(n\nu) \frac{\ell}{n}\ . \] If we use $\gamma=1$ we get $\Delta = 2 + 20 \frac{\ell}{n}$. So for say, $n = 20\ell$ we get $\Delta=3$. If we use $\gamma=100$ we get $\Delta = 1.01 + 2.02 * 29 * \frac{\ell}{n}$. So for $n=120 \ell$ we get $\Delta \approx 1.5$ and for $n=240 \ell$ we get $\Delta \approx 1.25$. } \ECnote{Recall that this is all for worst case $B$. But this $B$ has $\delta$ probability only and $\tfrac{1}{2} B_\max$ has probability about $1/2$. This needs to be integrated in the group privacy analysis.} We apply the generalized group privacy with $\Delta$ to obtain the claimed property. \end{enumerate} \ECnote{We can optimize a bit more the minimum $n$ (factor of 2) by not using the maximum $B_{\max}$ and accounting in the privacy analysis for the lower reporting probability when $b^{-1} B$ increases. } \ECnote{Comment: Potentially we can use correlated sampling techniques to have a non-negatively correlated instead of independent choice so that the number of bad elements is very close to its expectation and the actual difference between neighboring datasets is even more concentrated around the L1 distance. But not sure it is worth the work.} \section{Refined analysis} Group privacy: Let $G$ be a randomized algorithms that is applied to a set $T$ outputs a set $D=G(T)$. Let $A$ be $(\varepsilon,\delta)$-DP. Suppose that for any two neighboring datasets $T$ and $T'$ we can partition the output distributions of $G(T)$ and $G(T')$ to matching events $B(T,i)$ and $B(T',i)$ so that the following holds: For all $i$, $\Pr_T[B(T,i)] = \Pr_{T'}[B(T',i)]$. For all $i$, $B(T,i)$ contains exactly one set $D$. Let $A$ be an algorithm that on neighboring datasets produces outputs that are $(\varepsilon,\delta)$-indistinguishable. Consider $A|p(D)$ that outputs $A(D)$ with probability $p$ and $\bot$ otherwise. Then the outputs of $A|p(D)$ on neighboring dataset are $(\varepsilon, p\delta)$-indistinguishable (check). Let $A$ be an algorithm that on neighboring datasets produces outputs that are $(\varepsilon,\delta)$-indistinguishable. Let $S$ be a predicate that is $(\varepsilon',\delta')$-indistinguishable on neighboring datasets. Let $A|S (D)$, which outputs $A(D)$ if $S(D)$. {\bf say something that gains from the sampling by $S$.} \section{$O(n\log n)$ solution for friendly elements } Incorporating sampling: Now we want to be efficient. Instead of counting exactly the number of liking tuples, for each $x$ we sample $S$ tuples. We then compute $A(x)$ as the number of tuples in $S$ that like $x$. (better with different sample for each $x$ for independence). \paragraph{Sample size:} The sample size $s$ should be large enough so that say $2/3$ likes on the sample imply with very high probability that there are $> n/2$ likes on the full set. We need the sample to be at least $a \log(n)$. We then do DP thresholding on the stretch with $2L''+2 = s/3$ . And then $\nu'$ the solution of $L(\nu,\delta) = L''$. We get $\nu' \approx 3\ln(1/2\delta)/s$. The sampling will decrease the ratio of neighboring $q(i)$ by $s/n$, so we get the guarantees we need. So the only constraint on sample size is ensuring that $2/3$ filters out tuples with $\leq n/2$ friends. With the crude multiplicative Chernoff bound $\delta=1/3$ and we get $s \approx 72\ln(n)$ to guarantee that probability $1/n^2$ of passing a tuple with $\leq n/2$ friends. But this constant can be tightened by using the raw Chernoff bounds. \paragraph{thresholding by $|T_B|$ and not its expectation} Thresholding the actual number of bad tuples $T_B$ and not its expectation. Now L1 norm of neighboring and also worst-case local sensitivity can increase. But we don't need to account for worst case as this is mitigated with higher fail probability when $E[|T_B|]$ is larger. We need to do the computation but it should balance out. Actually might also reduce the factor 2 due to "largest" $E[|T_B|]$ that can pass the threshold. Instead when mitigating by likelihood it should help. \section{Comments on application of private friendly elements} In the applications for clustering, each element is a $k$-tuple obtained by applying a clustering algorithm on a part of the data. Comments: If we can assume that the algorithm that returns the tuples exposes privacy of points at random (return a random member of the cluster) we can integrate this into the privacy analysis which will allow for a larger $\delta$ (in terms of number of inverse (poly) number of tuples rather than numbers of points). The number of tuples needed does not grow with the number of points in the datasets. We bound sensitivity in terms of neighboring tuples. If the algorithm that generates tuples has the property that one member of the tuple changes on neighboring point sets then we can save in the group privacy argument. The solution can be modified to problem specs where elements are considered perfect if the like all except for $a$ elements and require success when at most $b$ elements are not perfect. This extends the applications. In application to clustering. We still can proabbly avoid solving $n$ small problems. In the non-private setting, one small problem suffices. What we can do is emulate. Solve one problem. Then process and "emulate" output of $n$ problems. This involves discarding all ambiguous points. Then aggregate. \printbibliography \section{Our Algorithms}\label{sec:finding-averages} In this section we present two $(\varepsilon,\delta)$-differentially private algorithms for the $k$-tuple clustering problem: $\mathsf{PrivatekAverages}$ and $\mathsf{PrivatekNoisyCenters}$. Algorithm $\mathsf{PrivatekAverages}$ attempts to solve the problem by determining the clusters in ${\rm Partition}({\cal T})$ and then privately estimating the average of each cluster using the algorithm from \cref{prop:approx-aver-Rd}. Algorithm $\mathsf{PrivatekNoisyCenters}$, on the other hand, does not operate by averaging clusters. Instead, it first selects one of the input tuples $X \in {\cal T}$ (in a special way), and then adds a (relatively small) Gaussian noise to this tuple.\footnote{We remind that all the tuples in this work are \emph{unordered}, and indeed the privacy analysis of our algorithms relies on it (i.e., the domain of outputs is all the unordered $k$-tuples, and $(\varepsilon,\delta)$-indistinguishability holds for each subset of this domain). Both algorithms share the same first step, which is to call $\mathsf{PrivateTestPartition}$ (\cref{alg:TestPar}) that privately decides whether ${\cal T}$ is $\ell$-nearly partitioned by $\Delta$-far balls or not (for small $\ell$), and if so, determines (non-privately) a set of $\Delta$-far balls ${\cal B} = \set{B_1,\ldots,B_k}$ that $\ell$-nearly partitions ${\cal T}$. In \cref{sec:alg-test-close-tuples} we describe Algorithm $\mathsf{PrivateTestCloseTuples}$, which is the main component of $\mathsf{PrivateTestPartition}$. In \cref{sec:alg-test} we describe $\mathsf{PrivateTestPartition}$ and state its properties. Then, in \cref{sec:alg-find-averages} we describe $\mathsf{PrivatekAverages}$ and prove its guarantees, and in \cref{sec:alg-prac-find-averages} we describe $\mathsf{PrivatekNoisyCenters}$ and prove its guarantees. \subsection{Algorithm $\mathsf{PrivateTestCloseTuples}$}\label{sec:alg-test-close-tuples} In this section we describe $\mathsf{PrivateTestCloseTuples}$ (\cref{alg:TestCloseTuples}), which given two multisets of $k$-tuples ${\cal T}_1$ and ${\cal T}_2$, privately checks whether the tuples in ${\cal T}_1$ are close to the tuples in ${\cal T}_2$. \begin{algorithm}[$\mathsf{PrivateTestCloseTuples}$]\label{alg:TestCloseTuples} \item Input: Multisets ${\cal T}_1 \in (({\mathbb R}^d)^k)^m$ and ${\cal T}_2 \in (({\mathbb R}^d)^k)^n$, a privacy parameter $\varepsilon_1 \in (0,1]$ for ${\cal T}_1$, a privacy parameters $\varepsilon_2 \in (0,1]$ for ${\cal T}_2$, a confidence parameter $\beta \in (0,1]$, and a separation parameter $\Delta > 6$. \item Operation:~ \begin{enumerate} \item For each $X = \set{\px_1,\ldots,\px_k} \in {\cal T}_1$:\label{step:loop-over-R} \begin{enumerate} \item Let ${\cal B}_{X} = \set{B_i^{X} = B(\px_i, r_i^{X})}_{i=1}^k$, where $r_i^X = \frac1{\Delta}\cdot \min_{j \neq i} \norm{\px_i - \px_j}$.\label{step:B_x} \item Let $\ell_{X} = \size{\set{Y \in {\cal T}_2 \colon Y\text{ is \textbf{not} partitioned by }{\cal B}_{X}}}$.\label{step:l_x} \item Let $\hat{\ell}_{X} = \ell_{X} + {\rm Lap}\paren{\frac{m}{\varepsilon_2}}$.\label{step:hl_x} \item Set ${\rm pass}_{X} = \begin{cases} 1 & \hat{\ell}_{X} \leq \frac{m}{\varepsilon_2} \cdot \log\paren{\frac{m}{\beta}}\\ 0 &\text{otherwise} \end{cases}$.\label{step:pass} \end{enumerate} \item Let $s = \sum_{X \in {\cal T}_1} {\rm pass}_{X}$ and compute $\hat{s} \gets s + {\rm Lap}\paren{\frac1{\varepsilon_1}}$.\label{step:s} \item If $\hat{s} < m - \frac1{\varepsilon_1} \log\paren{\frac1{\beta}}$, set ${ Status} = \text{"Failure"}$. Otherwise, set ${ Status} = \text{"Success"}$.\label{step:status} \item If ${ Status} = \text{"Success"}$ and ${\rm pass}_{X} = 1$ for at least one $X \in {\cal T}_1$, let $X^*$ be the first tuple in ${\cal T}_1$ with ${\rm pass}_{X^*} = 1$ and set ${\cal B} = {\cal B}_{X^*}$. Otherwise, set ${\cal B}$ to be a set of $k$ empty balls.\label{step:x-star} \item Output $({ Status},{\cal B})$. \end{enumerate} \end{algorithm} \subsubsection{Properties of $\mathsf{PrivateTestCloseTuples}$} The properties of $\mathsf{PrivateTestCloseTuples}$ are summarized by the following claims. \begin{claim}[Correctness]\label{claim:correctness-closeTuples} Assume that ${\cal T} = {\cal T}_1 \cup {\cal T}_2$ is partitioned by $(2\Delta+2)$-far balls. Then with probability $1-\beta$, when executing $\mathsf{PrivateTestCloseTuples}$ on input ${\cal T}_1,{\cal T}_2,\varepsilon_1,\varepsilon_2,\beta$,$\Delta$, it outputs $(\text{``Success"},{\cal B})$, where ${\cal B}$ is a set of $\Delta$-far balls that partitions ${\cal T}$. \end{claim} \begin{proof} We first prove that for every $X \in {\cal T}_1$, the set of balls ${\cal B}_{X} = \set{B_i^{X} = B(\px_i, r_i^{X})}_{i=1}^k$ from Step~\ref{step:B_x} is a set of $\Delta$-far balls that partitions ${\cal T}_2$. Fix $X = \set{\px_1,\ldots,\px_k} \in {\cal T}_1$, let ${\cal B} = \set{B_i = B(\pc_i, r_i)}_{i=1}^k$ be a set of $(2\Delta+2)$-far balls that partitions ${\cal T}$ (such a set exists by assumption), and assume w.l.o.g. that $\forall i \in [k] \colon \px_i \in B_i$. In addition, recall that $r_i^{X} = \frac1{\Delta}\cdot \min_{j \neq i} \norm{\px_i - \px_j}$ (Step~\ref{step:B_x}), and therefore, by definition it holds that ${\cal B}_{X}$ is a set of $\Delta$-far balls. It is left to prove that it partitions ${\cal T}$. Note that for every $i \neq j$ it holds that \begin{align*} \norm{\px_i - \px_j} &\geq \norm{\pc_i - \pc_j} - \norm{\px_i - \pc_i} - \norm{\px_j - \pc_j}\\ &> (2\Delta+2) \cdot \max\set{r_i,r_j} - r_i - r_j\\ &\geq 2\Delta \cdot \max\set{r_i,r_j} \end{align*} Therefore, for every $i \in [k]$, $r_i^{X} = \frac1{\Delta}\cdot \min_{j \neq i} \norm{\px_i - \px_j} > 2\cdot r_i$. Since $\px_i \in B_i$, we conclude that $B_i \subseteq B_i^{X}$, which yields that ${\cal B}_{X}$ partitions ${\cal T}$. Therefore, for every $X = \set{\px_1,\ldots,\px_k} \in {\cal T}_1$ it holds that $\ell_{X}$, the value from Step~\ref{step:l_x}, is $0$. Hence, by \cref{fact:laplace-concent} and the union bound, with probability $1-\frac{\beta}2$ it holds that $\forall X \in {\cal T}_1:\text{ }{\rm pass}_{X} = 1$, which yields that $s = m$ (where $m = \size{{\cal T}_1}$). When $s = m$, we obtain by \cref{fact:laplace-concent} that with probability $1- \frac{\beta}{2}$ it holds that $\hat{s} \geq s - \frac1{\varepsilon_1} \log(1/\beta) = m - \frac1{\varepsilon_1} \log(1/\beta)$, i.e., ${ Status} = \text{``Success''}$. This concludes the proof of the claim. \end{proof} \begin{claim}[${ Status}$ is $\varepsilon_1$-DP w.r.t. ${\cal T}_1$]\label{claim:status-is-private-T1} Let ${\cal T}_1,{\cal T}_1' \in (({\mathbb R}^d)^k)^m$ be two neighboring databases, let ${\cal T}_2 \in (({\mathbb R}^d)^k)^n$, and consider two independent executions $\mathsf{PrivateTestCloseTuples}({\cal T}_1, {\cal T}_2)$ and $\mathsf{PrivateTestCloseTuples}({\cal T}_1', {\cal T}_2)$ (with the same parameters $\varepsilon_1,\varepsilon_2,\beta, \Delta$). Let ${ Status}$ and ${ Status}'$ be the status outcomes of the two executions (respectively). Then ${ Status}$ and ${ Status}'$ are $\varepsilon_1$-indistinguishable. \end{claim} \begin{proof} Note that each $k$-tuple $X \in {\cal T}_1$ can affect only the bit ${\rm pass}_{X}$. Therefore, by the properties of the Laplace mechanism (\cref{fact:laplace}) and post-processing (\cref{fact:post-processing}), it holds that ${ Status}$ and ${ Status}'$ are $\varepsilon_1$-indistinguishable. \end{proof} \begin{claim}[${ Status}$ is $\varepsilon_2$-DP w.r.t. ${\cal T}_2$]\label{claim:status-is-private-T2} Let ${\cal T}_2,{\cal T}_2' \in (({\mathbb R}^d)^k)^n$ be two neighboring databases, let ${\cal T}_1 \in (({\mathbb R}^d)^k)^m$, and consider two independent executions $\mathsf{PrivateTestCloseTuples}({\cal T}_1, {\cal T}_2)$ and $\mathsf{PrivateTestCloseTuples}({\cal T}_1, {\cal T}_2')$ (with the same parameters $\varepsilon_1,\varepsilon_2,\beta$). Let ${ Status}$ and ${ Status}'$ be the status outcomes of the two executions (respectively). Then ${ Status}$ and ${ Status}'$ are $\varepsilon_2$-indistinguishable. \end{claim} \begin{proof} For each $X \in {\cal T}_1$, let $\ell_{X}, {\rm pass}_{X}$ and $\ell_{X}', {\rm pass}_{X}'$ be the values computed in the loop \ref{step:loop-over-R} in the two executions (respectively). Since $\size{\ell_{X} - \ell_{X}'} \leq 1$, we obtain by the properties of the Laplace mechanism, along with post-processing, that ${\rm pass}_{X}$ and ${\rm pass}_{X}'$ are $\frac{\varepsilon_2}{m}$-indistinguishable. Hence, by basic composition (\cref{thm:composition1}) we deduce that $\set{{\rm pass}_{X}}_{X \in {\cal T}_1}$ and $\set{{\rm pass}_{X}'}_{X \in {\cal T}_1}$ are $\varepsilon_2$-indistinguishable, and we conclude by post-processing that ${ Status}$ and ${ Status}'$ are $\varepsilon_2$-indistinguishable. \end{proof} The following claim states that when $\mathsf{PrivateTestCloseTuples}({\cal T}_1,{\cal T}_2)$ outputs $(\text{``Success''},{\cal B})$, then with high probability, ${\cal T}_2$ is almost partitioned by ${\cal B}$. \begin{claim}[On success, ${\cal B}$ almost partitions ${\cal T}_2$]\label{claim:main-T2} Let $\delta > 0$, let ${\cal T}_1 \in (({\mathbb R}^d)^k)^m$ and ${\cal T}_1 \in (({\mathbb R}^d)^k)^n$, and assume that $m > \frac1{\varepsilon_1}\cdot \paren{2 \log(1/\delta) + \log(1/\beta)}$. Consider a random execution of \\$\mathsf{PrivateTestCloseTuples}({\cal T}_1,{\cal T}_2,\varepsilon_1,\varepsilon_2,\beta)$, and let $({ Status},{\cal B})$ be the outcome of the execution. Let $S$ be the event that ${ Status} = \text{"Success"}$, and let $E \subseteq S$ be the event that ${\cal T}_2$ is $\ell$-nearly partitioned by ${\cal B}$, where $\ell = \frac{m}{\varepsilon_2} \cdot \log\paren{\frac{m}{\beta \delta}}$. Then the following holds: If $\pr{S} \geq \delta$, then $\pr{E \mid S} \geq 1 - \delta$. \end{claim} \begin{proof} Let $\set{{\rm pass}_{X}}_{X \in {\cal T}_1}$ be the values from \cref{alg:TestPar} in the execution $\mathsf{PrivateTestCloseTuples}({\cal T}_1,{\cal T}_2,\varepsilon_1,\varepsilon_2,\beta)$, and let $W$ be the event that there exists $X \in {\cal T}_1$ with ${\rm pass}_{X} = 1$. Note that \begin{align*} \pr{\neg W \mid S} \leq \frac{\pr{S \mid \neg W}}{\pr{S}} \leq \frac{\pr{{\rm Lap}(1/\varepsilon_1) > \frac{2}{\varepsilon_1}\cdot \log\paren{\frac1{\delta}}}}{\delta} \leq \frac{\delta^2}{2 \delta} \leq \frac{\delta}2, \end{align*} where the second inequality holds since $\pr{S} \geq \delta$ and since $m - \frac1{\varepsilon_1} \log\paren{\frac1{\beta}} > \frac{2}{\varepsilon_1}\cdot \log\paren{\frac1{\delta}}$, and the third one holds by \cref{fact:laplace-concent}. Therefore, in the following we prove the claim by showing that \begin{align}\label{eq:E-mid-W-goal} \pr{E \mid W \land S} \geq 1 -\frac{\delta}2 \end{align} Let $X^*$ be the tuple from Step~\ref{step:x-star} (it exists when $W \land S$ occurs), and recall that ${\cal B} = {\cal B}_{X^*}$ and that $\ell_{X^*}$ is the minimal value such that ${\cal T}_2$ is $\ell_{X^*}$-nearly partitioned by ${\cal B}$. Since ${\rm pass}_{X^*} = 1$, it holds that $\hat{\ell}_{X^*} = \ell_{X^*} + {\rm Lap}(m/\varepsilon_2) \leq \frac{m}{\varepsilon_2}\cdot \log\paren{\frac{m}{\beta}}$. \cref{eq:E-mid-W-goal} now follows by the following calculation. \begin{align*} \pr{E \mid W \land S} &= \pr{\ell_{X^*} > \frac{m}{\varepsilon_2} \cdot \log\paren{\frac{m}{\beta \delta}} \mid \hat{\ell}_{X^*} \leq \frac{m}{\varepsilon_2}\cdot \log\paren{\frac{m}{\beta}}}\\ &\leq \pr{{\rm Lap}(m/\varepsilon_2) < -\frac{m}{\varepsilon_2}\cdot \log\paren{\frac{1}{\delta}}}\\ &\leq \frac{\delta}{2}, \end{align*} where the last inequality holds by \cref{fact:laplace-concent}. \end{proof} \subsection{Algorithm $\mathsf{PrivateTestPartition}$}\label{sec:alg-test} In this section we describe $\mathsf{PrivateTestPartition}$ (\cref{alg:TestPar}) and state its properties. In the following, we define $m$ and $\varepsilon_1$ (functions of $n,\varepsilon,\delta,\beta$) that are used by $\mathsf{PrivateTestPartition}$. \begin{definition}\label{def:m} Let $m = m(n,\varepsilon,\delta,\beta)$ be the smallest integer that satisfies $m > \frac1{\varepsilon_1} \cdot \paren{2 \log(1/\delta) + \log(1/\beta)}$, where $\varepsilon_1 = \log(\frac{\varepsilon n}{2 m} - 3)$. \end{definition} The dependence between $m$ and $\varepsilon_1$ for Algorithm $\mathsf{PrivateTestPartition}$ is due to the choice of ${\cal T}_1$ as an $m$-size random sample of ${\cal T}$. A smaller $m$ allows for a larger value of $\varepsilon_1$ for the same overall privacy, by a sub-sampling argument (e.g., \cref{lem:subsampling}). We note that for $n \gg 1/\varepsilon$ and $\beta,\delta \geq \frac{1}{{\rm poly}(n)}$, we have $\varepsilon_1 = \Theta(\log n)$, which yields that $m = O(1)$. For smaller values of $\delta$, we obtain that $m = O\paren{\frac{\log(1/\delta)}{\log n}}$. \begin{algorithm}[$\mathsf{PrivateTestPartition}$]\label{alg:TestPar} \item Input: A multiset ${\cal T} \in (({\mathbb R}^d)^k)^n$, privacy parameters $\varepsilon,\delta \in (0,1]$, confidence parameter $\beta \in (0,1]$, and separation parameter $\Delta > 6$. \item Operation:~ \begin{enumerate} \item Let $m$ and $\varepsilon_1$ be the values from \cref{def:m} w.r.t. $n,\varepsilon,\delta,\beta$, and let $\varepsilon_2 = \varepsilon/2$. \item Let ${\cal T}_1$ be a uniform sample of $m$ $k$-tuples from ${\cal T}$ (without replacement), and let ${\cal T}_2 = {\cal T}$. \item Output $({ Status},{\cal B}) = \mathsf{PrivateTestCloseTuples}({\cal T}_1,{\cal T}_2,\varepsilon_1,\varepsilon_2,\beta,\Delta)$. \end{enumerate} \end{algorithm} \subsubsection{Properties of $\mathsf{PrivateTestPartition}$} The following claim is an immediate corollary of \cref{claim:correctness-closeTuples} \begin{claim}[Correctness]\label{claim:correctness} Assume that ${\cal T}$ is partitioned by $(2\Delta+2)$-far balls. Then with probability $1-\beta$, when executing $\mathsf{PrivateTestCloseTuples}$ on input ${\cal T},\varepsilon,\delta,\beta,\Delta$, it outputs $(\text{``Success"},{\cal B})$, where ${\cal B}$ is a set of $\Delta$-far balls that partitions ${\cal T}$. \end{claim} The following claim is a corollary of \cref{claim:status-is-private-T1,claim:status-is-private-T2}. \begin{claim}[${ Status}$ is private]\label{eq:status-is-private} Let ${\cal T}$ and ${\cal T}'$ be two neighboring databases, and consider two independent executions $\mathsf{PrivateTestPartition}({\cal T})$ and $\mathsf{PrivateTestPartition}({\cal T}')$ (with the same parameters $\varepsilon,\delta,\beta$). Let ${ Status}$ and ${ Status}'$ be the status outcomes of the two executions (respectively). Then ${ Status}$ and ${ Status}'$ are $\varepsilon$-indistinguishable. \end{claim} \begin{proof} As a first step, assume that we have two (different) copies of ${\cal T}$, call them $\tilde{{\cal T}}_1$ and $\tilde{{\cal T}}_2$, where ${\cal T}_1$ is chosen from the copy $\tilde{{\cal T}}_1$, and ${\cal T}_2$ is chosen from the copy $\tilde{{\cal T}}_2$, and let $(\tilde{{\cal T}}_1',\tilde{{\cal T}}_2')$ be a neighboring database of $(\tilde{{\cal T}}_1,\tilde{{\cal T}}_2)$. If $\tilde{{\cal T}}_2$ and $\tilde{{\cal T}}_2'$ are neighboring (and $\tilde{{\cal T}}_1 = \tilde{{\cal T}}_1'$), we obtain by \cref{claim:status-is-private-T2} that ${ Status}$ and ${ Status}'$ are $\varepsilon/2$-indistinguishable. Therefore, assume that $\tilde{{\cal T}}_1$ and $\tilde{{\cal T}}_1'$ are neighboring (and $\tilde{{\cal T}}_2 = \tilde{{\cal T}}_2'$). By \cref{claim:status-is-private-T1}, ${ Status}$ and ${ Status}'$ are $\varepsilon_1$-indistinguishable if the resulting samples ${\cal T}_1$ and ${\cal T}_1'$ in the two executions are neighboring. Since ${\cal T}_1$ is just an $m$-size sample from $\tilde{{\cal T}}_1$, and since $\varepsilon_1 = \log(\frac{\varepsilon n}{2 m} - 3)$, we obtain by subsampling argument (\cref{lem:subsampling}) that ${ Status}$ and ${ Status}'$ are $\varepsilon/2$-indistinguishable also in this case. Finally, going back to our case where $\tilde{{\cal T}}_1 = \tilde{{\cal T}}_2 = {\cal T}$, we deduce by the above analysis along with group privacy (of $2$) that ${ Status}$ and ${ Status}'$ are $\varepsilon$-indistinguishable. \end{proof} The following claim is an immediate corollary of \cref{claim:main-T2}. It states that when the tests succeed, then w.h.p., ${\cal T}$ is $\ell$-nearly partitioned by ${\cal B}$, for the value of $\ell$ defined below. \begin{definition}\label{def:ell} Let $\ell = \ell(n,\varepsilon,\delta,\beta) = \frac{2 m}{\varepsilon} \cdot \log\paren{\frac{m}{\beta \delta}}$, where $m = m(n,\varepsilon,\delta,\beta)$ is the value from \cref{def:m}. \end{definition} We note that $\ell = O\paren{\frac{\log^2(1/\delta)}{\varepsilon \log n}}$. When $\beta,\delta \geq 1/{\rm poly}(n)$, we have that $\ell = O\paren{\frac1{\varepsilon} \log n}$. \begin{claim}[On success, ${\cal B}$ almost partitions ${\cal T}$]\label{claim:main} Let ${\cal T} \in (({\mathbb R}^d)^k)^n$ and $\delta > 0$. Consider a random execution of $\mathsf{PrivateTestPartition}({\cal T},\varepsilon,\delta,\beta,\Delta)$, and let $({ Status},{\cal B})$ be the outcome of the execution. Let $S$ be the event that ${ Status} = \text{"Success"}$, and let $E \subseteq S$ be the event that ${\cal T}$ is $\ell$-nearly partitioned by ${\cal B}$, where $\ell = \ell(n,\varepsilon,\delta,\beta)$ is the value from \cref{def:ell}. Then the following holds: If $\pr{S} \geq \delta$, then $\pr{E \mid S} \geq 1 - \delta$. \end{claim} \begin{proof} Immediately holds by \cref{claim:main-T2} since $\ell = \frac{m}{\varepsilon_2}\cdot \log\paren{\frac{m}{\beta \delta}}$, and since it holds that $m > \frac1{\varepsilon_1}\cdot \paren{2 \log(1/\delta) + \log(1/\beta)}$ (by definition), as required by \cref{claim:main-T2}. \end{proof} Recall that Algorithm $\mathsf{PrivateTestPartition}$ has two outputs: A bit $Status$ and a set of balls ${\cal B}$. As we stated in Claim~\ref{eq:status-is-private}, the bit $Status$ preserves privacy. The set of balls ${\cal B}$, however, does {\em not}. Still, in the following sections we use Algorithm $\mathsf{PrivateTestPartition}$ as a subroutine in our two main algorithms $\mathsf{PrivatekAverages}$ and $\mathsf{PrivatekNoisyCenters}$. To argue about the privacy properties of these algorithms, we rely on the following key property of algorithm $\mathsf{PrivateTestPartition}$. \begin{claim}\label{claim:privacy-framework} Let $\mathsf{A}^*$ be an algorithm that gets as input a multiset ${\cal T} \in (({\mathbb R}^d)^k)^n$ and a set of balls ${\cal B} = \set{B_1,\ldots,B_k}$, and let $\ell = \ell(n,\varepsilon/2,\delta/4,\beta/2)$ be the value from \cref{def:ell}. Assume that $\mathsf{A}^*$ has the property that for any neighboring multisets ${\cal T},{\cal T}'$ and any sets of $\Delta$-far balls ${\cal B},{\cal B}'$ that $\ell$-nearly partitions ${\cal T}$ and ${\cal T}'$ (respectively), it holds that $\mathsf{A}^*({\cal T},{\cal B})$ and $\mathsf{A}^*({\cal T}',{\cal B}')$ are $(\varepsilon^*,\delta/4)$-indistinguishable. Let $\mathsf{A}$ be the algorithm that on input ${\cal T}$, does the following steps: (1) Compute $({ Status},{\cal B}) = \mathsf{PrivateTestPartition}\paren{{\cal T},\varepsilon/2,\delta/4,\beta/2,\Delta}$, and (2) If ${ Status} = \text{``Failure''}$, output $\perp$ and abort, and otherwise output $\mathsf{A}^*({\cal T},{\cal B})$. Then $\mathsf{A}$ is $(\varepsilon/2 + \varepsilon^*,\delta)$-differentially private. \end{claim} \begin{proof} Let ${\cal T}$ and ${\cal T}'$ be two neighboring multisets of size $n$. In the following we consider two independent executions: $\mathsf{A}({\cal T})$ and $\mathsf{A}({\cal T}')$. In $\mathsf{A}({\cal T})$, let $O$ be the outcome, let $S,E$ be the events from \cref{claim:main} w.r.t. the execution of $\mathsf{PrivateTestPartition}$ in step (1), and let $({ Status},{\cal B})$ be the resulting output of $\mathsf{PrivateTestPartition}$. Similarly, let $O',S',E',{ Status}',{\cal B}'$ be the events and random variables w.r.t. the execution $\mathsf{A}({\cal T}')$. Let $q = \pr{S}$ and $q' = \pr{S'}$. By \cref{eq:status-is-private} and by group privacy (\cref{fact:group-priv}), ${ Status}$ and ${ Status}'$ are $\frac{\varepsilon}{2}$-indistinguishable. Therefore, $q \in e^{\pm \varepsilon/2} \cdot q'$. Recall that $\mathsf{A}$ outputs $\perp$ and aborts whenever ${ Status} = \text{"Failure"}$, and therefore, $\pr{O = \perp} = 1-q$ and $\pr{O' = \perp} = 1-q'$. If $q < \frac{\delta}2$ then $q' < e^{\varepsilon/2} \cdot \frac{\delta}2 \leq \delta$ (recall that $\varepsilon\leq 1$), and therefore, $\pr{O = \perp}, \pr{O' = \perp} \geq 1 - \delta$. This means that $O$ and $O'$ are $(0,\delta)$-indistinguishable in the case that $q < \frac{\delta}2$ (by \cref{lem:indis}). Similarly, it holds that $O$ and $O'$ are $(0,\delta)$-indistinguishable when $q' < \frac{\delta}2$. Hence, in the rest of the analysis we assume that $q,q' \geq \frac{\delta}2$. By \cref{prop:similar-E}, since $O|_{\neg S} \equiv O'|_{\neg S'}$ (both outcomes equal to $\perp$ when ${ Status} = { Status}' = "\text{Failure}"$) and since $\pr{S} \in e^{\pm \varepsilon/2} \cdot \pr{S'}$, it is enough to prove that $O|_S$ and $O'|_{S'}$ are $(\varepsilon^*,\frac{\delta}2)$-indistinguishable. Furthermore, since $\pr{E \mid S},\pr{E' \mid S'} \geq 1 - \frac{\delta}{4}$ (by \cref{claim:main}), we deduce by \cref{fact:indis-cor} that it is enough to prove that $O|_{E}$ and $O'|_{E'}$ are $(\varepsilon^*,\frac{\delta}4)$-indistinguishable, meaning that we only need to prove indistinguishability in the case that ${\cal T}$ and ${\cal T}'$ are $\ell$-nearly partitioned by ${\cal B}$ and ${\cal B}'$, respectively. The proof of the claim now follows since $\mathsf{A}^*({\cal T},{\cal B})|_{E}$ and $\mathsf{A}^*({\cal T}',{\cal B}')|_{E'}$ are $(\varepsilon^*,\delta/4)$-indistinguishable by the assumption on the algorithm $\mathsf{A}^*$. \end{proof} \begin{remark}\label{remark:Test-runtime} Note that $\mathsf{PrivateTestPartition}$ runs in time $O(m d k^2 n) = \tilde{O}(d k^2 n)$ since for each iteration $X \in {\cal T}_1$ in $\mathsf{PrivateTestCloseTuples}$, Step~\ref{step:B_x} takes $O(dk^2)$ time, and Step~\ref{step:l_x} takes $O(d k^2 n)$ times. \end{remark} \subsection{Algorithm $\mathsf{PrivatekAverages}$}\label{sec:alg-find-averages} In this section we describe and state the properties of $\mathsf{PrivatekAverages}$ (\cref{alg:FindAverages}) which is our first algorithm for $k$-tuple clustering. \begin{algorithm}[$\mathsf{PrivatekAverages}$]\label{alg:FindAverages} \item Input: A multiset ${\cal T} \in \paren{B(0,\Lambda)^k}^n \subseteq (({\mathbb R}^d)^k)^n$, privacy parameters $\varepsilon,\delta \in (0,1]$, a confidence parameter $\beta \in (0,1]$, and a lower bound on the radii $r_{\min} \in [0,\Lambda]$. \item Operation:~ \begin{enumerate} \item Compute $({ Status},{\cal B} = \set{B_1,\ldots,B_k}) = \mathsf{PrivateTestPartition}({\cal T},\varepsilon/2,\delta/4,\beta/2, \Delta)$ for $\Delta = 7$.\label{step:call-testSeparation} \item If ${ Status} = \text{"Failure"}$, output $\perp$ and abort. \item Let $\pc_1,\ldots,\pc_k$ be the centers of $B_1,\ldots,B_k$ (respectively), and let ${\cal Q}_i = \set{\px \in {\rm Points}({\cal T}) \colon i = \operatorname*{argmin}_{j \in [k]} \norm{\px - \pc_j}}$.\label{step:compute-clusters} \item Let $\ell = \ell(n,\varepsilon/2,\delta/4,\beta/2)$ be the value from \cref{def:ell}. \item For $i=1$ to $k$: \begin{enumerate} \item Compute a noisy average $\hat{\pa}_i$ of ${\cal Q}_i$ by executing the algorithm from \cref{prop:approx-aver-Rd} with parameters $\Lambda, r_{\min}, \hat{\beta} = \frac{\beta}{2k}, \hat{\varepsilon} = \frac{\varepsilon}{4k(\ell+1)}, \hat{\delta} = \frac{\delta}{8 k \exp(\varepsilon/2)(\ell + 1)}$.\label{step:computing-noisy-bound-aver} \end{enumerate} \item Output $\hat{A} = \set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$.\label{step:kAverages:output} \end{enumerate} \end{algorithm} \subsubsection{Properties of $\mathsf{PrivatekAverages}$} The properties of $\mathsf{PrivatekAverages}$ are given in the following theorems. \begin{theorem}[Privacy of $\mathsf{PrivatekAverages}$]\label{claim:privacy} Let $d, k, \Lambda > 0$, $r_{\min} \in [0,\Lambda]$, $\varepsilon,\delta, \beta \in (0,1]$. Then for any integer $n \geq 2\cdot \ell(n,\varepsilon/2,\delta/4,\beta/2) + 2$ (where $\ell$ is the function from \cref{def:ell}), algorithm $\mathsf{PrivatekAverages}(\cdot,\varepsilon,\delta,\beta,r_{\min})$ is $(\varepsilon,\delta)$-differentially private for databases ${\cal T} \in (B(\pt{0},\Lambda)^k)^n \subseteq (({\mathbb R}^d)^k)^n$. \end{theorem} \begin{proof} Let ${\cal T}$ and ${\cal T}'$ be two neighboring multisets of size $n$. In the following we consider two independent executions: $\mathsf{PrivatekAverages}({\cal T})$ and $\mathsf{PrivatekAverages}({\cal T}')$ (both with the same parameters $r_{\min},\varepsilon, \delta, \beta$). In $\mathsf{PrivatekAverages}({\cal T})$, let $O$ be the output, and let ${\cal B} = \set{B_1,\ldots,B_k},{\cal Q}_1,\ldots,{\cal Q}_k$ be the values from the execution $\mathsf{PrivatekAverages}({\cal T})$. Similarly, we let $O', {\cal B}' = \set{B_1',\ldots,B_k'},{\cal Q}_1',\ldots,{\cal Q}_k'$ be the these values w.r.t. the execution $\mathsf{PrivatekAverages}({\cal T}')$. By \cref{claim:privacy-framework}, if we treat Step~\ref{step:compute-clusters} to \ref{step:kAverages:output} as algorithm $\mathsf{A}^*$ of the claim, it is enough to prove that $O = \hat{A}$ and $O'= \hat{A}'$ are $(\varepsilon/2,\delta/4)$-indistinguishable only in the case that ${\cal T}$ and ${\cal T}'$ are $\ell$-nearly partitioned by ${\cal B}$ and ${\cal B}'$, respectively. In addition, note that since ${\cal T}$ and ${\cal T}'$ are neighboring, and since $n \geq 2\ell + 2$, there exists at least one $k$-tuple that is partitioned by both ${\cal B}$ and ${\cal B}'$, yielding that for each ball $B_i \in {\cal B}$, there exists a balls in ${\cal B}'$ (call it $B_i'$), such that $B_i \cap B_i' \neq \emptyset$. Since ${\cal B}$ and ${\cal B}'$ are sets of $\Delta$-far balls for $\Delta = 7$, \cref{prop:close-sets-of-far-balls} yields that for every $\px \in B_i$ (or $B_i'$), it holds that $i = \operatorname*{argmin}_{j \in [k]}\norm{\px - \pc_j} = \operatorname*{argmin}_{j \in [k]}\norm{\px - \pc_j'}$. Therefore, in the two executions, $\set{{\cal Q}_1,\ldots,{\cal Q}_k}$ and $\set{{\cal Q}_1',\ldots,{\cal Q}_k'}$ agree on all the points of all the common $(n-1)$ $k$-tuples of ${\cal T}$ and ${\cal T}'$ that are partitioned by ${\cal B}$ or ${\cal B}'$. Since there are at least $k \cdot (n-1-\ell)$ such points, we deduce that there are at most $k (\ell + 1)$ points that the partitions $\set{{\cal Q}_1,\ldots,{\cal Q}_k}$ and $\set{{\cal Q}_1',\ldots,{\cal Q}_k'}$ disagree on. In the following, let $s_i$ be the number of points that the multisets ${\cal Q}_i$ and ${\cal Q}_i'$ differ by. Note that each point that the partitions disagree on contributes at most $1$ to at most two of the $s_i$'s. Hence, $\sum_{i=1}^k s_i \leq 2k(\ell + 1)$. By the privacy guarantee of \cref{prop:approx-aver-Rd} (see \cref{remark:bound-aver-add-del}) along with group privacy (\cref{fact:group-priv}), for each $i \in [k]$, the resulting noisy averages $\hpa_i$ of the execution $\mathsf{PrivatekAverages}({\cal P})$, and the resulting $\hpa_i'$ of the execution $\mathsf{PrivatekAverages}({\cal P}')$, which computed in Step~\ref{step:computing-noisy-bound-aver}, are $(\frac{\varepsilon s_i}{4k(\ell + 1)},\frac{\delta s_i}{8k(\ell + 1)})$-indistinguishable. Thus, by basic composition (\cref{thm:composition1}) we deduce that $\set{\hpa_1,\ldots,\hpa_k}$ and $\set{\hpa_1'\ldots,\hpa_k'}$ are $( \frac{\varepsilon \sum_{i=1}^k s_i}{4k(\ell + 1)},\frac{\delta \sum_{i=1}^ks_i}{8 k(\ell + 1)}) = (\frac{\varepsilon}{2}, \frac{\delta}{4})$-indistinguishable, as required. \end{proof} \begin{theorem}[Utility of $\mathsf{PrivatekAverages}$]\label{claim:utility-kAverg} There exists a universal constant $\lambda > 0$ such that the following holds: Let $n,d, k \in {\mathbb N}$, $\Lambda > 0$, $r_{\min} \in [0,\Lambda]$, $\varepsilon,\delta,\beta \in (0,1]$, let $\ell = \ell(n,\frac{\varepsilon}2,\frac{\delta}4,\frac{\beta}2)$ be the value from \cref{def:ell}. If $n \geq \frac{\lambda k \ell \sqrt{d \log(d k \ell/\delta)} \log\paren{\frac{\Lambda d k}{r_{\min} \beta}}}{\varepsilon}$, then algorithm $\mathsf{PrivatekAverages}(\cdot, \varepsilon, \delta, \beta, r_{\min})$ is an $(\alpha,r_{\min},\beta,\Delta=16,\Lambda)$-averages-estimator for $k$-tuple clustering (\cref{def:averages-estimator}), for \begin{align*} \alpha = \alpha(n,d,k,\varepsilon,\delta,\beta,\Lambda,r_{\min}) := \frac{ \lambda d k \ell \sqrt{\log\paren{\frac{ k \ell}{\delta}}}}{\varepsilon n} \paren{\sqrt{\log\paren{\frac{d k \ell}{\delta}}\log\paren{\frac{d k \ell}{\beta}}} + \log \paren{\frac{\Lambda d k}{r_{\min} \beta}}}. \end{align*} \remove{ and let ${\cal T} \in \paren{B(0,\Lambda)^k}^n \subseteq (({\mathbb R}^d)^k)^n$. Assume that $n \geq \frac{\lambda k \ell \sqrt{d \log(d k \ell/\delta)} \log\paren{\frac{\Lambda d k}{r_{\min} \beta}}}{\varepsilon}$ and that ${\cal T}$ is partitioned by $\Delta$-far balls for $\Delta = 16$. Then w.p. $\geq 1-\beta$ over a random execution of $\mathsf{PrivatekAverages}({\cal T}, \varepsilon, \delta, \beta, r_{\min})$, the output $\hat{A} = \set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$ of the execution is an \emph{$(\alpha,r_{\min})$-good-average} solution for clustering ${\cal T}$ (according to \cref{def:gamma-good}), where \begin{align*} \alpha = \alpha(n,d,k,\varepsilon,\delta,\beta,\Lambda,r_{\min}) := \frac{ \lambda d k \ell \sqrt{\log\paren{\frac{ k \ell}{\delta}}}}{\varepsilon n} \paren{\sqrt{\log\paren{\frac{d k \ell}{\delta}}\log\paren{\frac{d k \ell}{\beta}}} + \log \paren{\frac{\Lambda d k}{r_{\min} \beta}}}. \end{align*} } \end{theorem} We remind that $\ell = O\paren{\frac{\log^2(1/\delta)}{\varepsilon \log n}}$. Therefore, by ignoring ${\rm polylog}(n,d,k,\ell)$ factors, we obtain that for $n = \tilde{\Omega}\paren{\frac{d k \cdot \log^{2.5}(1/\delta)\paren{\sqrt{\log(1/\delta)} + \log\paren{\Lambda/r_{\min}}}}{\varepsilon^2}}$, it holds that $\alpha = O(1)$. \begin{proof} Let ${\cal T} \in ({\cal B}(\pt{0},\Lambda)^k)^n \subset (({\mathbb R}^d)^k)^n$ that is partitioned by $(\Delta=16)$-far balls. Consider a random execution of $\mathsf{PrivatekAverages}({\cal T},\varepsilon,\delta,\beta,r_{\min})$, and let $\tilde{\beta} = \frac{\beta}{2}$ be the value from Step \ref{step:call-testSeparation}. Since ${\cal T}$ is partitioned by $(2\cdot 7 + 2)$-far balls, \cref{claim:correctness} yields that with probability $1 - \beta/2$, the set ${\cal B} = \set{B_1,\ldots,B_k}$ (computed in Step~\ref{step:call-testSeparation}) partitions ${\cal T}$. In the following we assume that this event occurs. Let $\set{{\cal Q}_1,\ldots,{\cal Q}_k}$ be the clusters that were computed in Step~\ref{step:compute-clusters} of $\mathsf{PrivatekAverages}$. By \cref{prop:from-almost-par-to-evenly-par}, it holds that $\set{{\cal Q}_1,\ldots,{\cal Q}_k} = {\rm Partition}({\cal T})$. The proof now follows by the utility guarantee of \cref{prop:approx-aver-Rd} for each $i \in [k]$ with the parameters defined in Step~\ref{step:computing-noisy-bound-aver} of the algorithm. \end{proof} \begin{remark}[Run time of $\mathsf{PrivatekAverages}$]\label{remark:kAver-runtime} Step~\ref{step:call-testSeparation} of $\mathsf{PrivatekAverages}$ takes $\tilde{O}(dk^2 n)$ time (see \cref{remark:Test-runtime}). By \cref{prop:approx-aver-Rd}, the $k$ executions of Step~\ref{step:computing-noisy-bound-aver} takes time $\sum_{i=1}^k \tilde{O}(\size{{\cal T}_i}) = \tilde{O}(dkn)$ (ignoring logarithmic factors). Overall, the running time of $\mathsf{PrivatekAverages}$ is $\tilde{O}(dk^2n)$. \end{remark} \subsubsection{Reducing the dependency in the dimension $d$}\label{sec:reducing-by-JL} When the dimension $d$ is large, algorithm $\mathsf{PrivatekAverages}$ is an averages-estimator for $\alpha = \tilde{O}\paren{d/n}$ (ignoring ${\rm poly}(k,1/\varepsilon)$ and ${\rm polylog}(n,\delta,\beta,\Lambda,1/r_{\min})$ factors). This means that if we aim for $\alpha = O(1)$, we must take $n = \tilde{\Omega}(d)$, and in some settings, such a dependency in the dimension might be expensive. Yet, we can easily reduce the $d$ into $\sqrt{d}$ by replacing in Step~\ref{step:computing-noisy-bound-aver} the average algorithm of \cref{prop:approx-aver-Rd} by the average algorithm of \cite{NSV16} that uses the JL transform for saving a factor of $\sqrt{d}$ (see the last paragraph in \cref{sec:prelim:est-aver} for more details). \subsection{Algorithm $\mathsf{PrivatekNoisyCenters}$}\label{sec:alg-prac-find-averages} In this section we describe Algorithm $\mathsf{PrivatekNoisyCenters}$ (\cref{alg:noisy-tuple}) which is our second algorithm for $k$-tuple clustering. \begin{algorithm}[$\mathsf{PrivatekNoisyCenters}$]\label{alg:noisy-tuple} \item Input: A multiset ${\cal T} \in (({\mathbb R}^d)^k)^n$, privacy parameters $\varepsilon \in (0,1]$, $\delta \in (0,1/2]$, confidence parameter $\beta \in (0,1]$, and a separation parameter $\Delta \gg 6$. \item Operation:~ \begin{enumerate} \item Compute $({ Status},{\cal B} = \set{B_1,\ldots,B_k}) = \mathsf{PrivateTestPartition}({\cal T},\varepsilon/2,\delta/4,\beta/2, \Delta)$.\label{step:call-testSeparation-prac \item If ${ Status} = \text{"Failure"}$, output $\perp$ and abort. \item Let $\pc_1,\ldots,\pc_k$ be the centers of $B_1,\ldots,B_k$ (respectively).\label{step:centers} \item For $i=1$ to $k$:\label{step:for-loop-prac} \begin{enumerate} \item Let $\lambda_i = \frac{2}{\Delta} (1+\gamma_i) \min_{j \neq i} \norm{\pc_i - \pc_j}$ where $\gamma_i = \frac4{\Delta-2} \cdot \paren{{\rm Lap}(4k/\varepsilon) + \frac{4k}{\varepsilon} \log(4k/\delta) + 1}$. \item Let $\hat{\pc}_i = \pc_i + ({\cal N}(\pt{0}, \sigma_i^2))^d$, where $\sigma_i = \frac{4 k \lambda_i}{\varepsilon} \sqrt{2 \log(10k/\delta)}$. \end{enumerate} \item Output $\hat{C} = \set{\hat{\pc}_1,\ldots,\hat{\pc}_k}$.\label{step:kAverages:output-prac} \end{enumerate} \end{algorithm} \subsubsection{Properties of $\mathsf{PrivatekNoisyCenters}$} The properties of $\mathsf{PrivatekNoisyCenters}$ are given in the following theorems. \begin{theorem}[Utility of $\mathsf{PrivatekNoisyCenters}$]\label{thm:util-NoisykCen} Let $d,k > 0$, $\varepsilon,\beta,\delta \in (0,1]$ with $\delta < \beta$, let ${\cal T} \in (({\mathbb R}^d)^k)^n$, and assume that ${\cal T}$ is partitioned by $(2\Delta+2)$-far balls, for $\Delta = \Omega\paren{\frac{k \log\paren{k/\delta} \sqrt{\log(k/\beta)}}{\varepsilon}}$. Then when executing $\mathsf{PrivatekNoisyCenters}({\cal T},\varepsilon,\delta,\beta,\Delta)$, with probability $1-\beta$, the output $\hat{C} = \set{\hat{\pc}_1,\ldots,\hat{\pc}_k}$ satisfy for every $i$ and $j \neq i$ that $\norm{\hat{\pc}_i - \pc_i} < \norm{\hat{\pc}_i - \pc_j}$, where $\pc_1,\ldots,\pc_n$ are the centers from Step~\ref{step:centers}. \end{theorem} We remark that the $k$ factor in the $\Delta$ in \cref{thm:util-NoisykCen}, comes from applying basic composition (\cref{thm:composition1}) over the $k$ noisy centers $\hat{C}$. This however can be reduced to $\tilde{O}(\sqrt{k})$ factor by applying advanced composition (\cref{thm:composition2}). \begin{proof} By the union bound on all the choices of $\gamma_i$, w.p. $1-\delta/8 \geq 1 - \beta/8$, for each $i \in [k]$ it holds that $\min_{j \neq i} \norm{\pc_i - \pc_j} \geq \Omega\paren{\sqrt{\log(k/\beta)}} \cdot \sigma_i$. Therefore, for every $i\neq j$ we can apply \cref{prop:separation-spherical-case} with $\mu = \pc_i$ and $\py = \pc_j$ to obtain that with proper choices of the constants in $\Delta$, with probability $1-\frac{\beta}{2k^2}$ it holds that $\norm{\hat{\pc}_i - \pc_i} < \norm{\hat{\pc}_i - \pc_j}$. By the union bound over all $i \neq j$ we deduce that with probability $1 - \beta/2$ this holds for every $i \neq j$, as required. \end{proof} \begin{theorem}[Privacy of $\mathsf{PrivatekNoisyCenters}$]\label{thm:priv-NoisykCen} Let $d,k > 0$, $\varepsilon,\beta \in (0,1]$, $\delta \in (0,1/2]$, $\Delta > 6$. Then for any integer $n \geq 2\cdot \ell(n,\varepsilon/2,\delta/4,\beta/2) + 2$ (where $\ell$ is the function from \cref{def:ell}), $\mathsf{PrivatekNoisyCenters}(\cdot,\varepsilon,\delta,\beta,\Delta)$ is $(\varepsilon + \delta/4, \delta)$-differentially private for databases ${\cal T} \in (({\mathbb R}^d)^k)^n$. \end{theorem} \begin{proof} Let ${\cal T}$ and ${\cal T}'$ be two neighboring multisets of size $n$. In the following we consider two independent executions: $\mathsf{PrivatekNoisyCenters}({\cal T})$ and $\mathsf{PrivatekNoisyCenters}({\cal T}')$ (both with the same parameters $r_{\min},\varepsilon, \delta, \beta$). In $\mathsf{PrivatekNoisyCenters}({\cal T})$, let $O$ be the output, and let ${\cal B} = \set{B_i = B(\pc_i,r_i)}_{i=1}^k$ be the $\Delta$-far balls in the execution $\mathsf{PrivatekNoisyCenters}({\cal T})$. Similarly, we let $O', {\cal B}' = \set{B_i' = B(\pc_i',r_i')}_{i=1}^k$ be the these values w.r.t. the execution $\mathsf{PrivatekNoisyCenters}({\cal T}')$. By \cref{claim:privacy-framework}, it is enough to prove that the resulting outputs $O = \tilde{C}$ and $O' = \tilde{C}'$ of Steps \ref{step:centers} to \ref{step:kAverages:output-prac} are $(\varepsilon/2 + \delta/4,\delta/4)$-indistinguishable only in the case that ${\cal T}$ and ${\cal T}'$ are $\ell$-nearly partitioned by ${\cal B}$ and ${\cal B}'$, respectively. Since $2 \ell \leq n-2$ and since ${\cal T}$ and ${\cal T}'$ are neighboring, there must exists a $k$-tuple $X = \set{\px_1,\ldots,\px_k} \in {\cal T}$ that is partitioned by both ${\cal B}$ and ${\cal B}'$. In the rest of the analysis we assume (w.l.o.g.) that $\px_i \in B_i \cap B_i'$ for every $i \in [k]$. In the following, we prove that for every $i \in [k]$ it holds that $\min_{j \neq i} \norm{\pc_i - \pc_j}$ is close to $\min_{j \neq i} \norm{\pc_i' - \pc_j'}$. For every $i\neq j$ it holds that \begin{align*} \norm{\pc_i - \pc_j} &\leq \norm{\pc_i - \pc_i'} + \norm{\pc_j - \pc_j'} + \norm{\pc_i' - \pc_j'}\\ &\leq \norm{\pc_i - \px_i} + \norm{\pc_i' - \px_i} + \norm{\pc_j - \px_j} + \norm{\pc_j' - \px_j} + \norm{\pc_i' - \pc_j'}\\ &\leq r_i + r_i' + r_j + r_j' + \norm{\pc_i' - \pc_j'}\\ &\leq \frac2{\Delta} \norm{\pc_i - \pc_j} + \frac2{\Delta} \norm{\pc_i' - \pc_j'} + \norm{\pc_i' - \pc_j'}. \end{align*} Therefore, \begin{align*} \norm{\pc_i - \pc_j} \leq \frac{\Delta+2}{\Delta-2} \norm{\pc_i' - \pc_j'} = \paren{1 + \frac4{\Delta-2}} \norm{\pc_i' - \pc_j'}. \end{align*} Now let $i \in [k]$, and let $s = \operatorname*{argmin}_{j \neq i} \norm{\pc_i - \pc_j}$ and $t = \operatorname*{argmin}_{j \neq i} \norm{\pc_i' - \pc_j'}$. We deduce that \begin{align}\label{eq:compare-minimums} \min_{j \neq i} \norm{\pc_i - \pc_j} = \norm{\pc_i - \pc_s} \leq \norm{\pc_i - \pc_t} \leq \paren{1 + \frac4{\Delta-2}} \norm{\pc_i' - \pc_t'} = \paren{1 + \frac4{\Delta-2}} \cdot \min_{j \neq i} \norm{\pc_i' - \pc_j'} \end{align} Similarly, it holds that $\min_{j \neq i} \norm{\pc_i' - \pc_j'} \leq \paren{1 + \frac4{\Delta-2}} \cdot \min_{j \neq i} \norm{\pc_i - \pc_j}$. Therefore, by the properties of the laplace mechanism, we deduce that for each $i$, the values of $\lambda_i$ and $\lambda_i'$ are $\frac{\varepsilon}{4k}$-indistinguishable, and by basic composition we deduce that $\set{\lambda_i}_{i=1}^k$ and $\set{\lambda_i'}_{i=1}^k$ are all together $\varepsilon/4$-indistinguishable. In the following, let $L$ be the event that $\forall i \in [k]:\text{ }\gamma_i \geq \frac{4}{\Delta-2}$, and $L'$ be the event that $\forall i \in [k]:\text{ }\gamma_i' \geq \frac{4}{\Delta-2}$. By \cref{fact:laplace-concent} and the union bound, it holds that $\pr{L},\pr{L'} \leq \delta/8$. Therefore, by \cref{fact:indis-cor}, it is enough to prove that $\tilde{C}|_{L}$ and $\tilde{C}'|_{L'}$ are $(\varepsilon/2 + \delta/4,\delta/8)$-indistinguishable. First, by \cref{fact:conditioning}, we deduce that $\set{\lambda_i}_{i=1}^k|_{L}$ and $\set{\lambda_i'}_{i=1}^k|_{L'}$ are $(\varepsilon/4 + \delta/4)$-indistinguishable\Enote{Missing here a delta error of $e^{\varepsilon} \delta/(8-\delta) \leq \delta/4$.}. We now continue with the analysis assuming that $\lambda_i = \lambda_i'$ for all $i \in [k]$. Note that for every $i$ it holds that \begin{align*} \norm{\pc_i - \pc_i'} &\leq \norm{\pc_i - \px_i} + \norm{\pc_i' - \px_i}\\ &\leq r_i + r_i'\\ &\leq \frac1{\Delta} \cdot \paren{\min_{j \neq i} \norm{\pc_i - \pc_j} + \min_{j \neq i} \norm{\pc_i' - \pc_j'}}\\ &\leq \lambda_i, \end{align*} where the last inequality holds by \cref{eq:compare-minimums} (assuming that $L$ occurs). Therefore, by the properties of the Gaussian Mechanism (\cref{fact:Gaus}), we deduce that for each $i$, $\hpc_i$ and $\hpc_i'$ are $(\frac{\varepsilon}{4k},\frac{\delta}{8k})$-indistinguishable, and by basic composition (\cref{thm:composition1}) we deduce that $\hat{C}$ and $\hat{C}'$ are $(\frac{\varepsilon}{4},\frac{\delta}{8})$-indistinguishable (assuming that $\lambda_i = \lambda_i'$ for all $i \in [k]$). Finally, recall that $\set{\lambda_i}_{i=1}^k|_{L}$ and $\set{\lambda_i'}_{i=1}^k|_{L'}$ are $(\varepsilon/4 + \delta/4)$-indistinguishable, and therefore, we conclude by adaptive composition (\cref{thm:composition1}) that $\hat{C}$ and $\hat{C}'$ are $(\varepsilon/2 + \delta/4,\delta/8)$-indistinguishable. \end{proof} \begin{remark}[Run time of $\mathsf{PrivatekNoisyCenters}$]\label{remark:kNoisyCenters-runtime} Step~\ref{step:call-testSeparation-prac} of $\mathsf{PrivatekNoisyCenters}$ takes $\tilde{O}(dk^2 n)$ time (see \cref{remark:Test-runtime}). The foor-loop in Step~\ref{step:for-loop-prac} only takes $O(d k n)$ time. Overall, the running time of $\mathsf{PrivatekNoisyCenters}$ is $\tilde{O}(dk^2n)$. \end{remark} \section{$k$-Means Clustering}\label{sec:kMeans} In this section we present our first application of $k$-tuples clustering, which is an $(\varepsilon,\delta)$-differentially private $k$-means approximation algorithm $\mathsf{PrivatekMeans}$ with utility guarantee that holds when the input is stable in the sense that we will define. We first start with preliminaries about $k$-means clustering. \subsection{Preliminaries}\label{sec:kMeans:Preliminaries} For a multiset ${\cal P} \in ({\mathbb R}^d)^*$ and a $k$-tuple of centers $C = \set{\pc_1,\ldots,\pc_k} \in ({\mathbb R}^d)^k$, we denote ${\rm COST}_{{\cal P}}(C) := \sum_{\px \in {\cal P}} \min_{i \in [k]}\norm{\px - \pc_i}^2$ and denote ${\rm OPT}_k({\cal P}) := \min_{C \in ({\mathbb R}^d)^k} {\rm COST}_{{\cal P}}(C)$. The following proposition states that given a multiset ${\cal P} \in ({\mathbb R}^d)^n$ and an $\omega$-approximation algorithm $\mathsf{A}$ for $k$-means, then when sampling $s$ i.i.d.\ points from ${\cal P}$ and executing $\mathsf{A}$ on these points, then with probability $1-\beta$ we obtain $k$ centers with cost $\approx \omega {\rm OPT}_{k}({\cal P})$ (up to a small additive error that depends on $s$ and $\beta$). The proof appears at \cref{missing-proof:cost-of-sample-is-good}. \def\propCostOfSampleIsGood{ Let ${\cal P}$ be a multiset of $n$ points in ${\cal B}(\pt{0},\Lambda) \subseteq {\mathbb R}^d$ and let ${\cal A}$ be an $\omega$-approximation algorithm for $k$-means. Consider the following random execution: (1) Construct a multiset ${\cal S}$ of $s$ i.i.d.\ samples from ${\cal P}$, (2) Compute $\tilde{C} = {\cal A}({\cal S},k)$. Then for every $\beta > 0$, with probability $1-\beta$ it holds that \begin{align*} {\rm COST}_{{\cal P}}(\tilde{C}) \leq \omega\cdot {\rm OPT}_k({\cal P}) + \xi(s,\beta), \end{align*} where $\xi(s,\beta) := 4\paren{M(s,\beta)+ \sqrt{M(s,\beta) \cdot \omega {\rm OPT}_k({\cal P})}}$ for $M(s,\beta) := 25 \Lambda^2 k d \log \paren{\frac{2nd}{\beta}} \cdot \frac{n}{s}$. } \begin{proposition}\label{prop:cost-of-sample-is-good} \propCostOfSampleIsGood \end{proposition} The following proposition states that given a multiset of points ${\cal P}$ and given two $k$-tuples of centers $C = \set{\pc_1,\ldots,\pc_k}$ and $C' = \set{\pc_{1}', \ldots, \pc_{k}'}$ such that each $\pc_i'$ is relatively close to a unique center $\pc_i$ in $C$, then by clustering the points according to $C'$ and performing a single Lloyd step, we get new centers whose $k$-means cost is almost bounded by ${\rm COST}_{{\cal P}}(C)$. The proof appears at \cref{missing-proof:close-centers-have-similar-cost}. \def\propCloseCentersHaveSimilarCost{ Let $k \in {\mathbb{N}} $ and $\gamma \in [0,1/8]$. Let ${\cal P} \in ({\mathbb R}^d)^*$, let $C = \set{\pc_1,\ldots,\pc_k}$ and $C' = \set{\pc_{1}', \ldots, \pc_{k}'}$ be two $k$-tuples of centers in ${\mathbb R}^d$ such that for every $i \in [k]$ it holds that $\norm{\pc_i' - \pc_i} \leq \gamma\cdot D_i$, where $D_i = \min_{j \neq i}\norm{\pc_i - \pc_j}$. In addition, for every $i \in [k]$ let ${\cal P}_i$ be the multiset of all points in ${\cal P}$ that $\pc_i'$ is closest to them in $C'$. Then $$\sum_{i=1}^k {\rm OPT}_1({\cal P}_i) \leq (1 + 32\gamma) {\rm COST}_{{\cal P}}(C).$$ } \begin{proposition}\label{prop:close-centers-have-similar-cost} \propCloseCentersHaveSimilarCost \end{proposition} \subsection{Private $k$-Means Under Stability Assumption}\label{sec:kMeans:Alg} In this section we describe our private algorithm $\mathsf{PrivatekMeans}$ for approximation the $k$-means when the input is stable in the sense that we will define next. The idea is the following: Fix a database ${\cal P} \in ({\mathbb R}^d)^n$, parameters $s,t \in {\mathbb N}$ and a (non-private) $k$-means approximation algorithm $\mathsf{A}$. Now execute $\mathsf{A}$ on $s$ i.i.d.\ samples from ${\cal P}$, and repeat this process $t$ times. Consider the event (over this process) that all the $t$ sets of $k$ centers are almost located at the same positions. More formally, consider a random execution of $\mathsf{GenCenters}^{\mathsf{A}}({\cal P},k,s,t)$ (\cref{alg:generateCenters}). For a $k$-tuple of centers $C = \set{\pc_1,\ldots,\pc_k} \in ({\mathbb R}^d)^k$ and a small stability parameter $\gamma > 0$ (say, $\gamma = 0.01$), let $E_C^{\gamma}$ be the event that is defined below. \begin{definition}[Event $E_{C}^{\gamma}$ over a random sampling of $\mathsf{GenCenters}$]\label{def:event-ECgamma} Let $E_{C}^{\gamma}$ be the event that for every $j \in [t]$ and $i \in [k]$, there exists a center in $\tilde{C}_j$ (call it $\tpc_i^j$) such that $\norm{\tpc_i^j - \pc_i} \leq \gamma\cdot D_i$, where $D_i = \min_{j \neq i}\norm{\pc_i - \pc_j}$. \end{definition} Namely, event $E_{C}^{\gamma}$ implies that the output $\tilde{{\cal C}} \in (({\mathbb R}^d)^k)^t$ of $\mathsf{GenCenters}$ is partitioned by $\Delta$-far balls for $\Delta = 1/\gamma$, where ${\rm Partition}(\tilde{{\cal C}})$ (according to \cref{def:clusters-rel}) is exactly $\set{\set{\tpc_1^j}_{j=1}^t, \ldots, \set{\tpc_k^j}_{j=1}^t}$ (i.e., for each $i \in [k]$, the centers $\set{\tpc_i^j}_{j=1}^t$ are very close to each other, compared to the distance from the other centers). In this section, we describe our general $(\varepsilon,\delta)$-differentially private algorithm $\mathsf{PrivatekMeans}$, that uses oracle accesses to a non-private $k$-means algorithm $\mathsf{A}$ and a private good-average $k$-tuple clustering algorithm $\mathsf{B}$, such that the following utility guarantee it achieved: For any $k$-centers $C$ and a small enough $\gamma$, when the event $E_{C}^{\gamma}$ occurs over $\mathsf{GenCenters}^{\mathsf{A}}({\cal P},k,s,t)$, then with probability $1-\beta$, algorithm $\mathsf{PrivatekMeans}$ outputs $\hat{C} = \set{\hat{\pc}_1,\ldots,\hat{\pc}_k}$ with ${\rm COST}_{{\cal P}}(\hat{C}) \leq (1 + O(\gamma)) {\rm COST}_{{\cal P}}(C)$ (plus some small additive error). $\mathsf{PrivatekMeans}$ is described in \cref{alg:kMeans} and its properties are proven in \cref{sec:kMeans:properties}. In \cref{sec:application} we show that a variant of the separation assumption in \cite{OstrovskyRSS12} implies that event $E_{C^*}^{\gamma}$ holds with high probability, where $C^*$ are the optimal $k$ means for ${\cal P}$. \begin{algorithm}[$\mathsf{GenCenters}$]\label{alg:generateCenters} \item Input: A multiset ${\cal P}$ of points in $B(\pt{0},\Lambda) \subseteq {\mathbb R}^d$ and parameters $k, s,t \in {\mathbb N}$. \item Oracle: A (non-private) $k$-means algorithm $\mathsf{A}$. \item Operation:~ \begin{enumerate} \item For each $j \in [t]$: \begin{enumerate} \item Let ${\cal S}_j$ be a database containing $s$ i.i.d.\ samples from ${\cal P}$ (with replacement).\label{step:sample} \item Compute the $k$-tuple of centers $\tilde{C}_j = \mathsf{A}({\cal S}_j)$.\label{step:non-priv-centers} \end{enumerate} \item Output ${\cal T} = \set{\tilde{C}_1,\ldots,\tilde{C}_t}$.\label{step:new-multisets} \end{enumerate} \end{algorithm} \begin{algorithm}[$\mathsf{PrivatekMeans}$]\label{alg:kMeans} \item Input: A multiset ${\cal P}$ of $n$ points in $B(\pt{0},\Lambda) \subseteq {\mathbb R}^d$, parameters $k, s, t \in {\mathbb N}$, privacy parameters $\varepsilon,\delta \in (0,1]$, confidence parameter $\beta \in (0,1]$, and a stability parameter $\gamma > 0$. \item Oracle: A (non-private) $k$-means algorithm $\mathsf{A}$, a private average algorithm $\mathsf{A}'$, and a private $k$-tuple clustering algorithm $\mathsf{B}$. \item Operation:~ \begin{enumerate} \item Compute ${\cal T} = \mathsf{GenCenters}^{\mathsf{A}}({\cal P},k,s,t)$.\label{step:gen} \item Compute $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k} = \mathsf{B}({\cal T})$.\label{step:the-aver-estim} \item For each $i \in [k]:$ \begin{itemize} \item Let ${\cal P}_i$ be the points in ${\cal P}$ that $\hpa_i$ is the closest point to them among $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$. \label{step:compute-clusters-kmeans} \item Compute $\hpc_i = \mathsf{A}'({\cal P}_i)$.\label{step:add-gaus-noise} \end{itemize} \item Output $\set{\hat{\pc}_1,\ldots,\hat{\pc}_k}$. \end{enumerate} \end{algorithm} \subsection{Properties of $\mathsf{PrivatekMeans}$}\label{sec:kMeans:properties} The following theorem captures the privacy guarantee of $\mathsf{PrivatekMeans}$. \begin{theorem}[Privacy of $\mathsf{PrivatekMeans}$]\label{claim:kMeans-privacy} Let $n,s,t,d,k \in {\mathbb N}$, $\Lambda > 0$, $\beta,\varepsilon,\delta, \gamma \in (0,1]$, let $\mathsf{A}$ be an (arbitrary) algorithm that outputs $k$ centers in $B(\pt{0},\Lambda) \subset {\mathbb R}^d$, let $\mathsf{A}'$ be an $(\frac{\varepsilon}{12},\frac{\delta}{8 e^{\varepsilon}})$-DP algorithm for databases over $B(\pt{0},\Lambda)$, and let $\mathsf{B}$ be an $\left(\frac{\varepsilon}{6},\frac{\delta}{4 e^{\varepsilon}}\right)$-DP algorithm for databases ${\cal T} \in (B(\pt{0},\Lambda)^k)^t$ (i.e., of size $t$). If $n \geq 2st$, then algorithm $\mathsf{PrivatekMeans}^{\mathsf{A}, \mathsf{A}', \mathsf{B}}(\cdot, k,s,t, \varepsilon,\delta,\beta,\gamma)$ is $(\varepsilon,\delta)$-differentially private for databases ${\cal P}$ over $B(\pt{0},\Lambda) \subset {\mathbb R}^d$. \end{theorem} \begin{proof} The proof builds on the fact that switching between sampling with replacement and without replacement has only a small effect on the privacy, as stated in \cref{lem:DP-with-replacement}. Consider a different variant $\widetilde{\mathsf{Gen}}{\mathsf{Centers}}$ of the procedure $\mathsf{GenCenters}$, in which the sampling of the $\approx s \cdot t$ points in all the iterations of Step~\ref{step:sample} is done without replacement, and consider a variant $\widetilde{\mathsf{Priv}}{\mathsf{atekMeans}}$ of $\mathsf{PrivatekMeans}$ in which it executes $\widetilde{\mathsf{Gen}}{\mathsf{Centers}}$ in Step~\ref{step:gen} rather than $\mathsf{GenCenters}$. Let ${\cal P} = \set{\px_1,\ldots,\px_n}$ and ${\cal P}' = \set{\px_1',\ldots,\px_n'}$ be two neighboring databases of points. In the following we consider two independent executions $\widetilde{\mathsf{Priv}}{\mathsf{atekMeans}}({\cal P})$ and $\widetilde{\mathsf{Priv}}{\mathsf{atekMeans}}({\cal P}')$ (both with the same parameters $k,\varepsilon,\delta,\beta$ and oracles $\mathsf{A},\mathsf{B}$). For $j \in [t]$ let ${\cal J}_j \subseteq [n]$ be the $s$ chosen indices of the points ${\cal S}_j$ in Step~\ref{step:sample} of $\widetilde{\mathsf{Gen}}{\mathsf{Centers}}$ (i.e., ${\cal S}_j = \set{\px_i}_{i \in {\cal J}_j}$), and let ${\cal J}_j'$ be the same indices in the execution $\widetilde{\mathsf{Priv}}{\mathsf{atekMeans}}({\cal P}')$. Since ${\cal J}_j$ and ${\cal J}_j'$ only depend on $n$ and not on the content of ${\cal P}$ and ${\cal P}'$, it is enough to prove that the output of both executions is $(\varepsilon,\delta)$-indistinguishable conditioned on the event that ${\cal J}_j = {\cal J}_j'$ for every $j \in [t]$. In the following, we assume that this event occurs. Since ${\cal P}$ and ${\cal P}'$ are neighboring, there exists at most one index $j \in [t]$ such that ${\cal S}_j$ of the execution $\widetilde{\mathsf{Priv}}{\mathsf{atekMeans}}({\cal P})$ is different than the corresponding set in $\widetilde{\mathsf{Priv}}{\mathsf{atekMeans}}({\cal P}')$, and therefore, the outputs $\hat{{\cal C}}$ of $\widetilde{\mathsf{Gen}}{\mathsf{Centers}}$ are different by at most one $k$-tuple. Therefore, by the assumption over algorithm $\mathsf{B}$, we deduce that the outcome of Step~\ref{step:the-aver-estim} is $(\frac{\varepsilon}{6}, \frac{\delta}{4 e^{\varepsilon}})$-differentially private. In the following, we prove that for any fixing of $k$ averages $\tpa_1,\ldots,\tpa_k$, Step~\ref{step:add-gaus-noise} is $(\frac{\varepsilon}{6}, \frac{\delta}{4 e^{\varepsilon}})$-differentially private. Given that, we deduce that $\widetilde{\mathsf{Priv}}{\mathsf{atekMeans}}$ is $(\frac{\varepsilon}{3}, \frac{\delta}{2 e^{\varepsilon}})$-differentially private by (adaptive) composition of Steps~\ref{step:the-aver-estim} and \ref{step:add-gaus-noise} (\cref{thm:composition1}). Hence, we conclude that the original algorithm $\mathsf{PrivatekMeans}$, that chooses the points with replacement, is $(\varepsilon,\delta)$-differentially private by applying \cref{lem:DP-with-replacement} with $m = s t \leq \frac{n}2, \frac{\varepsilon}{3}, \frac{\delta}{2 e^{\varepsilon}}$. It is left to prove the privacy guarantee of Step~\ref{step:add-gaus-noise}. For that, fix $k$ averages $\hat{A}=\set{\tpa_1,\ldots,\tpa_k}$, let ${\cal P}_1,\ldots,{\cal P}_k$ be the $k$ multisets in Step~\ref{step:add-gaus-noise} w.r.t ${\cal P}$ and $\hat{A}$, and let ${\cal P}_1',\ldots,{\cal P}_k'$ be the same multisets w.r.t ${\cal P}'$ and $\hat{A}$. Since ${\cal P}$ and ${\cal P}'$ are neighboring, there exist at most two indices $i \in [k]$ such that ${\cal P}_i \neq {\cal P}_i'$, and for each one of them, ${\cal P}_i$ and ${\cal P}_i'$ are neighboring. Therefore, by the privacy guarantee of $\mathsf{A}'$ along with basic composition (\cref{thm:composition1}), Step~\ref{step:add-gaus-noise} is $(2 \cdot \frac{\varepsilon}{12}, 2\cdot \frac{\delta}{8 e^{\varepsilon}})$-differentially private, as required. \end{proof} The following theorem, which captures the utility guarantee of $\mathsf{PrivatekMeans}$, states that when event $E^{\gamma}_C$ (\cref{def:event-ECgamma}) occurs by $\mathsf{GenCenters}$ in Step~\ref{step:gen}, then with probability at least $1-\beta$, the output $\hat{C} = \set{\hat{\pc}_1,\ldots,\hat{\pc}_k}$ has ${\rm COST}_{{\cal P}}(\hat{C}) \leq (1 + O(\gamma)) {\rm COST}_{{\cal P}}(C) + O\paren{\zeta^2 k}$, where $\zeta/m$ is the additive error of $\mathsf{A}'$ over database of size $m$ with confidence $1- O(\beta/k)$. We remark that by setting $\mathsf{A}'$ as the Gaussian mechanism (\cref{fact:Gaus}) with privacy parameter $\paren{O(\varepsilon),O(\delta)}$, we obtain that $\zeta = O\paren{\frac{\Lambda \sqrt{\log(1/\delta)}}{\varepsilon} \paren{\sqrt{d} + \sqrt{\log(k/\beta)}}}$. \begin{theorem}[Utility of $\mathsf{PrivatekMeans}$]\label{claim:kMeans-utility} Let $n,s,t,d,k,\Lambda > 0$, $\beta,\varepsilon,\delta \in (0,1]$, $\gamma \in (0,\frac1{16}]$, and let ${\cal P}$ be a multiset of $n$ points in $B(\pt{0},\Lambda) \subseteq {\mathbb R}^d$. Let $\mathsf{A}$ be an algorithm that outputs $k$ centers in ${\mathbb R}^d$. Let $\mathsf{A}'$ be an algorithm that given a multiset ${\cal S}$ of points over $B(\pt{0},\Lambda)$, w.p. $1-\frac{\beta}{2k}$ estimates ${\rm Avg}({\cal S})$ up to an additive error $\zeta/\size{{\cal S}}$ for $\zeta = \zeta(d, \Lambda, \frac{\beta}{2k})$. Let $\mathsf{B}$ be an $(t, \: \alpha=1,\text{ }r_{\min}=\gamma/n,\: \beta/2, \: \Delta=1/\gamma, \: \Lambda)$-averages-estimator $k$-tuple clustering algorithm (\cref{def:averages-estimator}). Finally, let $C = \set{\pc_1,\ldots,\pc_k} \in ({\mathbb R}^d)^k$ with $\min_{i \neq j} \norm{\pc_i - \pc_j} \geq 1/n$. Consider a random execution of $\mathsf{PrivatekMeans}^{\mathsf{A},\mathsf{A}',\mathsf{B}}({\cal P},t,k,\varepsilon,\delta,\beta,\gamma)$ conditioned that the event $E_{C}^{\gamma}$ occurs by $\mathsf{GenCenters}$ in Step~\ref{step:gen} of the execution. Then with probability $1-\beta$ (over the above conditional execution), the output $\hat{C} = \set{\hpc_1,\ldots,\hpc_k}$ of $\mathsf{PrivatekMeans}$ satisfies \begin{align*} COST_{{\cal P}}(\set{\hpc_1,\ldots,\hpc_k}) \leq (1 + 64\gamma) {\rm COST}_{{\cal P}}(C) + \zeta k (\zeta + 2\Delta) \end{align*} \end{theorem} \begin{proof} Consider a random execution of $\mathsf{PrivatekMeans}^{\mathsf{A},\mathsf{A}',\mathsf{B}}({\cal P},t,k,\varepsilon,\delta,\beta,\gamma)$ conditioned on the event $E^{\gamma}_C$. For $j \in [t]$, let $\tilde{C}_j = \set{\tpc_1^j,\ldots,\tpc_k^j}$ be the value from Step~\ref{step:non-priv-centers} of the $j$'th iteration of $\mathsf{GenCenters}$, where we denote by $\tpc_i^j$ the center that is close to $\pc_i$, i.e., $\norm{\tpc_i^j - \pc_i} \leq \gamma \cdot D_i$, where $D_i = \min_{j \neq i}\norm{\pc_i- \pc_j}$ (such center exists by event $E_C^{\gamma}$). In addition, for $i \in [k]$, let $\pa_i = {\rm Avg}(\set{\tpc_{i}^j}_{j=1}^t)$ and note that \begin{align}\label{eq:dist-pai-pci} \forall i \in [k]:\text{}\norm{\pa_i - \pc_i} &= \norm{\frac1{t} \sum_{j=1}^t \tpc_{i}^j - \pc_i}\\ &\leq \frac1{t} \sum_{j=1}^t \norm{\tpc_{i}^j - \pc_i}\nonumber\\ &\leq \gamma \cdot D_i.\nonumber \end{align} Now, let ${\cal T}=\set{\tilde{C}_1 = \set{\tpc_i^1}_{i=1}^k, \ldots,\tilde{C}_t = \set{\tpc_i^t}_{i=1}^k}$ be the output of $\mathsf{GenCenters}$ in Step~\ref{step:gen} of $\mathsf{PrivatekMeans}$, and note that ${\cal T}$ is partitioned by the set of $(\Delta = 1/\gamma)$-far balls $\set{B(\pc_i, r_i = \gamma D_i)}_{i=1}^k$ where ${\rm Partition}({\cal T}) = \set{\set{\tpc_{1}^j}_{j=1}^t, \ldots, \set{\tpc_{k}^j}_{j=1}^t}$. Therefore, when executing algorithm $\mathsf{B}$ in Step~\ref{step:the-aver-estim}, we obtain by assumption a set of $k$ points $\set{\hpa_1,\ldots,\hpa_k}$ such that with probability $1 - \frac{\beta}{2}$ it holds that \begin{align}\label{eq:dist-pai-hpai} \forall i \in [k]:\text{ } \text{}\norm{\pa_i - \hpa_i} \leq \max\set{r_i,r_{\min}} \leq \gamma\cdot D_i, \end{align} where in the second inequality we used the fact that $r_i \leq \gamma D_i$ and that $r_{\min} = \gamma/n \leq \gamma D_i$. Therefore, we deduce by \cref{eq:dist-pai-pci,eq:dist-pai-hpai} that with probability $1 - \frac{\beta}2$ it holds that \begin{align}\label{eq:hpa-pc-dist} \forall i \in [k]:\text{}\norm{\hpa_i - \pc_i} \leq 2\gamma \cdot D_i. \end{align} Let ${\cal P}_1,\ldots,{\cal P}_k$ be the clusters from Step~\ref{step:compute-clusters-kmeans} of the algorithm. If \cref{eq:hpa-pc-dist} occurs, then by \cref{prop:close-centers-have-similar-cost} we get that \begin{align}\label{eq:avg-cost} \sum_{i=1}^k \sum_{\px \in {\cal P}_i} \norm{\px - {\rm Avg}({\cal P}_i)}^2 \leq (1 + 64\gamma) {\rm COST}_{{\cal P}}(C). \end{align} Since the algorithm computes a noisy estimation $\hpc_i$ of each ${\rm Avg}({\cal P}_i)$ using the oracle $\mathsf{A}'$, we get that with probability $1-k\hat{\beta} = 1 - \frac{\beta}{2}$ it holds that \begin{align}\label{eq:dist-from-avg} \forall i \in [k]:\quad \norm{\hpc_i - {\rm Avg}({\cal P}_i)} \leq \zeta/\size{{\cal P}_i} \end{align} Finally, since \cref{eq:avg-cost} occurs with probability $1 - \frac{\beta}{2}$, and \cref{eq:dist-from-avg} occurs with probability $1 - \frac{\beta}{2}$, we conculde that with probability $1-\beta$ both of them occurs, which implies that \begin{align*} \lefteqn{{\rm COST}_{{\cal P}}(\set{\hpc_1,\ldots,\hpc_k})}\\ &\leq \sum_{i=1}^k \sum_{\px \in {\cal P}_i} \norm{\px - \hpc_i}^2\\ &= \sum_{i=1}^k \sum_{\px \in {\cal P}_i} \paren{\norm{\px - {\rm Avg}({\cal P}_i)}^2 + \norm{\hpc_i - {\rm Avg}({\cal P}_i)}^2 + 2 \norm{\px - {\rm Avg}({\cal P}_i)}\cdot \norm{\hpc_i - {\rm Avg}({\cal P}_i)}}\\ &\leq (1 + 64\gamma) {\rm COST}_{{\cal P}}(C) + k \zeta^2 + 2 \Lambda k \cdot \zeta. \end{align*} where in the last term of the second inequality we used the fact that $\norm{\px - {\rm Avg}({\cal P}_i)} \leq \Lambda$ for all $i \in [k]$ and $\px \in {\cal P}_i$.\Hnote{We just discard $\size{{\cal P}_i}^2$ in the denominator in the second term of the second inequality ?}\Enote{Yes}\Hnote{can't we gain anything for this ? mention this ?}\Enote{I guess we can and we should!! In general, I believe we can also improve the theoretical bounds here if we do the analysis more carefully.} \end{proof} \remove{ \begin{remark}[Run time of $\mathsf{PrivatekMeans}$] The algorithm performs $t$ oracle queries to the non-private algorithm ${\cal A}$, each time over a collection of points of size $s = O(n/t)$. Then, the most expensive step is executing $\mathsf{PrivatekAverages}$, which takes $\tilde{O}(d k^2 n)$ time. \end{remark} } \remove{ } \remove{ } \remove{ \Enote{Delete the following event} } \section{Private $k$-Means Under Stability Assumption}\label{sec:kMeans} In this section we present an $(\varepsilon,\delta)$-differential private $k$-means approximation algorithm $\mathsf{PrivatekMeans}$ with utility guarantee that holds when the input is stable in the sense that we will define. We do so by reducing the problem of approximating the $k$-means of stable data into the problem from \cref{sec:finding-averages} of approximating the averages of clusters of points that are fully-partitioned by $k$ far balls. The idea is the following: Fix a database ${\cal P} \in ({\mathbb R}^d)^n$, a parameter $m < n$ and a (non-private) $k$-means approximation algorithm ${\cal A}$. Now assume that when executing ${\cal A}$ on $m$ i.i.d. samples from ${\cal P}$, then with high probability all these sets of $k$ centers are almost located at the same positions. More formally, if we repeate the above process $T$ times (for some parameter $T$) and denote by $\tilde{C}_t = \set{\pc_1^t, \ldots, \pc_k^t}$ the centers of iteration $t \in [T]$, then our stability assumption requires that with high probability, the multiset of all resulting centers ${\cal C} = \bigcup_{t \in [T]} \tilde{C}_t$ is fully-partitioned by $k$ far balls, where ${\rm Partition}({\cal C})$ (according to \cref{def:clusters-rel}) is exactly $\set{\set{\pc_1^t}_{t=1}^T, \ldots, \set{\pc_k^t}_{t=1}^T}$ (i.e., for each $i \in [k]$, the $i$'th centers of each execution are very close to each other, compared to the distance from the other centers). Then under this assumption, \Hnote{Don't we want to formalize this assumption in some environment and give it a name/number so it is easier to refer to and the text is less vague ?} we show in this section how to use algorithm $\mathsf{PrivatekAverages}$ for approximating the $k$-means of ${\cal P}$. The full details of $\mathsf{PrivatekMeans}$ are described in \cref{fig:kMeans}. The privacy guarantee is proven in \cref{sec:priv-kMeans}, the utility guarantee (under the stability assumption) is proven in \cref{sec:util-kMeans}. In \cref{sec:application} we show that a variant of the separation assumption in \cite{OstrovskyRSS12} implies our stability assumption. \begin{figure}[thb!] \begin{center} \noindent\fbox{ \parbox{.95\columnwidth}{ \begin{center}{ \bf Algorithm $\mathsf{PrivatekMeans}$}\end{center} \textbf{Input:} A multiset ${\cal P}$ of points in $B(\pt{0},\Lambda) \subseteq {\mathbb R}^d$, parameter $k \in {\mathbb N}$, privacy parameters $\varepsilon,\delta >0$ and a confidence parameter $\beta > 0$. Let $n = \size{{\cal P}}$. \textbf{Additional input:} A (non-private) $k$-means algorithm ${\cal A}$. \begin{enumerate} \item Let $T \in {\mathbb N}$ be a value to be determined by the analysis.\label{step:T} \item For each $t \in [T]$: \begin{enumerate} \item Let ${\cal S}_t$ be a database containing $m= \floor{\frac{n}{2T}}$ i.i.d. samples from ${\cal P}$ (with replacement).\label{step:sample} \item Compute $\tilde{C}_t \gets {\cal A}({\cal S}_t)$.\label{step:non-priv-centers} \end{enumerate} \item Let $\tilde{{\cal C}} = \bigcup_{t \in [T]} \tilde{C}_t$ (a ``multiset union'', that includes duplications).\label{step:new-multisets} \item Execute $\mathsf{PrivatekAverages}$ (\cref{fig:FindAverages}) on the $kT$-size multiset $\tilde{{\cal C}}$ with input parameters \noindent $\tilde{\alpha} = \frac1{n}, \tilde{\varepsilon} = \frac{\varepsilon}{6 k}$, $\tilde{\delta} = \frac{\min\set{\delta,\beta}}{4 e^{\varepsilon} k}$, $\tilde{k} = k$. Let $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$ be the outcome of the execution.\label{step:the-aver-estim} \item For each $i \in [k]:$ \begin{itemize} \item Let $\hat{{\cal P}}_i$ be the points in ${\cal P}$ that $\hpa_i$ is the closest point to them among $\set{\hat{\pa}_1,\ldots,\hat{\pa}_k}$. \label{step:compute-clusters-kmeans} \item Use the Gaussian Mechanism (\ref{fact:Gaus}) with parameters $\Lambda, \hat{\varepsilon} = \frac{\varepsilon}{6k}, \hat{\delta} = \frac{\delta}{8 e^{2\varepsilon} k}, \hat{\beta} = \frac{\beta}{2k}$ to compute a noisy average $\hpc_i$ of $\hat{{\cal P}}_i$.\label{step:add-gaus-noise \end{itemize} \item Output $\set{\hat{\pc}_1,\ldots,\hat{\pc}_k}$. \end{enumerate} }} \end{center} \caption{A private $k$-means approximation algorithm $\mathsf{PrivatekMeans}$ under stability assumption.\label{fig:kMeans}} \end{figure} \subsection{Privacy of $\mathsf{PrivatekMeans}$}\label{sec:priv-kMeans} The following claim states that for a suitable choice of the parameter $T$ in Step~\ref{step:T}, then the algorithm $\mathsf{PrivatekMeans}$ is differential-private. \begin{claim}[Privacy]\label{claim:kMeans-privacy} Let $N = N(d,k,\varepsilon,\delta)= \tilde{O}\paren{k^4 d \log^4(1/\delta)/\varepsilon^2}$ be the value from \cref{claim:main}, and assume that $T \geq \ceil{N/k}$, where $T$ is the value in Step~\ref{step:T} of $\mathsf{PrivatekMeans}$. Then Algorithm $\mathsf{PrivatekMeans}$ is $(\varepsilon ,\delta)$-differential private. \end{claim} \begin{proof} The proof builds on the fact that switching between sampling with replacement and without replacement has only a small effect on the privacy, as stated in \cref{fact:DP-with-replacement}. Consider a different variant of $\mathsf{PrivatekMeans}'$, in which the sampling of the $\approx n/2$ points in all Steps~\ref{step:sample} ($m = \floor{n/(2 T)}$ points in $T$ iterations) is done without replacement. Let ${\cal P} = \set{\px_1,\ldots,\px_n}$ and ${\cal P}' = \set{\px_1',\ldots,\px_n'}$ be two neighboring databases of points \Enote{define}. In the following we consider two independent executions $\mathsf{PrivatekMeans}'({\cal P})$ and $\mathsf{PrivatekMeans}'({\cal P}')$ (both with the same parameters $k,\varepsilon,\delta,\beta$). In the execution $\mathsf{PrivatekMeans}'({\cal P})$, for $t \in [T]$ let ${\cal J}_t \subseteq [n]$ be the $m$ chosen indices of the points ${\cal S}_t$ in Step~\ref{step:sample} (i.e., ${\cal S}_t = \set{\px_j}_{j \in {\cal J}_t}$), and let ${\cal J}_t'$ be the indices w.r.t the execution $\mathsf{PrivatekMeans}'({\cal P}')$. Since ${\cal J}_t$ and ${\cal J}_t'$ only depend on $n$ and not on the content of ${\cal P}$ and ${\cal P}'$, it is enough to prove that the output of both executions is $(\varepsilon,\delta)$-indistinguishable conditioned on the event that ${\cal J}_t = {\cal J}_t'$ for every $t \in [T]$. In the following, we assume that this event occurs. Since ${\cal P}$ and ${\cal P}'$ are neighboring, there exists at most one index $t \in [T]$ such that ${\cal S}_t$ of the execution $\mathsf{PrivatekMeans}'({\cal P})$ is different than the corresponding set in $\mathsf{PrivatekMeans}'({\cal P}')$, and therefore, the resulting $\hat{{\cal C}}$ in Step~\ref{step:new-multisets} is different by at most $k$ points. Since $\mathsf{PrivatekAverages}$ is $(\tilde{\varepsilon},\tilde{\delta})$-differential private for multisets of size $\geq N$ (\cref{claim:privacy}), we deduce that the resulting $k$ averages $\set{\tpa_1,\ldots,\tpa_k}$ in Step~\ref{step:the-aver-estim} are $(k\tilde{\varepsilon},k\tilde{\delta})$- indistinguishable, i.e., Step~\ref{step:the-aver-estim} is $(\frac{\varepsilon}{6}, \frac{\delta}{4 e^{\varepsilon}})$-differential private. Note that for any fixing of $\set{\tpa_1,\ldots,\tpa_k}$, Step~\ref{step:add-gaus-noise} is a composition of $k$ Gaussian mechanisms, and by basic composition (\cref{thm:composition1}) it is $(\frac{\varepsilon}{6}, \frac{\delta}{8 e^{2\varepsilon}})$-differential private. By iterative composition \Enote{is iterative is the right word?} of Step~\ref{step:the-aver-estim} and Step~\ref{step:add-gaus-noise} (\cref{fact:iter-comp}), we deduce that $\mathsf{PrivatekMeans}'$ is $(\frac{\varepsilon}{3}, \frac{\delta}{2 e^{\varepsilon}})$-differential private. Finally, we conclude that the original $\mathsf{PrivatekMeans}$, that chooses the points with replacement, is $(\varepsilon,\delta)$-differential private by applying \cref{fact:DP-with-replacement} with $m = n/2, \frac{\varepsilon}{3}, \frac{\delta}{2 e^{\varepsilon}}$. \end{proof} \subsection{Utility of $\mathsf{PrivatekMeans}$}\label{sec:util-kMeans} \Enote{Continue from here} In the following, we formalize our stability assumption by fixing some arbitrary set of $k$ centers $C= \set{\pc_1,\ldots,\pc_k}$ and a parameter $\gamma \in [0,1]$ and require that all resulting centers $\tilde{C}_t$ in Step~\ref{step:non-priv-centers} are "$\gamma$-close" to $C$: \begin{definition}[Event $E_{C}^{\gamma}$ (over a random execution of $\mathsf{PrivatekMeans}$)]\label{def:event-ECgamma} Let $\gamma \in [0,1]$, $C = \set{\pc_1,\ldots,\pc_k} \subseteq {\mathbb R}^d$ and let $D_i = \min_{j \neq i}\norm{\pc_i - \pc_j}$. We define $E_{C}^{\gamma}$ to be the event that for every $t \in [T]$ and $i \in [k]$, there exists $\tpc_i^t \in \tilde{C}_t$ such that $\norm{\tpc_i^t - \pc_i} \leq \gamma\cdot D_i$. \end{definition} Assuming that for each $i \in [k]$ the centers $\set{\pc_i^t}_{t=1}^T$ are close to each other, then for each $i$ any choice of a point $\pc_i$ that is close to $\set{\pc_i^t}_{t=1}^T$ will make the event $E_{C}^{\gamma}$ to occur (for suitable $\gamma$). Therefore, we can think of $C = \set{\pc_1,\ldots,\pc_k}$ as the choice of such centers that minimize ${\rm COST}_{{\cal P}}(C)$. If ${\cal A}$ is an $\omega$-approximation algorithm for $k$-means, it holds that ${\rm COST}_{{\cal P}}(C) \leq \min\set{{\rm COST}_{{\cal P}}(\tilde{C}_t)}_{t=1}^T \approx \min\set{ \omega \cdot {\rm OPT}_k({\cal P})}_{t=1}^T$ (the ``$\approx$'' holds by \cref{prop:cost-of-sample-is-good} for large enough $m$). In \cref{sec:application} we even see that when ${\cal P}$ is separated for $k$-means according to \cite{OstrovskyRSS12}, then with high probability the event $E_{C^*}^{\gamma}$ occur, where $C^*$ is an optimal $k$-means for ${\cal P}$. The following lemma summarizes the utility guarantee of $\mathsf{PrivatekMeans}$. Roughly speaking, the lemma states that when event $E_{C}^{\gamma}$ occurs, then with high probability $\mathsf{PrivatekMeans}$ outputs $k$ centers $\hat{C} = \set{\hat{\pc}_1,\ldots,\hat{\pc}_k}$ such that ${\rm COST}_{{\cal P}}(\hat{C})$ is bounded by $(1 + O(\gamma)) {\rm COST}_{{\cal P}}(C)$ (plus some small additive error). \begin{lemma}[Utility]\label{lem:kMeans-utility} Let $\varepsilon,\delta,\beta \in (0,1)$, let ${\cal A}$ be a (non-private) algorithm, let ${\cal P} \in (B(\pt{0},\Lambda))^n$, let $C = \set{\pc_1,\ldots,\pc_k} \subseteq {\mathbb R}^d$ with $\min_{i \neq j} \norm{\pc_i - \pc_j} \geq 1/n$ and let $\gamma \in [0,\frac1{28})$. Consider a random execution of $\mathsf{PrivatekMeans}$ on inputs ${\cal P},k,\varepsilon,\delta,\beta,{\cal A}$ with \begin{align*} T = \Omega\paren{\frac{d k^2 \ell \sqrt{\log\paren{\frac{k \ell}{\min\set{\beta,\delta}}}}}{\gamma} \cdot \log\paren{\frac{d k \ell n \Lambda}{\min\set{\beta,\delta}}}}, \end{align*} letting $\ell = \tilde{O}\paren{(dk \log(T/\delta) + \log^2(1/\delta))/\varepsilon}$ be the value from \cref{claim:main} with respect to $\tilde{n} = k T, d, k, \tilde{\varepsilon} = \frac{\varepsilon}k, \tilde{\delta} = \frac{\min\set{\delta,\beta}}{k}$. Assume that event $E_{C}^{\gamma}$ occurs, and let $\hat{C} = \set{\hpc_1,\ldots,\hpc_k}$ be output of the execution. Then with probability $1-\beta/2$ it holds that \begin{align*} COST_{{\cal P}}(\set{\hpc_1,\ldots,\hpc_k}) \leq (1 + 64\gamma) {\rm COST}_{{\cal P}}(C) + O\paren{\frac{\Lambda^2 k^4 d}{\varepsilon^2} \log(k/\delta) \log(k/\beta)} \end{align*} \end{lemma} \begin{proof} In the following, for $t \in [T]$ let $\hat{C}_t = \set{\hpc_1^t,\ldots,\hpc_k^t}$ where we denote by $\hpc_i^t$ the center that is close to $\pc_i$, i.e., $\norm{\hpc_i^t - \pc_i} \leq \gamma \cdot D_i$, where $D_i = \min_{j \neq i}\norm{\pc_i- \pc_j}$ (holds by event $E_C^{\gamma}$). In addition, for $i \in [k]$, let $\pa_i = {\rm Avg}(\set{\hpc_{i}^t}_{t=1}^T)$ and note that \begin{align}\label{eq:dist-pai-pci} \forall i \in [k]:\text{}\norm{\pa_i - \pc_i} \leq \gamma \cdot D_i \end{align} Now, let ${\cal C}$ be the multiset from Step~\ref{step:new-multisets} of the algorithm, and note that ${\cal C}$ is fully-partitioned by the set of balls $\set{B(\pc_i, r_i = 2\gamma D_i)}_{i=1}^k$ which are also \textbf{very} far balls (according to \cref{def:sep-balls}) since $\gamma < \frac1{28}$, and the clusters of ${\cal C}$ are $\set{\set{\hpc_{1}^t}_{t=1}^T, \ldots, \set{\hpc_{k}^t}_{t=1}^T}$. Therefore, when applying algorithm $\mathsf{PrivatekAverages}$ in Step~\ref{step:the-aver-estim}, we obtain by \cref{claim:utility-kAverg} a set of $k$ points $\set{\hpa_1,\ldots,\hpa_k}$ such that \begin{align}\label{eq:dist-pai-hpai} \forall i \in [k]:\text{ } &\text{}\norm{\pa_i - \hpa_i}\nonumber\\ &\leq O\paren{\frac{r_i \cdot d k^2 \ell \sqrt{\log(k \ell/\tilde{\delta})}}{\tilde{\varepsilon} \tilde{n}} \paren{(1 + \tilde{\alpha}/r_i) \log(d k \ell/\tilde{\delta}) + \log \paren{\frac{\Lambda d k}{\tilde{\alpha} \tilde{\delta}}}}}\nonumber\\ &\leq O\paren{\frac{d k^2 \ell \sqrt{\log\paren{\frac{k \ell}{\min\set{\beta,\delta}}}}}{T} \cdot \log\paren{\frac{d k \ell n \Lambda}{\min\set{\beta,\delta}}}} \cdot D_i\\ &\leq \gamma\cdot D_i,\nonumber \end{align} where in the second inequality we used the fact that $r_i \leq D_i$ and that $D_i \geq 1/n = \tilde{\alpha}$, and in the second inequality we used the lower bound on $T$. Therefore, we deduce by \cref{eq:dist-pai-pci,eq:dist-pai-hpai} that \begin{align} \forall i \in [k]:\text{}\norm{\hpa_i - \pc_i} \leq 2\gamma \cdot D_i \end{align} Now, let $\hat{{\cal P}}_1,\ldots,\hat{{\cal P}}_k$ be the clusters from Step~\ref{step:compute-clusters-kmeans} of the algorithm. By \cref{prop:close-centers-have-similar-cost} we get that \begin{align}\label{eq:avg-cost} \sum_{i=1}^k \sum_{\px \in \hat{{\cal P}}_i} \norm{\px - {\rm Avg}(\hat{{\cal P}}_i)}^2 \leq (1 + 64\gamma) {\rm COST}_{{\cal P}}(C) \end{align} Since the algorithm compute a noisy estimation $\hpc_i$ of each ${\rm Avg}(\hat{{\cal P}}_i)$, we get by the properties of the Gaussian mechanism (see \cref{obs:Gaus-aver}) that with probability $1-\beta$ it holds that \begin{align}\label{eq:dist-from-avg} \forall i \in [k]:\text{}\norm{\hpc_i - {\rm Avg}(\hat{{\cal P}}_i)} &\leq O\paren{\frac{\Lambda}{\hat{\varepsilon} \size{\hat{{\cal P}}_i}} \sqrt{d \log(1/\hat{\delta}) \log(1/\hat{\beta})}}\\ &= O\paren{\frac{\Lambda k^2}{\varepsilon \size{\hat{{\cal P}}_i}} \sqrt{d \log(k/\delta) \log(k/\beta)}}\nonumber \end{align} We conclude from \cref{eq:avg-cost,eq:dist-from-avg} that \begin{align*} \lefteqn{{\rm COST}_{{\cal P}}(\set{\hpc_1,\ldots,\hpc_k})}\\ &\leq \sum_{i=1}^k \sum_{\px \in \hat{{\cal P}}_i} \norm{\px - \hpc_i}^2\\ &= \sum_{i=1}^k \sum_{\px \in \hat{{\cal P}}_i} \paren{\norm{\px - {\rm Avg}(\hat{{\cal P}}_i)}^2 + \norm{\hpc_i - {\rm Avg}(\hat{{\cal P}}_i)}^2 + 2 \norm{\px - {\rm Avg}(\hat{{\cal P}}_i)}\cdot \norm{\hpc_i - {\rm Avg}(\hat{{\cal P}}_i)}}\\ &\leq (1 + 64\gamma) {\rm COST}_{{\cal P}}(C) + O\paren{\frac{\Lambda^2 k^4 d}{\varepsilon^2} \log(k/\delta) \log(k/\beta)} + 2 \Delta \cdot O\paren{\frac{\Lambda k^3}{\varepsilon} \sqrt{d \log(k/\delta) \log(k/\beta)}}\\ &= (1 + 64\gamma) {\rm COST}_{{\cal P}}(C) + O\paren{\frac{\Lambda^2 k^4 d}{\varepsilon^2} \log(k/\delta) \log(k/\beta)} \end{align*} \end{proof} \remove{ } \remove{ } \remove{ \Enote{Delete the following event} }
{'timestamp': '2021-12-30T02:23:06', 'yymm': '2112', 'arxiv_id': '2112.14445', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14445'}
arxiv
\section{Great Expectations -- Explainable Machines\label{ch:intro-sec:intro}}% Transparency, interpretability and explainability promote understanding and confidence. % As a society, we strive for transparent governance and justified actions that can be scrutinised and contested. % Such a strong foundation provides a principled mechanism for reasoning about fairness and accountability, which we have come to expect in many areas. % Artificial Intelligence (AI) systems, however, are not always held to the same standards. % This becomes problematic when data-driven algorithms power applications that either implicitly or explicitly affect people's lives, for example in banking, justice, job screenings or school admissions~\cite{o2016weapons}. % In such cases, creating explainable predictive models or retrofitting transparency into pre-existing systems is usually expected by the affected individuals, or simply enforced by law. % A number of techniques and algorithms are being proposed to this end; however, as a relatively young research area, there is no consensus within the AI discipline on a suite of technology to address these challenges.% Building intelligible AI systems is oftentimes problematic, especially given their varied, and sometimes ambiguous, audience~\cite{kirsch2017explain,preece2018stakeholders}, purpose~\cite{hall2019systematic} and application domain~\cite{bhatt2020explainable}. % While intelligent systems are frequently deemed (unconditionally) opaque, it is not a definitive property and it largely depends on all of the aforementioned factors, some of which fall beyond the consideration of a standard AI development lifecycle. % Without clearly defined explainability desiderata~\cite{sokol2020explainability} addressing such diverse aspects can be challenging, in contrast to designing AI systems purely based on their predictive performance, which is often treated as a quality proxy that can be universally measured, reported and compared. % In view of this disparity, many engineers (incorrectly) consider these two objectives as inherently incompatible~\cite{rudin2019stop}, thus choosing to pursue high predictive performance at the expense of opaqueness, which may be incentivised by business opportunities.% While high predictive power of an AI system might make it useful, its explainability % determines its acceptability. % The pervasiveness of automated decision-making in our everyday life, some of it bearing social consequences, requires striking a balance between the two that is appropriate for what is at stake; for example, approaching differently a car autopilot and an automated food recommendation algorithm. % Another domain that could benefit from powerful and explainable AI is (scientific) discovery~\cite{roscher2020explainable} -- intelligent systems may achieve super-human performance, e.g., AlphaGo~\cite{silver2017mastering}, however a lack of transparency renders their mastery and ingenuity largely unattainable. % Such observations have prompted the Defense Advanced Research Projects Agency (DARPA) to announce the eXplainable AI (XAI) programme~\cite{gunning2016broad,gunning2017explainable} that promotes building a suite of techniques to % (i) create more explainable models while preserving their high predictive performance and % (ii) enable humans to understand, trust and effectively manage intelligent systems.% To address these challenges, AI explainability and Machine Learning (ML) interpretability solutions are developed at breakneck speed, giving a perception of a chaotic field that may seem difficult to navigate at times. % Despite these considerable efforts, a universally agreed terminology and evaluation criteria are still elusive, with many methods introduced to solve a commonly acknowledged but under-specified problem, and their success judged based on ad-hoc measures. % In this paper we take a step back and re-evaluate the foundations of this research to organise and reinforce its most prominent findings that are essential for advancing this field, with the aim of providing a well-grounded platform for tackling DARPA's XAI mission. % Our work thus reconciles and complements the already vast body of technical contributions, philosophical and social treatises, as well as literature surveys by bringing to light the interdependence of interdisciplinary and multifaceted concepts upon which explainable AI and interpretable ML are built. % Our discussion manoeuvres through this incoherent landscape by connecting numerous open questions and challenges -- rather than attempting to solve any individual issue -- which is achieved through a comprehensive review of published work that acknowledges any difficulties or disagreements pertaining to these research topics.% In particular, we review the notions of a \emph{black box} and \emph{opaqueness} in the context of artificial intelligence, and formalise \emph{explainability} -- the preferred term in our treatment of the subject (Section~\ref{sec:bbnes}). % We discuss the meaning and purpose of explanations as well as identify theoretical and practical prerequisites for lifting unintelligibility of predictive systems, based on which we define explainability as a socially-grounded technology providing insights that lead to \emph{understanding}, which both conceptualises such techniques and fixes their evaluation criterion. % Furthermore, we show how transparency, and other terms often used to denote similar ideas, can be differentiated from explainability -- both overcome opaqueness, but only the latter leads to understanding -- which we illustrate with decision trees of different sizes. % While the premise of our definition is clear, understanding largely depends upon the explanation recipients, who come with a diverse range of background knowledge, experience, mental models and expectations~\cite{gregor1999explanations}. % Therefore, in addition to technical requirements, explainability tools should also embody various social traits as their output is predominantly aimed at humans. % We discuss these aspects of AI and ML explainers in Section~\ref{ch:intro-sec:humans}, which considers the role of an \emph{explanation audience} and people's preference for \emph{contrastive statements} -- XAI insights inspired by explainability research in the social sciences~\cite{miller2019explanation}. % We also examine the social and bi-directional \emph{explanatory process} underlying conversational explanations between humans, highlighting the desire of explainees (i.e., the audience of explanations) to customise, personalise and contest various aspects of explanatory artefacts provided for opaque systems within a congruent interaction~\cite{sokol2018glass,sokol2020one}. % We then connect these desiderata to validation and evaluation approaches for explainable AI and Interpretable ML (IML) techniques, arguing for studies that concentrate on assessing the understanding gained by the target audience in favour of other metrics.% Next, in Section~\ref{sec:tradeoff}, we take a closer look at explainability by design (ante-hoc) and techniques devised to remove opaqueness from pre-existing black boxes (post-hoc and, often, model-agnostic), focusing on the latter type given that such methods are universally applicable to a wide variety models, which increases their potential reach and impact. % While these explainers are appealing, their modus operandi can be an unintended cause of low-fidelity explanations that lack truthfulness with respect to the underlying black box~\cite{rudin2019stop}. % Furthermore, their flexibility means that, from a technical perspective, they can be applied to any predictive model, however they may not necessarily be equally well suited to the intricacies of each and every one of them. % Creating a faithful post-hoc explainer requires navigating multiple trade-offs reflected in choosing specific components of otherwise highly-modular explainability framework and parameterising these building blocks based on the specific use case~\cite{sokol2019blimey,sokol2020towards,sokol2020limetree,sokol2020tut}. % These observations % prompt us to revisit the disputed \emph{transparency--predictive power trade-off} and assess \emph{benefits} of interpretability that go beyond understanding of predictive algorithms and their decisions, such as their \emph{fairness} and \emph{accountability}.% We continue our investigation in Section~\ref{sec:elephant} by assessing % \emph{explainability needs for various parts of predictive systems} -- data, models and predictions -- as well as multiplicity and diversity of these, sometimes incompatible, insights. % To this end, we use an \emph{explainability taxonomy} derived from the Explainability Fact Sheets~\cite{sokol2020explainability} to reason about such systems within a well-defined framework that considers both their social and technical requirements. % Notably, it covers human aspects of explanations, thus giving us a platform to examine the audience (explainees), explanation complexity and fidelity, as well as the interaction mode, among many others. % This discussion leads us to a high-level overview of landmark XAI and IML literature that highlights the interplay between various (often interdisciplinary and multifaceted) concepts popular in the field, thus painting a coherent perspective. % Section~\ref{sec:summary} then summarises our main observations and contributions:% \begin{itemize} \item we formally define explainability and catalogue other relevant nomenclature;% \item we establish a spectrum of opaqueness determined by the desired level of transparency and interpretability;% \item we identify important gaps in human-centred explainability from the perspective of current technology;% \item we dispute universality of post-hoc explainers given their complexity and high degree of modularity; and% \item we address explanation multiplicity through explanatory protocols for data, models and predictions.% \end{itemize} These insights pave the way for the development of more intelligible and robust machine learning and artificial intelligence explainers.% \section{Defining Black-Box and Explainable Artificial Intelligence\label{sec:bbnes}}% To avoid a common criticism of explainability research, we begin by discussing the concept of interpretability. % To this end, we identify causes of opaqueness when dealing with intelligent systems and assess prerequisites for their understanding. % In this setting we observe \textbf{shades of black-boxiness}: an interpretability spectrum determined by the extent of understanding exhibited by explainees, which, among others, is conditioned upon their mental capacity and background knowledge. % We link this finding with various notions used in XAI and IML literature, a connection that helps us to fix the nomenclature and \textbf{define explainability} (our preferred term).% The term \textbf{black box} can be used to describe a system whose internal workings are opaque to the observer -- its operation may only be traced by analysing its inputs and outputs~\cite{beizer1995black,bunge1963general}. % Similarly, in computer science (including AI and ML) a black box is a (data-driven) algorithm that can be understood as an automated process that we cannot reason about beyond observing its behaviour. % For AI in particular, \citet{rudin2019stop} points out two main sources of opaqueness: % (i) a \emph{proprietary} system, which may be transparent to its creators, but operates as a black box; and % (ii) a system that is too \emph{complex} to be comprehend by \emph{any human}. % While the latter case concerns entities that are universally opaque for the \emph{entire population}, we argue that -- in contrast to a binary classification~\cite{dawkins2011tyranny} -- this definition of black boxes essentially establishes a (continuous) \emph{spectrum of understanding}. % Notably, different levels and degrees of transparency and understandability have previously been pointed out and discussed in relation to individual elements of predictive systems, explainees' background knowledge and complexity of information conveyed by explanations, however these observations are often limited to multiple, hand-crafted discrete categories~\cite{marr1982vision,lipton2016mythos,arrieta2020explainable,roscher2020explainable,kim2021multi}.% For example, a seminal inquiry into opaqueness of visual perception systems by \citet{marr1982vision} suggested three different levels at which information processing devices can be understood. % The top tier is \emph{computational theory}, which concerns abstract specification of the problem at hand and the overall goal. % It is followed by \emph{representation and algorithm}, which deals with implementation details and selection of an appropriate representation. % The final level is \emph{hardware implementation}, which simply establishes physical realisation of the explained problem. % To illustrate his framework, \citet{marr1982vision} argued that understanding why birds fly cannot be achieved by only studying their feathers: ``% In order to understand bird flight, we have to understand aerodynamics; only then do the structure of feathers and the different shapes of birds' wings make sense.% '' % Nonetheless, he points out that these three tiers are only loosely related and some phenomena may be explained at only one or two of them, therefore it is important to identify which of these levels need to be covered in each individual case to arrive at understanding.% \citeauthor{lipton2016mythos}'s categorisation of transparency~\cite{lipton2016mythos} -- which he defines as the ability of a human to comprehend the (ante-hoc) mechanism employed by a predictive model -- may be roughly seen as a modern interpretation of \citeauthor{marr1982vision}'s levels of understanding~\cite{marr1982vision}. % The first of \citeauthor{lipton2016mythos}'s dimensions is \emph{decomposability}, which entails appreciation of individual components that constitute a predictive system, namely: input, parameterisation and computation; % it can be compared to \citeauthor{marr1982vision}'s \emph{computational theory}. % Next, \emph{algorithmic transparency} involves understanding the modelling process embodied by a predictive algorithm, which relates to \citeauthor{marr1982vision}'s \emph{representation and algorithm}. % Finally, \emph{simulatability} enables humans to simulate a decisive process in vivo at the level of the entire model, capturing a concept similar to \citeauthor{marr1982vision}'s \emph{hardware implementation}. % These three levels of \citeauthor{lipton2016mythos}'s notion of transparency span diverse processes fundamental to predictive modelling, and their understanding can offer a comprehensive, albeit predominantly technical, view of such systems.% While not universally recognised, knowledge, perception and comprehension of a phenomenon undeniably depend upon the observer's cognitive capabilities and mental model, the latter of which is an internal representation of this phenomenon built on real-world experiences~\cite{kulesza2013too}. % For example, \citet{kulesza2013too} outline a \emph{fidelity}-based understanding spectrum spanning two dimensions:% \begin{description}[labelindent=2\parindent]% \item[completeness] captures how truthful the understanding is overall (\emph{generality}); and% \item[soundness] determines how accurate the understanding is for a particular phenomenon (\emph{specificity}).% \end{description} Therefore, a \emph{complete} understanding of an event from a certain domain is equivalently applicable to other, possibly unrelated, events from the same domain; for example, gravity in relation to a pencil falling from a desk. % A \emph{sound} understanding, on the other hand, accurately describes an event without (over-)simplifications, which may result in misconceptions; for example, leaving a pencil on a slanted surface results in it falling to the ground. % Striking the right balance between the two depends upon the observer and may be challenging to achieve: completeness without soundness is likely to be too broad, hence uninformative; and the opposite can be too specific to the same effect.% \footnote{% Note that comparable distinctions can be found across literature. % For example, a differentiation between \emph{functional} and \emph{mechanistic} \emph{understanding}, where the former concerns ``functions, goals, and purpose[s]'' and the latter relies on ``parts, processes, and proximate causal mechanisms''~\cite{lombrozo2014explanation,lombrozo2019mechanistic}. % A similar categorisation is also pertinent to \emph{knowledge}, which can either be \emph{declarative} or \emph{procedural}~\cite{gregor1999explanations} -- the former allows to recall facts (i.e., ``knowing that'') and the latter translates to skills that enable performing a cognitive task (i.e., ``knowing how'').% }% Within this space, \citet{kulesza2013too} identify two particularly appealing types of a mental model% :% \begin{description}[labelindent=2\parindent,leftmargin=4\parindent] \item[functional] which is enough to operationalise a concept but does not necessarily entail the understanding of its underlying mechanism (akin to The Chinese Room Argument~\cite{searle1980minds,penrose1989emperor}); and% \item[structural] which warrants a detailed understanding of how and why a concept operates.% \end{description} For example, a functional understanding of a switch and a light bulb circuit can be captured by the dependency between flipping the switch and the bulb lighting up. % A structural understanding of the same phenomenon, on the other hand, may focus on the underlying physical processes, e.g., closing an electrical circuit allows electrons to ``move'', which heats up the bulb's filament, thus emitting light (note simplifications employed by this explanation). % The former understanding is confined to operating a light switch, while the latter can be generalised to many other electrical circuits. % Each one is aimed at a different audience and their complexity should be fine-tuned for the intended purpose as explanations misdirected towards an inappropriate audience may be incomprehensible. % These observations lead us to argue that such a spectrum of understanding in human explainability can constitute a yardstick for determining explanatory qualities of predictive algorithms -- a link that has mostly been neglected in the literature, but which can help us to explicitly define popular XAI and IML terminology.% A considerable amount of research into explainable AI and interpretable ML published in recent years appears to suggest that it is a freshly established field; however, in reality it is more of a renaissance~\cite{gregor1999explanations}. % While work in this area indeed picked up the pace in the past decade, interest in creating transparent and explainable, data-driven algorithms dates back at least to the 1990s~\cite{rudin2019stop}, and further back to the 1970s if expert systems are taken into account~\cite{leondes2001expert,gregor1999explanations}. % With such a rich history and the increased publication velocity attributed to the more recent re-establishment of the field, one may think that this research area has clearly defined objectives and a widely shared and adopted \textbf{terminology}. % However, with an abundance of keywords that are often used interchangeably in the literature -- without precisely defining their meaning -- this is not yet the case. % The most common terms include, but are not limited to:% \begin{tasks}[label=\labelitemi,item-indent=3\parindent,label-offset=0pt,after-item-skip={\dimexpr\itemsep+\parsep}](4)% \task explainability, \task observability, \task transparency, \task explicability, \task intelligibility, \task comprehensibility, \task understandability, \task interpretability, \task simulatability, \task explicitness, \task justification, \task rationalisation, \task sensemaking,% \task insight, \task evidence, \task reason, and \task cause. \end{tasks} Other keywords -- such as function (of), purpose (of), excuse, consequence, effect, implication and meaning -- can also be found in non-technical explainability research~\cite[page 32]{achinstein1983nature}. % Additionally, \emph{explanandum} or \emph{explicandum} often appear in XAI and IML literature, however these terms, which are borrowed from philosophy of science, denote the concept to be explained.% While early XAI and IML research might have missed out on an opportunity to clearly define its goals and nomenclature, recent work has attempted to rectify this problem~\cite{% biran2014justification,biran2017explanation,rudin2019stop,gilpin2018explaining,alvarez2019weight,mohseni2021multidisciplinary,chen2022machine,lipton2016mythos,vilone2020explainable,markus2021role,guidotti2018survey,langer2021we,rosenfeld2019explainability,bibal2016interpretability,papenmeier2022complicated,montavon2018methods,yao2021explanatory,furnkranz2020cognitive,murdoch2019definitions,roscher2020explainable,kim2021multi,adadi2018peeking,offert2017know,arrieta2020explainable,marcinkevivcs2020interpretability,kaur2022sensible,stepin2021survey,palacio2021xai% }. % Within this spaces, some authors simply list the relevant terms without assigning any meaning to them~\cite{marcinkevivcs2020interpretability} while others cite dictionary definitions~\cite{roscher2020explainable,arrieta2020explainable,palacio2021xai} -- e.g., to interpret is ``to explain [\ldots] the meaning of'' or ``present in understandable terms'' according to Merriam-Webster -- or suggest that many such keywords are synonymous~\cite{bibal2016interpretability}. % It is also common to find circular or tautological definitions, which use one term from the list shown above to specify another~\cite{adadi2018peeking}; % for example, ``something is explainable when we can interpret it'', ``interpretability is making sense of ML models'', ``interpretable systems are explainable if their operations can be understood by humans'' or ``intelligibility is the possibility to comprehended something''. % Hierarchical and ontological definitions of these terms also appear in the literature~\cite{rosenfeld2019explainability,bibal2016interpretability,stepin2021survey}, often creating a web of connections that is difficult to parse, follow and apply. % Another counterproductive approach to defining these concepts assumes that their meaning is inherently intuitive or can only be captured by tacit knowledge -- viewpoints that can be summarised by ``I know it when I see it'' phrase~\cite{offert2017know}.% A different route to specifying these terms is binding keywords to particular components of a predictive pipeline or associating them with the technical and social properties of such a system~\cite{markus2021role,lipton2016mythos,roscher2020explainable}; however, the former is just a labelling strategy and the latter assumes that we can achieve explainability by simply fulfilling a set of requirements. % A fictitious scenario under this purview could determine that data are understandable, models are transparent and predictions are explainable; % the overall interpretability of predictive pipelines, on the other hand, is determined by the fidelity, brevity and relevance of the insights produced by the designated method. % More specifically, transparency is oftentimes associated with ante-hoc methods (the internal mechanisms of a predictive model) and interpretability with post-hoc approaches (the observable behaviour a system)~\cite{lipton2016mythos}; % alternatively, interpretability is designated for models and explainability for their outputs (more precisely, reasons behind predictions)~\cite{kim2021multi}. % Similarly, simulatability may be linked to an entire model, decomposability to its individual components and algorithmic transparency to the underlying training algorithm~\cite{lipton2016mythos}. % Interpretability has also been defined as a domain-specific notion that imposes ``a set of application-specific constraints on the model'', thus making this concept only applicable to predictive models that can provide their own explanations (i.e., ante-hoc interpretability) and should not, along with the term explainability, be used to refer to ``approximations to black box model predictions'' (i.e., post-hoc explainability)~\cite{rudin2019stop}. % In this particular view, therefore, a predictive model is interpretable if it ``obeys structural knowledge of the domain, such as monotonicity, causality, structural (generative) constraints, additivity or physical constraints that come from domain knowledge''.% Alternatively, interpretability could be used as an umbrella term and refer to data, models and post-hoc approaches as long as it facilitates extracting helpful information from these components or produces insights into them~\cite{murdoch2019definitions}. % This designation, however, may not be universal and, to complicate matters even more, certain terms can be used with respect to multiple elements of a predictive system, causing confusion. % For example, transparency may relate to predictive models, interpretability to input data and models, and explainability to data, models and human recipients~\cite{roscher2020explainable}. % While transparency may be uniquely linked to predictive models, it can still carry multiple meanings and apply to operations of a model as well as its design, components and the underlying algorithmic process~\cite{roscher2020explainable,lipton2016mythos}. % Desiderata-based definitions appearing in the literature, on the other hand, specify explainability through a mixture of properties such as interpretability (determined by clarity \& parsimony) and fidelity (consisting of completeness \& soundness)~\cite{markus2021role,rosenfeld2019explainability}; nonetheless, note that achieving both does not necessarily guarantee better comprehension of the explained system. % In like manner, \citet{alvarez2019weight} used the \emph{weight of evidence} idea from information theory to mathematically define AI and ML explainability and outline a precise list of its desiderata. % While appealing, the complexities of the real world make their conceptualisation difficult to apply at large. % \citet{murdoch2019definitions} followed a similar route and captured interpretation, understanding and evaluation of data-driven systems in the predictive--descriptive--relevant (PDR) framework, which spans: predictive performance (accuracy) of a model; descriptive capabilities of its (post-hoc) explainer quantified via fidelity; and relevancy of the resulting explanatory insights determined by their ability to provide ``insight[s] for a particular audience into a chosen problem''.% Within this chaotic landscape some researchers propose flexible definitions that are inspired by interdisciplinary work and can accommodate a variety of contexts while maintaining a precise and coherent meaning. % \citet{gilpin2018explaining} offered definitions of ``explanation'', ``interpretability'' and ``explainability'' drawing from a broad body of literature in an effort to standardise XAI and IML findings. % While their notions appear somewhat vague -- explanations should answer ``Why?'' and ``Why-should?'' questions until such questions can no longer be asked -- they argue for making explanations \emph{interpretable} and \emph{complete}, striving towards human \emph{understanding} that depends on the explainee's cognition, knowledge and biases. % Similarly, \citet{biran2014justification} were concerned with \emph{explanations}, which they characterised as ``giving a reason for a prediction'' and answering ``how a system arrives at its prediction''. % They also defined \emph{justifications} as ``putting an explanation in a context'' and conveying ``why we should believe that the prediction is correct'', which, they note, do not necessarily have to correspond to how the predictive system actually works. % Notably, many of these observations reappear across diverse publications, with the shared theme indicating that explanations should always answer an implicit or explicit ``Why?'' question~\cite{koura1988approach}, in addition to addressing ``What?'' and ``How?''~\cite{miller2019explanation,palacio2021xai}. % In a later piece of work, \citet{biran2017explanation} defined explainability as ``the degree to which an observer can understand the cause of a decision'' (also adopted by \citet{miller2019explanation}), thus making it much more explainee-centred. % While many authors use the term \emph{cause} rather loosely in XAI and IML research, we argue against such practice -- it is important to reserve it exclusively for insights extracted from \emph{causal} models~\cite{pearl2018book}.% More recently, based on an extensive review of literature in computer science and related disciplines, \citet{mohseni2021multidisciplinary} provided a collection of definitions for the most common terms in explainable AI and interpretable ML, nonetheless the underlying rationale is predominantly qualitative making them difficult to operationalise. % Similarly, \citet{arrieta2020explainable} differentiated between the following terms: understandability/intelligibility, comprehensibility, interpretability/transparency and explainability. % Specifically, they defined interpretability or transparency as a \emph{passive} characteristic of a model that allows humans to make sense of it on different levels -- e.g., its internal mechanisms and derivation of predictions -- therefore relating it to the cognitive skills, capacities and limitations of individual explainees. % Explainability, on the other hand, was described as an \emph{active} characteristic of a model that is achieved through actions and procedures employed (by the model) to clarify its functioning for a certain audience. % \citet{montavon2018methods} also offered definitions of these two terms -- interpretability and explainability -- from a perspective of functional understanding~\cite{lombrozo2014explanation,lombrozo2019mechanistic}. % They characterised interpretability as a mapping of an abstract concept, e.g., a predicted class, onto a domain that can be comprehended by a human; % explainability, in their view, is responsible for providing a collection of factors -- expressed in an interpretable domain -- that contribute to an automated decision of a particular instance. % In summary, their goal is to study and understand how inputs are mapped to outputs, possibly via a human-comprehensible representation of relevant concepts.% Each definition conveys a more or less precise meaning that can be used to label relevant techniques, however they do not necessarily clarify and help to navigate the complex landscape of IML and XAI research. % To organise this space, we categorise the underlying terminology based on three criteria:% \begin{itemize} \item \emph{properties} of systems;% \item \emph{functions} and \emph{roles} that they serve; and% \item \emph{actions} required to process, assimilate and internalise information elicited by them.% \end{itemize} The core concept around which we build our nomenclature is \textbf{explainability}; we define it as \textbf{insights that lead to understanding} (the \textbf{role} of an explanation) -- a popular and widely accepted rationale in the social sciences~\cite{koehler1991explanation,baumeister1994self,lombrozo2006structure,paez2019pragmatic,woodward1979scientific,achinstein1983nature}. % While it may seem abstract, understanding can be assessed with questioning dialogues~\cite{walton2007dialogical,walton2011dialogue,walton2016dialogue,arioua2015formalizing,madumal2019grounded} -- e.g., a machine interrogating the explainees to verify their understanding of the phenomenon being explained at the desired level of detail -- which are the opposite of explanatory dialogues. % Such a process reflects how understanding is tested in education, where the quality of tuition as well as knowledge and skills of pupils are evaluated through standardised tests and exams (albeit not without criticism~\cite{mead2015teacher}). % Furthermore, encouraging people to explain a phenomenon helps them to realise the extent of their ignorance and confront the complexity of the problem, which are important factors in exposing The Illusion of Explanatory Depth~\cite{rozenblit2002misunderstood} -- a belief that one understands more than one actually does.% This notion of explainability and the three building blocks of XAI and IML terminology allow us to precisely define the other popular terms. % Therefore,% \begin{tasks}[label=\labelitemi,item-indent=3\parindent,label-offset=0pt,after-item-skip={\dimexpr\itemsep+\parsep}](3)% \task \emph{observability},% \task \emph{transparency},% \task \emph{explicability},% \task \emph{intelligibility},% \task \emph{comprehensibility},% \task \emph{understandability},% \task \emph{interpretability},% \task \emph{simulatability}, and% \task \emph{explicitness}% \end{tasks} are \textbf{properties} of an AI or ML system % that enable it to % directly (ante-hoc) or indirectly (post-hoc) % convey information of varied complexity, the \emph{understanding} of which depends upon the cognitive capabilities and (domain) expertise of the explainee. % For example, observing an object falling from a table is a transparent phenomenon per se, but the level of its understanding, if any, is based upon the depth of the observer's physical knowledge. % Such characteristics provide% \begin{tasks}[label=\labelitemi,item-indent=3\parindent,label-offset=0pt,after-item-skip={\dimexpr\itemsep+\parsep}](3)% \task \emph{justification},% \task \emph{rationalisation},% \task \emph{insight},% \task \emph{evidence}, and% \task \emph{reason}% \end{tasks} (\textbf{roles}) that can be used to% \begin{tasks}[label=\labelitemi,item-indent=3\parindent,label-offset=0pt,after-item-skip={\dimexpr\itemsep+\parsep}](3)% \task \emph{reason} about,% \task \emph{make sense} of,% \task \emph{rationalise},% \task \emph{justify},% \task \emph{interpret}, or% \task \emph{comprehend}% \end{tasks} (note that here these are used as verbs) behaviour of a -- black-box or glass-box -- predictive system, all of which are \textbf{actions} that under the right circumstances lead to \emph{understanding}. % While \emph{simulatability} is also based upon observing a transparent process and replicating it, such an \textbf{action} does not necessarily imply understanding of the underlying phenomenon -- recall the difference between declarative and procedural knowledge~\cite{gregor1999explanations}, structural and functional mental models~\cite{kulesza2013too}, functional and mechanistic understanding~\cite{lombrozo2014explanation,lombrozo2019mechanistic} and The Chinese Room Argument~\cite{searle1980minds} discussed earlier. % Lastly, a \emph{cause} has a similar meaning to a \emph{reason}, but the first one is derived from a causal model, whereas the latter is based purely on observations of the behaviour of a (black-box) model.% Such a setting makes a welcome connection between the XAI and IML terminology synthesised by the equation% \[% \texttt{Explainability} \; = \; % \underbrace{% \texttt{Reasoning} \left( \texttt{Transparency} \; | \; \texttt{Background Knowledge} \right)% }_{\textit{understanding}}% \text{,}% \]% which defines \texttt{Explainability} as the \textbf{process} of deriving \emph{understanding} -- i.e., extracting meaning -- through \texttt{Rea\-son\-ing} applied to \texttt{Transparent} insights distilled from a data-driven predictive system that are adjusted to the explainee's \texttt{Background Knowledge}. % In this process, the \texttt{Reasoning} can either be done by the explainer or the explainee, and there is an implicit assumption that the explainee's \texttt{Background Knowledge} aligns with the \texttt{Transparent} representation of the predictive model. % If the latter does not hold, mitigation techniques such as employing an \emph{interpretable representation} can be used to communicate concepts that are otherwise incomprehensible~\cite{ribeiro2016why,sokol2019blimey,sokol2020towards}. % \texttt{Reasoning} also comes in many different shapes and sizes depending on the underlying system (\texttt{Transparency}) as well as the explainer and the explainee (\texttt{Background Knowledge}); for example, % logical reasoning with facts, % causal reasoning over a causal graph, % case-based reasoning with a fixed similarity metric, and % artificial neuron activation analysis for a \emph{shallow} neural network.% Therefore, linear models are transparent given a reasonable number of features; additionally, with the right ML and domain background knowledge -- requirement of normalised features, effect of feature correlation and the meaning of coefficients -- the explainee can reason about their properties, leading to an explanation based on understanding. % Similarly, a visualisation of a \emph{shallow} decision tree can be considered both transparent and explainable assuming that the explainee understands how to navigate its structure (ML background knowledge) and the features are meaningful (domain background knowledge); again, it is up to the explainee to reason about these insights. % When the size of a tree increases, however, its visualisation loses the explanatory power because many explainees become unable to process and reason about its structure. % Restoring the explainability of a deep tree requires delegating the reasoning process to an algorithm that can digest its structure and output sought after insights in a concise representation. % For example, when explaining a prediction, the tree structure can be traversed to identify a similar instance with a different prediction, e.g., as encoded by two neighbouring leaves with a shared parent, thus demystifying the automated decision~\cite{sokol2019desiderata,sokol2021towards}.% While understanding and applying the newly acquired knowledge to unseen tasks are recurring themes in XAI and IML literature~\cite{doshi2017towards,bibal2016interpretability,kim2021multi,biran2017explanation,furnkranz2020cognitive,chen2022machine,rosenfeld2019explainability} -- with a few notable exceptions~\cite{palacio2021xai,yao2021explanatory,langer2021we} -- they rarely ever play the central role. % For example, \citet{palacio2021xai} define an explanation as ``the process of describing one or more facts, such that it facilitates the understanding of aspects related to said facts (by a human consumer)''. % Similarly, \citet{yao2021explanatory} ``highlight[s] one important feature of explanations: they elicit understanding (in humans)''; % \citeauthor{yao2021explanatory} proceeds to suggest that the three levels of analysis proposed by \citet{marr1982vision}, and discussed earlier, should be extended with a \emph{social} level to reflect that AI models, especially the ones of concern to XAI and IML researchers, do not operate in isolation from humans.% Furthermore, some researchers appear to converge towards a similar definition to ours. % \citet{papenmeier2022complicated} characterise transparency as ``the extent to which information is exposed to a system's inner workings'' and interpretability as ``the extent to which transparency is meaningful to a human'', both of which lead them to formalise explanations as ``the mechanisms by which a system communicates information about its inner workings (transparency) to the user''. % In like manner, \citet{roscher2020explainable} posit that ``the scientist is using the data, the transparency of the method, and its interpretation to explain the output results (or the data) using domain knowledge and thereby [\ldots] obtain[s] a scientific outcome'', which process should lead to understanding by presenting properties of ML models in humans-comprehensible terms; % they further suggest that ``explainability usually cannot be achieved purely algorithmically'', which resonates with the role of human \emph{reasoning} in our definition. % Similarly, \citet{langer2021we} identify a ``(given) context'' as the element moderating ``explanatory information'' to facilitate ``stakeholders' understanding'' (of a subset of components present in a complex system). % Additionally, while not explicitly stated, one interpretation of \citeauthor{rosenfeld2019explainability}'s notion of explanations~ \cite{rosenfeld2019explainability} is a collection of human-centred processes that allow explainees to understand a predictive model by presenting them with a suitable representation of its logic (a concept that they call \emph{explicitness}), however based on a graphical representation of their framework explainability is achieved through interpretability, only one component of which is transparency. % Adjacent to XAI and IML, \citet{bohlender2019towards} discussed explanations in software systems, which are meant to ``resolve [a] lack of understanding'' pertaining to a particular aspect (explanandum) of a system for a specific audience and ``the processing of [an] explanation [\ldots] is what makes [an] agent [\ldots] understand the explanandum'' -- an action that may require the use of cognitive or computational resources and that may only be operationalised in specific contexts determined, for example, by the background knowledge of the explainees.% Given the importance of \emph{understanding} in our definition, as well as explainability research outside of XAI and IML~\cite[pages 23, 42, 57]{achinstein1983nature}, it is crucial to review its acquisition and operationalisation together with how it is distinct from and more desirable than not only declarative but also procedural \emph{knowledge}. % For example, consider justifications that can be seen to communicate why a decision is correct without necessarily providing the exact logic behind it~\cite{biran2017explanation}, therefore preventing the explainee from internalising and reapplying these insights to other scenarios. % Similarly, knowledge can be acquired and recalled thus giving the impression of understanding but recitation in itself does not imply comprehension or operationalisation (i.e., an ability to apply it) -- an observation that follows from The Chinese Room Argument~\cite{searle1980minds}. % For example, memorising a textbook or answers to a set of questions may suffice to pass an exam but falls short of effectively resolving related yet distinct problems~\cite{gregor1999explanations}. % This is an important insight for evaluating explainability -- as defined in this paper -- since we first have to specify what it means to attain understanding before we can assess effectiveness of the explanatory process~\cite{paez2019pragmatic}. % Furthermore, internalising knowledge into understanding and correctness thereof are conditioned on the reasoning capabilities and background knowledge of the explainee~\cite{achinstein1983nature,gregor1999explanations}. % The detrimental effects of misalignments in this space were shown by \citet{bell2022its}, who reported that explainability mechanisms pertinent to inherently interpretable models may be confusing, especially so for a lay audience; % for example, ante-hoc transparency of decision trees achieved though a visualisation of their structure misleads people (lacking technical expertise) into believing that the feature used by the root-node split is the most important attribute.% \section{Humans and Explanations -- Two Sides of the Same Coin\label{ch:intro-sec:humans}} Defining explainability as leading to understanding and our categorisation into \emph{properties}, \emph{functions} and \emph{actions} highlight an important aspect of this research topic: explanations do not operate in a vacuum, they are highly contextual and directed at some autonomous agent, either a human or machine, who is as important as the explainability algorithm itself. % Notably, up until recently XAI and IML research has been undertaken mostly within the computer science realm~\cite{miller2017explainable}, thus bringing in various biases and implicit assumptions from this predominantly technical field. % While some explainability research has found its way into other scientific disciplines, e.g., law~\cite{wachter2017counterfactual}, the majority gravitated around technical properties. % This research agenda was disrupted by \citet{miller2017explainable}, who observed that the function of an explanation and its recipients are largely neglected -- a phenomenon which they dubbed ``inmates running the asylum'' -- leading to a substantial paradigm shift. % \citeauthor{miller2019explanation}'s follow-on work~\cite{miller2019explanation} grounded this observation in (human) explainability research from the social sciences, where this topic has been studied for decades, thus providing invaluable insights that can benefit XAI and IML.% \citeauthor{miller2019explanation}'s findings~\cite{miller2019explanation} have arguably reshaped the field, with a substantial proportion of the ensuing research acknowledging the \textbf{explainees} -- their autonomy, goals, expectations, intentions and interactions. % While explainability of data-driven systems has various benefits, it is usually in focus when an AI agent fails, behaves anomalously or operates inconsistently with the explainee's beliefs, expectations or mental model, e.g., an unexpected ML prediction causing a disagreement; alternatively, an explanation may be requested to support learning or provide information needed to solve a problem or complete a task~\cite{gregor1999explanations}. % In such cases, explainees' preferences, needs and goals should be addressed to maximise the effectiveness of an explanation, for example by appropriately adjusting its complexity~\cite{miller2019explanation,gregor1999explanations}. % This step can be further improved by treating explainability as a process instead of one-off information offloading~\cite{miller2019explanation,gregor1999explanations}; by satisfying the explainees' natural desire to \textbf{interact} and communicate with the explainer within a predictable protocol, they are provided with an opportunity to seamlessly customise and personalise the explanation~\cite{sokol2020one}. % Perhaps the most influential of \citeauthor{miller2019explanation}'s observations is the humans' preference for \textbf{contrastive} explanations given their prominence in everyday life. % We discuss these three fundamental aspects of human-centred explainability in more detail below.% Understanding can be an elusive objective when it comes to explaining intelligent systems since each unique \textbf{explanation audience} may expect to receive different insights, e.g., a medical diagnosis can be communicated in terms of test results or observable symptoms depending on whether it is directed towards medical staff or patients. % While in our considerations we implicitly assume that the explanation recipient is a human, it may as well be another algorithm that further processes such insights, in which case other, more suitable, properties would be of interest. % When taken into account, the \emph{purpose} of explainability and the explainee's goal also influence the explanation composition~\cite{gregor1999explanations}. % For example, an explanation will look different when it helps to debug an ML model and when it justifies a negative outcome of a loan application; note that the target audience also differs, with the former aimed at ML engineers and the latter at lay people. % A complementary view, based on a \emph{means-end account} of XAI~\cite{buchholz2022means}, argues to examine ``\emph{what} should be explained (topic), \emph{to whom} something should be explained (stakeholder), \emph{why} something should be explained (goal), and \emph{how} something should be explained (instrument)''. % Addressing such desiderata by accounting for the explainee's cognitive capabilities and skill level, however, is challenging as it requires access to the explainee's background knowledge and mental model, which are vague and often undefined concepts that cannot be easily extracted and modelled.% Nonetheless, just by considering the audience and purpose of an explanation, we can identify (and deliver) a collection of relevant properties. % In certain cases, such as the aforementioned loan application, the \emph{actionability} of explanatory insights is crucial, e.g., suggesting that an individual would receive a loan had he or she been 10 years younger is futile. % Multiplicity of apparently indistinguishable arguments can also decrease the perceived quality of an explanation when one is chosen at random without a user-centred heuristic in place, which, again, depends on the application domain and audience. % For example, research suggests~\cite{miller2019explanation} that if one of multiple, otherwise equivalent, \emph{time}-ordered events has to be chosen as an explanation, the most recent one will best resonate with the explainee; additionally, prioritising explanations by their \emph{novelty} will keep the explainee engaged and attentive, and distinguishing between \emph{sufficient} and \emph{necessary} conditions for a given outcome can help to reduce cognitive load. % While desirable, \emph{brevity} of an explanation can sometimes be at odds with its comprehensiveness and \emph{completeness} -- sacrificing the big picture (which in itself may be too convoluted to understand) for concise communication~\cite{kulesza2015principles}. % Explanatory minimalism, nonetheless, bears the danger of oversimplification; however, when it % is a strict requirement, explanation \emph{soundness} can be favoured to focus on factors pertinent to the explained instance and discard more general reasons that are largely irrelevant. % Such an approach can introduce inaccuracies with respect to the overall data-driven system, but the explanations remain truthful for the individual instance. % Striking the right balance between generality and specificity of an explanation -- as well as achieving all the other aforementioned desiderata -- is notoriously challenging and often requires tuning its soundness and completeness for the intended audience and application, which itself may be impractical when done manually, and prohibitively difficult through capturing the explainee's mental model.% While posing problems for AI explainers, satisfying this wide range of diverse assumptions and expectations comes naturally to humans when they engage in an \textbf{explanatory process} among themselves. % This is partly due to shared background knowledge, and is further amplified by interactive communication that allows to rapidly iterate over questions, exchange informations and refine answers to arrive at understanding. % One explanation does not fit all and treating explainability as a bi-directional process provides a platform to appreciate uniqueness of each explainee through personalised explanations~\cite{sokol2020one} that enable transfer of knowledge and help to develop understanding~\cite{gregor1999explanations}. % While these topics have received relatively little attention in the XAI and IML literature, we can draw design insights and inspirations from research on \emph{explanatory debugging} of predictive models~\cite{kulesza2015principles}. % Therefore, an interactive explanatory process should be \emph{iterative}, enabling the explainee to learn, provide feedback and receive updated insights until reaching a satisfactory conclusion; % the explainer ought to always \emph{honour user-provided feedback} by incorporating it into the explanation generation process, or clearly communicate a precise reason if that is impossible; % the communication should be \emph{reversible} to % allow the explainee to retract a requested change or annul a piece of feedback when it was provided by mistake, or to explore an interesting part of the predictive model through a speculative enquiry; and, finally, % the whole process should be \emph{incremental} to easily attribute each piece of feedback to an explanation change, thereby showing up-to-date results regardless of how small the tweaks are.% Even though dialogue is fundamental to human explainability, it is largely absent in XAI and IML techniques~\cite{sokol2020one}, which are often based on one-way communication, where the user receives a description of a data-driven system without an opportunity to request more details or contest it. % A similar interaction in a form of the aforementioned questioning dialogues can also be used to judge the explainee's understanding of the explained concept, thus be a proxy for assessing effectiveness of the explainer. % Notably, human dialogue tends to be verbal or written, both of which are based on the natural language. % While ubiquitous, this form of communication is not equally effective in conveying all types of information, requiring humans to augment it with visual aids, which are especially helpful when the interaction serves explanatory purposes. % The same strategy can be adopted in explainable AI and interpretable ML, where the explainer would switch between various explanatory artefacts -- such as (written and spoken) text, images, plots, mathematical formulation, numbers and tables -- depending on which one is best suited for the type of information being communicated in a given context~\cite{gregor1999explanations}. % Mixing and matching them is also possible, e.g., a numerical table or a plot complemented with a caption, and may be beneficial as the whole can be greater than the sum of its parts, especially that certain explanation types may require a specific communication medium or explanatory artefact to be effective. % Using visualisation, textualisation and (statistical) summarisation, however, does not guarantee a coherent relation, structure or story conveyed by these communication media alone, which could possibly be achieved by grounding them in a shared context through \emph{logical reasoning} or \emph{formal argumentation}~\cite{dung2009assumption}; % additional inspiration can be found in \emph{sensemaking theory}, which was recently adapted to XAI and IML applications~\cite{kaur2022sensible}.% \textbf{Contrastive explanations} -- more specifically, counterfactuals -- dominate the human explanatory process and are considered the gold standard in explainability of data-driven systems~\cite{miller2019explanation}. % They juxtapose a hypothetical situation (foil) next to the factual account % with the aim to emphasise the consequences of or ``would be'' change in the outcome. % Counterfactuals statements can be characterised by their lineage: \emph{model-driven} explanations are represented by artificial data points (akin to centroids), whereas \emph{data-driven} explanations are instances recovered from a (training) data set (similar to medoids). % Furthermore, the contrast can either be implicit -- i.e., ``Why class \(X\)?'' (hence not any other class) -- or explicit -- i.e., ``Why class \(X\) and not \(Y\)?'' % Counterfactuals are appropriate for lay audiences and domain experts alike, can use concepts of varying difficulty and be expressed in different media such as text and images. % They are parsimonious as the foil tends to be based on a single factor, but, if desired, can account for an arbitrary degree of feature covariance. % They support interaction, customisation and personalisation, e.g., a foil built around a user-selected feature provided in an explanatory dialogue, which can be used to restrict their search space, possibly making them easier to retrieve. % When deployed in a user-centred application, they can provide the explainees with appealing insights by building the foil only around actionable features. % However, their effectiveness may be problematic when explaining a proprietary predictive system, e.g., built as a black box with the intention to protect a trade secret, since counterfactual explanations can leak sensitive information, thereby allowing the explainee to steal or game the underlying model. % In an open world, they also suffer from vaguely defined or imprecise notions known as \emph{non-concepts}~\cite{offert2017know}, e.g., ``What is not-a-dog?''% These idealised properties make counterfactual statements appealing, but some may get lost in practice, e.g., an imperfect implementation, resulting in subpar explanations. % On the face of it, these explanatory artefacts resemble causal insights, but unless they are generated with a causal model~\cite{pearl2016causal}, they should not be treated as such and instead be interpreted as descriptors of a decision boundary used by a predictive system. % If they are model-driven, as opposed to data-driven, they may not necessarily come from the data manifold, yielding (out-of-distribution) explanations that are neither feasible nor actionable in the real life, e.g., ``Had you been 200 years old, \ldots'' % Even if they are consistent with the data distribution, the foil may still come from a sparse region, thus prescribing possible but improbable feature values~\cite{poyiadzi2020face}. % Counterfactual explanations are often specific to a single data point, although humans are known to generalise such insights to unseen and possibly unrelated cases -- recall The Illusion of Explanatory Depth effect~\cite{rozenblit2002misunderstood} -- which may result in overconfidence.% Fulfilling all of these desiderata can help in developing an explainability system that enables the explainees to (better) \emph{understand} an automated decision-making process, which, as we noted earlier, offers a yardstick by which success of such techniques can be quantified~\cite{kim2021multi,paez2019pragmatic,bohlender2019towards,langer2021we}. % To be effective, however, the approach to assess, evaluate and measure understanding has to account for the aforementioned contextual parameters such as the application domain (and its sensitivity), function of the explanation, intended audience (and its background knowledge) as well as (technical) caveats of the XAI or IML algorithm~\cite{arrieta2020explainable,murdoch2019definitions}. % Just like beauty, which is in the eye of the beholder, the (perceived) quality, helpfulness and success of an explanation are judged by the recipient~\cite{kim2021multi}. % Therefore, producing explanations is a necessary but insufficient condition of engendering understanding, which additionally requires them to be relevant to the stakeholders, comprehensible by them and compatible with their desiderata~\cite{langer2021we,gregor1999explanations}, % for example, by aligning the type of insights and their level of transparency towards the chosen use case and audience (in view of the anticipated background knowledge and skills). % Specifically, consider the truthfulness of explanatory information, which may be reduced for a particular purpose without harming the audience's ability to derive understanding; % the simplification used in depicting underground lines and stops is a case in point as it conveys the cues necessary to navigate such a transportation system despite foregoing an accurate representation of scale and distance~\cite{paez2019pragmatic}. % Notably, a transparent representation that is universal and satisfies all the different needs and expectations of diverse explainee groups may not exist, just like an agreement between these individuals on the objective nature of understanding. % Given this strong dependence on human perception, the effectiveness of explanations should be evaluated empirically~\cite{bohlender2019towards} to combat The Illusion of Explanatory Depth~\cite{rozenblit2002misunderstood}, and, in view of The Chinese Room Argument~\cite{searle1980minds}, the studies should go beyond assessing simple task completion to capture the difference between knowledge and understanding within a well-defined, real-life context expected in the deployment.% \section{The Discord over Sacrificing Explainability for Predictive Power\label{sec:tradeoff}}% Theoretical desiderata do not always align with the operationalisation and practicalities of XAI and IML algorithms, and the latter are what ends up affecting our lives. % For example, explainability is an inherently social process that usually involves bi-directional communication, but most implementations -- even the ones using contrastive statements~\cite{wachter2017counterfactual,waa2018contrastive} -- output a single explanation that is optimised according to some predefined metric, not necessarily addressing concerns of an individual explainee~\cite{sokol2020one}. % Similarly, while inherently transparent predictive models and ante-hoc explainers may be preferred~\cite{rudin2019stop}, such solutions are often model-dependent, labour-intensive and tend to be application-specific, which limits their scope as well as wider applicability and adoption. % Instead, post-hoc and model-agnostic explainers dominate the field~\cite{ribeiro2016why,lundberg2017unified,ribeiro2018anchors,sokol2019blimey} since they are considered one-stop solutions -- a unified explainability experience without a cross-domain adaptation overhead. % This silver bullet framework, however, comes at a cost: subpar fidelity that can result in misleading or outright incorrect explanations. % While increasingly such considerations find their way into publications, they are often limited to acknowledging the method's shortcomings, stopping short of offering a % \begin{wrapfigure}[12]{i}{.28\textwidth}% \centering \vspace{-.25\baselineskip} \includegraphics[width=.225\textwidth]{fig/explainability-vs-performance}% \caption{% Fictitious depiction of the anecdotal trade-off between transparency and predictive power of AI systems~\cite{gunning2016broad}.% \label{fig:ch1:tradeoff}% } \end{wrapfigure} viable solution.% A common belief motivating many methods published in the explainability literature is the perceived \emph{dichotomy} between transparency and predictive power of AI and ML systems. % A popular example supporting this theory is the unprecedented effectiveness of deep neural networks on certain tasks, whose ever increasing complexity, e.g., the number of layers % and hidden units, improves their performance at the expense of transparency. % This trade-off has been reiterated in the DARPA XAI program's Broad Agency Announcement~\cite{gunning2016broad} and supported by an appealing graph reproduced in Figure~\ref{fig:ch1:tradeoff}. % However, at the time of publication it has been a \emph{theory} based mostly on anecdotal evidence, with \citet{rudin2019stop} criticising plots like this given their lack of scale, transparency or precise performance metrics, and supporting data. % Notably, \citeauthor{rudin2019stop} argues that investing more effort into feature engineering and data modelling can help to build inherently explainable AI and ML systems that perform on a par with their black-box alternatives~\cite{chen2018interpretable}.% This anecdotal trade-off and a tendency to prioritise predictive power mean that explainability is often only an afterthought. % Such a mindset % contributes to a landscape with an abundance of well-performing but inherently opaque algorithms that are in need of explainability, thus creating a demand for universal explainers that are post-hoc and model-agnostic, such as surrogates~\cite{craven1996extracting,ribeiro2016why,sokol2019blimey}. % This seemingly uncompromising development approach -- where state-of-the-art performance remains the main objective, later complemented with a post-hoc explainer -- offers an attractive alternative (and rebuttal) to designing inherently explainable AI and ML systems, whose creation arguably requires more effort. % While such explainers are compatible with any black-box model, they are not necessarily equally well suited for every one of them~\cite{sokol2020tut} -- after all the computer science folklore of ``no free lunch'' (a single, universal algorithm cannot outperform all the others across the board) applies here as well -- which is reflected in the continuous stream of novel XAI and IML techniques being proposed in the literature, many of whom report competing or contradictory findings (likely because of diverging operational contexts). % Some post-hoc and model-agnostic explainers boast appealing properties and guarantees, however upon closer inspection one often encounters caveats and assumptions required for these to hold, such as the underlying ``black box'' being a linear model~\cite{lundberg2017unified}. % Additionally, making an explainer model-agnostic introduces an extra layer of complexity that usually entails a degree of randomness and decreased fidelity~\cite{zhang2019should,sokol2019blimey}, so that using them may become a stopgap to claim explainability of an inherently opaque predictive system instead of addressing genuine explainability needs. % Correctly interpreting the insights produced by XAI and IML methods may therefore be challenging as it requires a sufficient level of (technical) expertise and alignment with the explainees' background knowledge for the recipients to understand the capabilities and limitations of the explainer, thus avoid drawing incorrect conclusions -- % this is especially relevant to post-hoc and model-agnostic approaches given their higher complexity~\cite{mittelstadt2019explaining,sokol2020limetree,sokol2020towards,sokol2020tut}.% In \citeauthor{rudin2019stop}'s view~\cite{rudin2019stop}, many high-stakes AI and ML systems can be made explainable by design with enough effort put towards data pre-processing, feature engineering and modelling (which otherwise, e.g., for neural networks, may go into architecture search and parameter tuning). % Such ante-hoc explainers are usually domain-specific and after the initial engineering endeavour they are easy to manage and maintain. % While this approach should be championed for structured (tabular) data where it has been shown to perform on a par with state-of-the-art black boxes~\cite{chen2018interpretable}, the same may be unachievable for sensory data such as images and sounds, for which opaque models, e.g., deep neural networks, have the upper hand. % In addition to black boxes modelling sensory data, pre-existing, inaccessible or legacy predictive systems may require interpretability, in which case they can only be retrofitted with post-hoc explainers. % Such techniques are also helpful to engineers and developers working with predictive models since they enable inspection and debugging of data-driven systems. % However, falling back on off-the-shelf solutions may not guarantee acceptable fidelity~\cite{sokol2019blimey,sokol2020limetree,sokol2020tut} (specifically, soundness and completeness), which is of particular importance and may require tailor-made explainers and transparent communication of their limitations.% While composing a predictive pipeline, we have an abundance of pre-processing as well as modelling tools and techniques at our disposal, a selection of which will end up in the final system. % The XAI and IML landscape, on the other hand, is quite different, especially for post-hoc and model-agnostic approaches: explainers tend to be end-to-end tools with only a handful of parameters exposed to the user. % In view of ``no free lunch'', this is undesirable as despite being model-agnostic, i.e., compatible with any model type, these monolithic algorithms cannot perform equally well for every one of them~\cite{sokol2019blimey,sokol2020tut}. % This variability in their behaviour can often be attributed to a misalignment between the assumptions baked into an explainer and the properties of the explained system, which manifests itself in low fidelity.% Model-specific or ante-hoc explainers as advocated by \citet{rudin2019stop} can be used to address this issue; % however, as discussed earlier, such a solution may have limited applicability and cannot be retrofitted to pre-existing predictive systems. % Resolving a similar challenge in machine learning and data mining often comes down to a series of investigative steps to guide algorithmic choices down the line, which can be operationalised within a standardised process for knowledge discovery such as KDD~\cite{fayyad1996data}, CRISP-DM~\cite{chapman2000crisp,martinez2019crisp} or BigData~\cite{agrawal2012challenges}. % For example, by analysing feature correlation, data uniformity and class imbalance, we can account for these phenomena when engineering features and training models, thereby making the resulting systems more accountable and robust. % Nonetheless, while we may have a set of universal properties expected of XAI and IML systems~\cite{sokol2020explainability}, we lack a dedicated process that could guide the development and assessment of explainers -- their practical requirements and needs -- which likely hinders adherence to best practice. % Although one can imagine a generic workflow for designing inherently interpretable (ante-hoc) systems~\cite{rudin2019stop}, a similar endeavour should not be neglected for model-agnostic and post-hoc explainers that could be adapted to individual predictive black boxes by capitalising on their flexibility and modularity~\cite{sokol2019blimey}, possibly overcoming low fidelity~\cite{sokol2020limetree}.% More recently, in response to \citeauthor{rudin2019stop}'s call to action~\cite{rudin2019stop}, the disputed trade-off between \emph{transparency} and \emph{predictive power} has been revisited with a greater scientific rigour~\cite{herm2021don,bell2022its}. % \citet{herm2021don} used explainability as a tool to aid people in problem-solving, investigating it under the aforementioned two dimensions complemented with \emph{comprehensibility}, which should be a direct consequence of a model being recognised as explainable. % Their preliminary findings are somewhat at odds with \citeauthor{rudin2019stop}'s postulate, especially so for high-stakes scenarios for which the user studies suggest that an artificial neural network enhanced with SHAP explanations boasts high predictive performance and is also perceived as explainable. % Similarly, \citet{bell2022its} performed empirical quantification of this trade-off in two public policy domains and found that (inherently) interpretable models may not necessarily be more explainable than black boxes. % The results of their experiments show that even opaque models may be recognised as explainable -- nonetheless, the authors emphasise the importance of ante-hoc explainability in mission-critical domains -- hinting that the trade-off may be more nuanced than acknowledged in the literature. % Notably, while the explainee's perception may suggest that black boxes accompanied by post-hoc explainers are up to the task, the fidelity, correctness and veracity of such insights remain contestable, especially in view of the recipient's susceptibility to be convinced by sheer presence of ``explanations'' that themselves may not necessarily be truthful~\cite{herman2017promise} or meaningful (as famously shown by The Copy Machine study~\cite{langer1978mindlessness}). % With just a few such inquiries available, the topic requires further investigation to offer a clear view on the possible trade-off between transparency and predictive power in XAI and IML. % We postulate that -- in accordance with our definition -- particular focus should be put on the \emph{reasoning} employed by explainees to extract meaning and create understanding based on transparent insights into black boxes given that a misconception of how to interpret them may result in a false sense of explainability~\cite{mittelstadt2019explaining}.% A distinct viewpoint on this matter manifests itself in % claims that we should not expect machine learning algorithms, such as deep neural networks, to be explainable and instead regulate them purely based on their real-life performance~\cite{simonite2019google} and behaviour~\cite[minute 29]{norvig2017google}, however it is not a widely shared belief~\cite{jones2018geoff}. % This insight comes from the alleged inability of humans to explain their actions since such justifications are post-factum stories that are concocted and retrofitted for the benefit of the audience. % Certifying autonomous agents based on their output, on the other hand, is consistent with human values as one can hypothesise about committing a crime, but one cannot be punished unless such a thought is acted upon. % While the origin and nature of human thought processes may be shrouded in mystery, its formulation is expected to follow the reason of logic to be (socially) acceptable. % In particular, \citet{miller2019but} refutes performance-based validation by arguing that explainability stemming from regulatory requirements is secondary to concerns arising from societal values such as ethics and trust. % Importantly, making data-driven systems understandable can instil confidence into the public as it allows the creators of such technologies to justify, control and improve them as well as lead to new discoveries~\cite{adadi2018peeking}. % An appropriate and comprehensive explainability solution can also become a technological springboard to reducing or eliminating bias~\cite{saxena2019perceptions,saxena2019fairness}, unfairness~\cite{buolamwini2018gender,olteanu2019social,kusner2017counterfactual} and lack of accountability (to the benefit of robustness~\cite{ackerman2019three,goodfellow2015explaining}, safety~\cite{angwin2016machine,grzywaczewski2017training} and security) from data-driven predictive models, thus improving their trustworthiness~\cite{sokol2019fairness}.% \begin{figure}[!t] \centering \includegraphics[trim={6pt 87pt 6pt 87pt},clip,width=.65\textwidth]{fig/elephant}% \caption{% Depiction of The Blind Men and the Elephant parable~\cite{saxe2016blind} illustrating that any complex subject can be studied in many ways. % It also symbolises that individual pieces of evidence may often be contradictory and insufficient to understand the bigger picture without first being aggregated and grounded within a shared context.\label{fig:ch1:elephant}}% \end{figure} \section{Explanation Diversity and Multiplicity -- What to Explain and How to Explain It\label{sec:elephant}} So far we have primarily focused on explaining predictions and actions of intelligent systems since they are observable and can be related to by a wide range of explainees regardless of their background. % However, automated \textbf{predictions} are just artefacts of a more elaborate % artificial intelligence or machine learning predictive process, which manipulates \textbf{data} to infer \textbf{models} that generalise well, thus are capable of predicting (previously unseen) instances~\cite{flach2012machine}. % Since any element of this workflow can be opaque~\cite{sokol2017role,sokol2017roleARW}, % comprehensive explanations may need to consist of insights pertaining to the entire predictive pipeline, discussing diverse topics such as data collection and (pre-)processing, modelling caveats and assumptions, and the meaning and interpretation of predictions, % all of which can be % bundled together in a shared user interface to provide a multi-faceted view of the investigated system~\cite{krause2016interacting,krause2016using,weld2019challenge}.% Additionally, as each explanation may provide just a small, and quite possibly distorted, reflection of the true behaviour of a data-driven model, achieving the desired level of transparency (and understanding) might require communicating multiple, complementary insights for each unintelligible step or observation, which in turn bears the danger of overwhelming and confusing the explainee. % This multitude of explanatory information has to be navigated carefully and can be understood as unique probing and inspection techniques that without a shared context may yield competing or even contradictory evidence akin to the parable of The Blind Men and the Elephant~\cite{saxe2016blind} % illustrated in Figure~\ref{fig:ch1:elephant}. % Note that this phenomenon is not unique to explainability; % multiplicity of data-driven models all of whom exhibit comparable predictive performance despite intrinsic differences, sometimes called the Rashomon effect of statistics, is well documented~\cite{breiman2001statistical,marx2020predictive,fisher2019all,sokol2022ethical}. % Furthermore, as AI and ML processes are directional -- from data, through models, to predictions -- the latter components depend on the former, which also applies to their respective explanations. % For example, if data attributes are incomprehensible, explanations of models and predictions expressed in terms of these features will also be opaque.% \textbf{Explaining data} may be challenging without any modelling assumptions, hence % there may not necessarily exist a pure data explanation method beyond simple \emph{summary statistics} (e.g., class ratio or per-class feature distribution) and \emph{descriptors} (e.g., ``the classes are balanced'', ``the data are bimodal'' or ``these features are highly correlated''). % Note that the former simply state well-defined properties and may not be considered explanations, whereas the latter can be contrastive and lead to understanding. % Importantly, data are already a model -- they express a (subjective and partial) view of a phenomenon and come with certain assumptions, measurement errors or even embedded cultural biases (e.g., ``How much is a lot?''). % Data statements~\cite{bender2018data}, data sheets~\cite{gebru2018datasheets} and nutrition labels~\cite{holland2018dataset} attempt to address such concerns by capturing these (often implicit) assumptions. % As a form of data explanations, they characterise important aspects of data and their collection process in a coherent format, e.g., experimental setup, collection methodology (by whom and for what purpose), pre-processing (cleaning and aggregation), privacy aspects, data ownership, and so on.% \textbf{Explaining models} % in whole or in parts (e.g., specific sub-spaces or cohorts) % should engender a general, truthful and accurate understanding of their functioning. % While some predictive systems may be inherently transparent, e.g., shallow decision trees, their simulatability~\cite{lipton2016mythos} -- the explainee's ability to simulate their decision process mentally \emph{in vivo} -- may not produce understanding (see Section~\ref{sec:bbnes}). % Popular model explanations include feature importance~\cite{breiman2001random,fisher2019all}, feature influence on predictions~\cite{friedman2001greedy}, presenting the model in cognitively-digestible portions~\cite{krause2016using,smilkov2016embedding} and model simplification~\cite{craven1996extracting} (e.g., mimicking its behaviour or a global surrogate). % Since not all models operate directly on the input features, an \emph{interpretable representation} may be necessary to convey an explanation, e.g., a super-pixel segmentation of an image~\cite{ribeiro2016why}; alternatively, if the data are comprehensible, landmark exemplars can be used to explain the behaviour of a model or its parts~\cite{kim2014bayesian,kim2016examples}.% \begin{wrapfigure}[15]{i}{.43\textwidth}% \centering \vspace{-.5\baselineskip} \includegraphics[width=.4\textwidth]{fig/ice-pd_cropped}% \caption{% Explanation of a model predicting the probability of the \emph{versicolor} class when varying the \emph{petal length} attribute for the Iris data set~\cite{fisher1936use}. % Individual Conditional Expectation of a selected instance is plotted in red; % the orange curve is the Partial Dependence of the model computed by averaging all individual ICEs (displayed in grey).% \label{fig:ch1:ice-pd}}% \end{wrapfigure} \textbf{Predictions} are explained to communicate a rationale behind a particular decision of a model. % Depending on the explanation type, a range of diverse aspects concerning the model's decisive process can be provided to the explainee. % For example, the user may be interested in feature importance~\cite{ribeiro2016why}, feature influence~\cite{lundberg2017unified}, relevant data examples~\cite{kim2015ibcm} and training instances~\cite{koh2017understanding}, or contrastive statements~\cite{wachter2017counterfactual,poyiadzi2020face}, to name a few. % Note that while some of these explanation types are similar to model explanations, here they are explicitly generated with respect to a single data point and may not necessarily generalise beyond this particular case, whereas for model explanations they convey similar information for all data (i.e., the entire modelled space). % A good example of this duality is information communicated by Individual Conditional Expectation (ICE~\cite{goldstein2015peeking}) and Partial Dependence (PD~\cite{friedman2001greedy}), both of which are feature influence explanations -- the first with respect to a single data point and the latter concerning a model -- as shown in Figure~\ref{fig:ch1:ice-pd}. % Akin to model explanations, the information can be conveyed in the raw feature space or using an interpretable representation.% With such a diverse range (and possibly large quantity) of explanations, their presentation requirements -- \textbf{content}, \textbf{delivery format}, \textbf{communication medium} and \textbf{provision protocol} or \textbf{mechanism}~\cite{sokol2020explainability,gregor1999explanations} -- will naturally vary~\cite{sokol2017role,sokol2017roleARW}. % A simple approach to characterise an AI component is (statistical) \emph{summarisation} -- it is commonly used for describing properties of data with numerical tables and vectors, which can be difficult to digest for non-experts. % \emph{Visualisation} -- a graphical representation of a phenomenon -- is a more advanced, insightful and flexible analytical tool. % Static figures communicate information in one direction, akin to summarisation; however, creating interactive plots can facilitate a ``dialogue'' with an explainee, thereby catering to a more diverse audience. % Visualisations are often supported by short narratives in the form of captions, which increase their informativeness. % \emph{Textualisation} -- a natural language description of a phenomenon -- can express concepts of higher complexity and dimensionality than plots, which can help to overcome the curse of dimensionality and the inherent limitations of the human visual system. % Communicating with text enables a true dialogue and has been shown to be more insightful and effective than presenting raw, numerical and visual data~\cite{portet2009automatic}, which can accompany the narrative to improve its expressiveness. % A further refinement of textualisation is formal \emph{argumentation}~\cite{dung2009assumption} -- a structured and logically-coherent dialogue accounting for every disputable statement and giving the explainee an opportunity to contest the narrative, thus providing explanations leading to understanding rather than informative descriptions. % Finally, such explanatory processes can either be triggered automatically, invoked (and driven) by the users or offered contextually whenever a need for a clarification is detected by the explainer~\cite{gregor1999explanations}.% Thus far we have been mainly concerned with AI and ML explainability on a relatively abstract level, all of which constitute just a small portion of XAI and IML research. % In an ideal world, relevant publications would consider many of the aforementioned factors and build their mechanisms around them, however it has only recently become a trend and numerous early pieces of work lack such a reflection. % To complement the viewpoint presented in the preceding sections and bridge the \emph{theoretical} (foundational and social) and \emph{technical} (algorithmic and engineering) aspects of explainers we briefly traverse through \textbf{practical explainability research}. % Without aiming to be exhaustive -- given the availability of several comprehensive surveys~\cite{guidotti2018survey,linardatos2021explainable} -- we finish this section by identifying a number of landmark contributions that have influenced the entire research field. % We also omit topics adjacent to explainability, such as interactive exploratory user interfaces~\cite{wexler2017facets,tensorboard}, creative visualisations of explainability approaches~\cite{krause2016interacting} and systems combining multiple explainability techniques within a single tool~\cite{weld2019challenge}.% The most popular explainers are \emph{model-agnostic} and \emph{post-hoc} as they can be retrofitted into any predictive system (at the expense of adding a modelling layer that may negatively impact explanation fidelity). % These include RuleFit~\cite{friedman2008predictive}, Local Interpretable Model-agnostic Explanations (LIME~\cite{ribeiro2016why}), anchors~\cite{ribeiro2018anchors}, SHapley Additive exPlanations (SHAP~\cite{lundberg2017unified}), Black-box Explanations through Transparent Approximations (BETA~\cite{lakkaraju2016interpretable,lakkaraju2017approximations}), PD~\cite{friedman2001greedy}, ICE~\cite{goldstein2015peeking} and Permutation Importance (PI~\cite{breiman2001random}), among many others. % Most of these methods operate directly on raw data, with the exception of LIME and anchors, which use interpretable representations to improve intelligibility of explanations composed for complex data domains such as text and images. % Another attractive avenue of explainability research, which partly overlaps with post-hoc methods, is opening up (deep) neural networks by designing tools and techniques \emph{specific to these approaches} or, more broadly, compatible with differentiable predictors. % These models are notoriously opaque, however their superior predictive performance for a wide spectrum of applications increases their popularity and accelerates their proliferation~\cite{lecun2015deep}. % Relevant explainability techniques include global surrogates~\cite{craven1996extracting}, saliency maps~\cite{zintgraf2017visualizing}, influential training instances~\cite{koh2017understanding}, counterfactuals~\cite{wachter2017counterfactual} (which are surprisingly similar to the problematic adversarial examples~\cite{goodfellow2015explaining}), and influential high-level, human-intelligible insights based on Testing with Concept Activation Vectors (TCAV~\cite{kim2018interpretability}). % An alternative XAI and IML research agenda concentrates on \emph{inherently explainable} predictive models, and \emph{ante-hoc} explainers designed for popular data-driven systems. % Examples of the former are generalised additive models~\cite{lou2013accurate} and falling rule list~\cite{wang2015falling}; whereas the latter include global and local explanations of na\"ive Bayes classifiers~\cite{kulesza2015principles}, and clustering insights based on prominent exemplars and dominating features~\cite{kim2014bayesian}.% \section{Towards Understanding Facilitated Through Intelligible and Robust Explainers\label{sec:summary}}% In this paper we explored the relatively recent and still evolving domains of artificial intelligence explainability and machine learning interpretability. % We introduced the main topics and provided the philosophical, theoretical and technical background needed to appreciate the depth and complexity of this research. % In particular, we highlighted two different mental models: \emph{functional} -- enough understanding to operationalise a concept; and \emph{structural} -- in-depth, theoretical appreciation of underlying processes. % We further argued that the former -- a shallow form of understanding -- aligns with The Chinese Room Argument~\cite{searle1980minds,penrose1989emperor} and the notion of simulatability~\cite{lipton2016mythos}. % We also reviewed diverse notions of explainability, interpretability, transparency, intelligibility and many other terms that are often used interchangeably in the literature, and argued in favour of \emph{explainability}. % We defined this concept as (logical) \emph{reasoning} applied to transparent XAI and IML insights interpreted under specific \emph{background knowledge} within a given context -- a process that engenders \emph{understanding} in explainees. % We used these observations to challenge the popular view that decision trees are explainable just because they are transparent. % Deep or wide trees lack interpretability, which can be restored by applying a suitable form of logical reasoning -- a prerequisite of explainability -- undertaken by either an algorithm or a human investigator.% While the most visible aspect of XAI and IML research is the technology that enables it, explainees -- the recipients of such explanations who tend to be humans -- are just as important (and ought to be treated as first-class citizens) since their \emph{understanding} of the underlying predictive system and its behaviour determines the ultimate success of an explainer. % We explored this topic by looking at human-centred explainability and various desiderata that this concept entails, in particular focusing on explicitly acknowledging presence of humans and projecting the explanations directly at them. % To this end, we pursued important insights from the social sciences that prescribe how to adapt machine explainability to fulfil expectations of the explainees, hence achieve seamless explanatory interaction. % The two crucial observations in this space are: (i) a preference for (meaningful) \emph{contrastive} explanations, which form the cornerstone of human-centred explainability; and (ii) facilitating an interactive, dialogue-like, bi-directional explanatory \emph{process} -- akin to a conversation -- as opposed to delivering a one-off ``take it or leave it'' explanation % to ensure coherence with people's expectations regardless of their background knowledge and prior experience with this sort of technology. % Notably, the explanation type and delivery medium should also be adapted to the circumstances. % This is particularly important when the audience is diverse as one predefined type of an explanation may be insufficient since it is unlikely to address all the possible concerns, questions and unique perspectives. % An XAI or IML explainer that communicates through contrastive explanations and provides the explainees with an opportunity to interactively customise and personalise them~\cite{madumal2019grounded} -- offering a chance to contest and rebut them in case of a disagreement -- should therefore be considered the gold standard~\cite{wachter2017counterfactual,miller2019explanation}.% In addition to enhancing explainee satisfaction, operating within this purview has other, far-reaching benefits such as enabling algorithmic fairness evaluation, accountability assessment and debugging of predictive models. % It is also compatible with all the elements of the artificial intelligence or machine learning workflow -- which consists of data, models and predictions -- as each of these components may be in need of interpretability. % In view of a variety of explainability approaches, each operating in a unique way, we also looked at the disputed trade-off between explainability and predictive power, the existence of which has mostly been supported by anecdotal evidence thus far, albeit recent studies show that this dependency may be more nuanced than previously expected. % We then connected this debate to the distinction between inherent (ante-hoc) and retrofitted (post-hoc) explainability: the former provides explanations of superior quality but requires extensive engineering effort to be built, whereas the latter is flexible and universal at the expense of fidelity. % While the former may be shunned due to the required work, we argued that building trustworthy post-hoc explainers may be just as complicated and demand just as much commitment since these seemingly easy to use tools % conceal a complex process governing their composition and influencing their quality behind the facade of universality~\cite{sokol2019blimey,sokol2020limetree,sokol2020towards,sokol2020tut}. % This considerable effort required to set them up, therefore, illuminates a crucial question: Is it better to spend time and effort on configuring post-hoc explainers or instead invest these resources into building inherently explainable predictive models? % Unsurprisingly, there is no definitive answer given the uniqueness of each individual case, e.g., legacy systems and predictors built from scratch.% Regardless of the particular implementation and operationalisation details, explainers of automated decision-making systems should adopt and embody as many of these findings as possible to engender trust in data-driven predictive models. % Since each explanation reveals just a fragment of the modelling process and only the right mixture of evidence can paint the full picture, XAI and IML approaches need to be responsive and adapt seamlessly to the users' requests and expectations. % Such an engaging algorithmic interlocutor should build logically consistent narratives and serve more as a guide and a teacher than a facts reporter. % To this end, we need to develop an explanatory process built on top of a system that enables logical reasoning between intelligent agents: human--machine or machine--machine. % An appropriate foundation -- managing the dialogue as well as tracking and storing the evolving knowledge base of the involved parties -- should benefit and encourage an interdisciplinary research agenda drawing from multiple areas of computer and social sciences. % In the end, nonetheless, the explainee needs to be a savvy interrogator, asking the right questions and firmly navigating the entire process to understand the behaviour of such data-driven oracles. % After all, in Arthur C.\ Clarke's words: % ``Any sufficiently advanced technology is indistinguishable from magic.'' % While this view may partially reflect a broader perception of artificial intelligence and machine learning applications, the work presented here reconciles XAI and IML research published to date to establish a solid foundation for addressing open questions in an effort to demystify predictive algorithms and harness their full potential. % The logical next step in this pursuit is development of a comprehensive framework, flexible protocol and suite of (quantitative \& qualitative) metrics to meaningfully evaluate the quality and effectiveness of explainable AI and interpretable ML techniques, allowing us to choose the best possible solution for each unique problem.% \renewcommand{\acksname}{Acknowledgements} \begin{acks} This research was partially supported by % the TAILOR project, funded by EU Horizon 2020 research and innovation programme under GA No 952215; and % the ARC Centre of Excellence for Automated Decision-Making and Society, funded by the Australian Government through the Australian Research Council (project number CE200100005).% \end{acks} \section*{Author Contributions} Conceptualisation, K.S.; Methodology, K.S.; Investigation, K.S.; Writing -- Original Draft, K.S.; Writing -- Review \& Editing, K.S.\ and P.F.; Supervision, P.F.; Funding Acquisition, P.F.% \section*{Declaration of Interests} The authors declare no competing interests.% \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2022-09-12T02:05:29', 'yymm': '2112', 'arxiv_id': '2112.14466', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14466'}
arxiv
\section*{Abstract} We reexamine the the classical multidimensional scaling (MDS). We study some special cases, in particular, the exact solution for the sub-space formed by the 3 dimensional principal coordinates is derived. Also we give the extreme case when the points are collinear. Some insight into the effect on the MDS solution of the excluded eigenvalues (could be both positive as well as negative) of the doubly centered matrix is provided. As an illustration, we work through an example to understand the distortion in the MDS construction with positive and negative eigenvalues. \section{Basics of the classical MDS} We recall in this section some basics of the classical MDS from Mardia et al (1979, Section 14.2). Let us denote the $n\times n$ distance matrix as $\bD =(d_{ij})$ and form the matrix $\bA$ \begin{align} \bA = \{a_{ij}\}, a_{ij} &= -\frac{1}{2}d_{ij}^2, \end{align} and define the corresponding doubly centered matrix $\bB$, \beq \bB = \bH\bA\bH, \eeq where $\bH = \mathbf{I_n}-\frac{\vect{1}_n \vect{1}_n^T}{n}$ is the centering matrix in the standard notation. We can rewrite $\bB$ as \beq \bB = \bX\bX^T, \eeq and the $n \times n$ matrix $\bX$ of the principal coordinates in the Euclidean space (assuming that $\bB$ is semi-positive) is given by \beq \label{X} \bX =\mathbf{\Gamma}\mathbf{\Lambda}^{\half}=({\lambda_1}^{\frac{1}{2}}{\gamma_1},{\lambda_2}^{\frac{1}{2}}{\gamma_2}\ldots, {\lambda_n}^{\frac{1}{2}}{\gamma_n})= (\vect{x}_{(1)},\vect{x}_{(2)}, \ldots, \vect{x}_{(n)}), \eeq where $$\vect{x}_{(i)}={\lambda_i}^{\frac{1}{2}}{\vect{\gamma}_i}, i=1,\ldots,n ,$$ with the spectral decomposition of $\bB$ \beq \label{Bspectral} \bB = \mathbf{\Gamma} \mathbf{\Lambda} \mathbf{\Gamma}^T, \eeq and $$\mathbf{\Gamma}= \{\gamma_{ij}\}=(\vect{\gamma}_1,\ldots, \vect{\gamma}_n)$$ is the orthogonal matrix of eigenvectors and $\mathbf{\Lambda}$ is the diagonal matrix of eigenvalues, $$\mathbf{\Lambda} = \text{Diag}\{\lambda_{1},\ldots,\lambda_{n} \}.$$ Indeed, the $n$ principal coordinates $\vect{x}_i, i=1,2, \ldots,n $ are the rows of $\bX$, namely, \beq \label{Xcoord} \bX= \begin{pmatrix} \vect{x}^T_1 \\ \vect{x}^T_2 \\ \vdots \\ \vect{x}^T_n \end{pmatrix} , \vect{x}_i^T=({\lambda_1}^{\frac{1}{2}}{\gamma}_{i1},\ldots,{\lambda_n}^{\frac{1}{2}}{\gamma}_{in}), i=1,\ldots, n. \eeq We can use any ``subpart" of $\bX$ to define the principal coordinates of a low dimensional space as our MDS solution. Note that the last eigenvalue $\lambda_{n}$ is zero so at least $\vect{x}_{(n)}=0$ so we can work on the remaining $n-1$ dimensional coordinates. Note that, for simplicity, we have taken $\bX$ as the $n \times n$ matrix rather than $n \times p$ matrix. We now show that, for any dissimilarity matrix $\bD$ with real entries but not necessarily semi-positive definite $\bB$ as in above, $\lambda_1$ will be always positive. We have $$ tr(\bB) = tr (\bH^2\bA)=tr (\bH\bA)= tr (\bA)-tr(\vect{1}^T \bA \vect{1})/n$$ so that \beq \label{tr} \sum_{i=1}^{n} \lambda_i = \sum_{i<j}d_{i,j}^2/n >0. \eeq Hence $\lambda_1>0$. Thus implying that we can always "fit" one-dimensional configuration for any distance/ dissimilarity matrix. Let us now consider the case when the n points lie on a line then we will have only one non-zero eigenvalue $\lambda$ of $\bB$ so from \eqref{tr}, it is given by $$\lambda = \sum_{i<j}d_{i,j}^2/n. $$ \begin{itemize} \item For n=3 with points on the line with the inter-point distances as $a,b,c$, we have $\lambda =(a^2+b^2+c^2)/3,$ where if $AB=a, BC=b,AC=c$ with the points $A,B,C$ in that order then $a+b=c.$ \item If the points are $1,2,\ldots,n$ then we find that $\lambda = n(n^2-1)/12$ so with the distances scaled to (0,1), we have $\lambda$ = $n(n^2-1)/12(n-1)^2$ and $\lambda$=O(n). \end{itemize} \section{The MDS solution for $2 \times 2$ distance matrix} Let $X=(\vect{x}_{(1)},\vect{x}_{(2)})$ where $\vect{x}_k,k=1,2$ are the coordinates in 2 dimensions. Suppose the two points are separated by a distance $d$. We have \begin{align} D = \begin{pmatrix} 0 & d \\ d & 0 \end{pmatrix} , \hspace{3pt} B = \begin{pmatrix} \frac{d^{2}}{4} & \frac{-d^{2}}{4} \\ \frac{-d^{2}}{4} & \frac{d^{2}}{4} \end{pmatrix}. \nn \intertext{The eigenvalues of $\bB$ are given by} |\bB-\lambda\bI_{2}| &= \lambda^{2}-2 \lambda \frac{d^{2}}{4}. \label{DecompersionTwo} \intertext{Solving \eqref{DecompersionTwo} gives the eigenvalues} \lambda_{1} = \frac{d^{2}}{2} \ &\text{and} \ \lambda_{2} = 0, \nn & \nn \intertext{with the corresponding eigenvectors } \vect{\gamma}_{1} = \left(\frac{1}{\sqrt{2}}, \frac{-1}{\sqrt{2}}\right)^{T} \ &\text{and} \ \vect{\gamma}_{2} = \left(\frac{1}{\sqrt{2}}, \frac{1}{\sqrt{2}}\right)^{T}. \nn \intertext{Now using \hspace{3pt}$\vect{x}_{(k)}=\lambda_{k}^{\frac{1}{2}}\vect{\gamma}_{k}$ from \eqref{X}, and we get for $\bX $} \vect{x}_{(1)} = \left(\frac{d}{2}, \frac{-d}{2}\right)^{T} \hspace{3pt} &\text{and} \hspace{3pt} \vect{x}_{(2)} = \left(0,0 \right)^{T} \label{TwoSol}. \end{align} So the principal coordinates from \eqref{Xcoord} are \beq \label{coord2D} \vect{x}_1 = \left(\frac{d}{2}, 0\right)^{T} \hspace{3pt} \text{and} \hspace{3pt} \vect{x}_2 = \left(-\frac{d}{2},0 \right)^{T}. \eeq To get a lower dimensional coordinate space (one dimensional), we can simply use, along the line ( $x$- axis), the following two points: $$x_1=\frac{d}{2},\quad x_2=-\frac{d}{2}.$$ We can now shift $x $ conveniently by using $ x^*$ = $ x +\frac{d}{2} $ so we have the new coordinates $$x^*_1=d,\quad x^*_2=0 $$ along the $x^*$- axis in one dimension with the origin at $x^*_2$. The solution \eqref{coord2D} is trivial as the points only require placing a distance $d$ apart to be recovered, although it does serve as a pointer for the $3 \times 3$ distance matrix in the next section. \section{The MDS solution for $3 \times 3$ distance matrix} We now extend the last section of the $2 \times 2$ distance matrix to the $3 \times 3$ distance matrix where in principle, we need to follow the same steps. Let now $\bX=(\vect{x}_{(1)},\vect{x}_{(2)},\vect{x}_{(3)})$, where $\vect{x}_k, k=1,2,3$ give the coordinates of points in three dimensions . Let \begin{align} \bD &= \begin{pmatrix} 0 & a & b \\ a & 0 & c \\ b & c & 0 \end{pmatrix}.\\ \text{Then it can be seen that} \nn \\ \bB & = \frac{1}{18} \begin{pmatrix} 4a^2+4b^2-2c^2 & -5a^2+b^2+c^2 & a^2-5b^2+c^2 \\ -5a^2+b^2+c^2 & 4a^2-2b^2+4c^2 & a^2+b^2-5c^2 \\ a^2-5b^2+c^2 & a^2+b^2-5c^2 & -2a^2+4b^2+4c^2 \end{pmatrix}. \nn \intertext{and} |\bB-\lambda\bI_{3}| &= \left(\frac{-1}{6}(a^{2}b^{2}+a^{2}c^{2}+b^{2}c^{2}) +\frac{1}{12}(a^{4}+b^{4}+c^{4})\right)\lambda \nn \\ & \quad \quad +\frac{1}{3}(a^{2}+b^{2}+c^{2})\lambda^{2}-\lambda^{3}. \label{DecompersionThree}\\ \intertext{Let} \Delta&=\sqrt{a^{4}+b^{4}+c^{4}-a^{2}b^{2}-a^{2}c^{2}-b^{2}c^{2}} \label{Delta}.\\ \intertext{Solving \eqref{DecompersionThree} we find that the eigenvalues are } \lambda_1 &=\frac{1}{6}(a^{2}+b^{2}+c^{2} +2\Delta ), \nn \\ \lambda_2 &=\frac{1}{6}(a^{2}+b^{2}+c^{2} -2\Delta ), \nn \\ \text{and} \ \lambda_3 &=0. \label{EigenvaluesThree} \intertext{We show below in the proof of Theorem 1 that $\Delta$ is always non-negative. To find the corresponding eigenvectors, $\bB$ is rotated using a Helmert rotation matrix $\bR$} \bR &= \begin{pmatrix} \frac{1}{\sqrt{3}} & \frac{1}{\sqrt{3}} & \frac{1}{\sqrt{3}} \\ \frac{-1}{\sqrt{2}} & 0 & \frac{1}{\sqrt{2}} \\ \frac{1}{\sqrt{6}} & \frac{-2}{\sqrt{6}} & \frac{1}{\sqrt{6}} \end{pmatrix}. \nn \\ \intertext{That is} \bR\bB\bR^{T} &= \begin{pmatrix} 0 & 0 & 0 \\ 0 & \frac{b^2}{2} & \frac{(-a^2+c^2)}{2\sqrt{3}} \\ 0 & \frac{(-a^2+c^2)}{2\sqrt{3}} & \frac{(2a^2 - b^2 +2c^2)}{6} \end{pmatrix} =\begin{pmatrix} 0 & 0 & 0 \\ 0 & \sigma^{2}_{1,1} & \sigma^{2}_{1,2} \\ 0 & \sigma^{2}_{1,2} & \sigma^{2}_{2,2} \end{pmatrix} \label{NullMat1} \end{align} which has a $2 \times 2$ symmetric matrix nested within a $3 \times 3$ null matrix. We first give the eigenvectors of $\bR^{T}\bB\bR$ by using a result of Mardia et al (1979, page 246, Exercise 8.1.1) , \begin{align} \vect{\phi}_1 &= \begin{pmatrix} 0 \\ \sigma^{2}_{2,2}-\sigma^{2}_{1,1}+\Theta \\ -2\sigma^{2}_{1,2} \end{pmatrix} \hspace{3pt} \text{and} \hspace{3pt} \vect{\phi}_2 = \begin{pmatrix} 0 \\ 2\sigma^{2}_{1,2} \\ \sigma^{2}_{2,2}-\sigma^{2}_{1,1}+\Theta \end{pmatrix} \label{NullMatVect} \intertext{where $\Theta = \sqrt{(\sigma^{2}_{1,1}-\sigma^{2}_{2,2})^{2}+4\sigma^4_{1,2}}$. Next, the rotation is reversed by pre-multiplying the {\bf unnormalized} eigenvectors \eqref{NullMatVect} by $\bR$ to deduce the eigenvectors of $\bB$} \vect{\gamma}_{1} &= \begin{pmatrix} b^{2}-c^{2}+\Delta \\ -a^{2}+c^{2} \\ a^{2}-b^{2}-\Delta \end{pmatrix},\ \vect{\gamma}_{2} = \begin{pmatrix} 2a^{2}-b^{2}-c^{2}-\Delta \\ -a^{2}+2b^{2}-c^{2}+2\Delta \\ -a^{2}-b^{2}+2c^{2}-\Delta \end{pmatrix} , \ \vect{\gamma}_{3} = \begin{pmatrix} 1 \\ 1 \\ 1 \end{pmatrix} \label{EigenvectorsThree} \intertext{ where $\Delta$ is given by \eqref{Delta}. Now using \hspace{3pt}$\vect{x}_{(k)}=\lambda_{k}^{\frac{1}{2}}\vect{\gamma}_{k}$ from \eqref{X}, and we get for $\bX $} \vect{x}_{(1)} &= w_{1} \begin{pmatrix} b^{2}-c^{2}+\Delta \\ -a^{2}+c^{2} \\ a^{2}-b^{2} -\Delta \end{pmatrix} \label{x1} \text{where} \nn \\ w_{1} &= \sqrt{(a^{2}+b^{2}+c^{2}+2 \Delta )/(12\delta )},\\ \delta &=\Delta (2\Delta-a^{2}+2 b^{2}-c^{2})\nn \\ \intertext{and} \vect{x}_{(2)} &= w_{2} \begin{pmatrix} 2a^{2}-b^{2}-c^{2}-\Delta \\ -a^{2}+2b^{2}-c^{2}+2\Delta \\ -a^{2}-b^{2}+2c^{2}-\Delta \end{pmatrix} \label{x2} \text{where}\nn \\ w_{2} &= \sqrt{(a^{2}+b^{2}+c^{2}-2 \Delta )/(12\delta )}, \\ \delta &=\Delta (2\Delta-a^{2}+2 b^{2}-c^{2})\nn \\ \intertext{and} \vect{x}_{(3)} &=(0,0,0)^{T} \label{x3}\\ \text{since} \hspace{3pt} \lambda_{3}=0. \nn \end{align} The constants $w_{1}$ and $w_{2}$ are a product of $\lambda_{k}^{\frac{1}{2}}$ and the eigenvector normalization constant. Let A, B and C be the vertices of the triangle then say $AB=a, BC=b, AC=c $ . Further, let $x,y,z $ be the three axes then with $n=3$ the principal coordinates from \eqref{Xcoord} can be written down using $\vect{x}_{(1)},\vect{x}_{(2)},\vect{x}_{(3)}$ from \eqref{x1}, \eqref{x2}, and \eqref{x3} respectively. As the triangle lies in the $x-y$ plane , we have the following theorem with $(x_i,y_i), i=1,2,3$ of A, B, C respectively by ignoring the $z-$ coordinates.\\ {\bf Theorem 1.} Let $a^{2}+b^{2}+c^{2} \geq 2 \Delta $ where $\Delta$ is given by \eqref{Delta} , we have \beq \label {A} x_1= w_{1} ( b^{2}-c^{2}+\Delta ),\quad y_1= w_{2}(2a^{2}-b^{2}-c^{2}-\Delta ), \eeq \beq \label {B} x_2= w_{1} ( -a^{2}+c^{2} ),\quad y_2= w_{2}(-a^{2}+2b^{2}-c^{2}+2\Delta ), \eeq \beq \label {C} x_3= w_{1} (a^{2}-b^{2} -\Delta ),\quad y_3= w_{2}(-a^{2}-b^{2}+2c^{2}-\Delta ), \eeq where $$w_{1} = \sqrt{(a^{2}+b^{2}+c^{2}+2 \Delta )/(12\delta )},\quad w_{2}= \sqrt{(a^{2}+b^{2}+c^{2}-2 \Delta )/(12\delta )},$$ with $\delta =\Delta (2\Delta-a^{2}+2 b^{2}-c^{2}).$ Further, the center of gravity of the triangle is at $(0,0)$. \\ {\bf Proof.} Most of the results are already proved above. Note that $\Delta$ and $\delta$ are non-negative using the following inequality of the Geometric Mean and Arithmetic Mean given below successively. $$ x^2y^2 \leq (x^4+y^4)/2.$$ Alternatively, we see easily $ \Delta >0$ on noting that $$ 2\Delta ^2 = (a^2 -b^2)^2 + (a^2 -c^2)^2 + (b^2 -c^2)^2. $$ {\bf Corollary 1.} Let $a=c, a < b < 2a $ then for this isosceles case, we have \beq \label {Iso} x_1= b/2, y_1= - (4a^{2}-b^{2})/6;\quad x_2= 0,y_2= -2 y_1 ;\quad x_3= -x_1, y_3= y_1. \eeq {\bf Proof.} From the equations \eqref{EigenvaluesThree}, \eqref{x1} and \eqref{x2}, we find that for $a<b<2a$ we have $$\lambda_1 = b^2/2, \lambda_2 =(4 a^2 - b^2)/6, \quad w_{1} = 1/(4\Delta ),\quad w_{2}= \sqrt{(4 a^{2}-b^{2})}/(12\Delta ),$$ where $\Delta =b^{2}-a^{2}.$ Using these results in Theorem 1, our proof follows. \\ We now consider a wide range of particular isosceles triangles \begin{itemize} \item If $b=a$ , we have an equilateral triangle. \item If $b=2a$ , we have a flat triangle as $\lambda_2 = \lambda_3 =0.$ \item If $b>2a$ then $\lambda_1>0, \lambda_3 =0$ but $\lambda_2$ is imaginary so we can have a real solution only in one dimension. \item If $a$ is very large and $b$ is fixed then we have a peaked isosceles triangle. \end{itemize} Note that for the isosceles triangle, without any loss of generalities by rescaling, we can write the coordinates of $A,B,C$ as $$ A=(1,-e),B=(0,2e),C=(-1,-e)$$ where $ e= \sqrt{(4 a^{2}-b^{2})}/(3 b).$ It allows the equilateral case with $a=b$ ( as a limit) leading to the coordinates $$ A(1,-1/\sqrt{3}),B(0,2/\sqrt{3}),C(-1,-1/\sqrt{3}).$$ {\bf Remark 1.} Equation \eqref{EigenvaluesThree}, which gives the eigenvalues of $\bB$, can be used to determine if the desired Euclidean properties of $\bD$ are violated. Rearranging the equation for the second eigenvalues \eqref{EigenvaluesThree} or $w_2 \geq 0$ gives the condition ( for $\bB$ to be semi- positive definite) \begin{align} a^{2}+b^{2}+c^{2} &\geq 2 \Delta. \end{align} Hence, if this inequality holds then $\bD$ is Euclidean. {\bf Remark 2.} For visualization, we can shift the origin (and rotate if so desired) for the points $A, B, C $. For example, in \eqref{A}, \eqref{B}, \eqref{C}, we can use the transformation (as in the $2x2$ case) $$x_i^*= x_i-x_1, y_i^*=y_i-y_1$$ so we have $$x_1^*= 0, y_1^*=0$$ which helps in visualizing the isosceles case, in particular. \section{Effect of excluding eigenvalues in the MDS solution} When the distance /dissimilarity matrix is very general, the corresponding matrix $\bB$ can have some negative eigenvalues, which can distort the Euclidean fitted configuration. We now give some insight into this possible effect. Let $\bD=(\delta_{ij})$ be an $n \times n$ dissimilarity matrix. We are using slightly different notation than in the first section to emphasize that we are working now on a dissimilarity matrix and with the fitted distances $(d_{ij})$ for the MDS solution . Suppose as in \eqref{Bspectral} the corresponding matrix $\bB$ has spectral decomposition $\bB = \mathbf{\Gamma} \mathbf{\Lambda} \mathbf{\Gamma}^T$, with the eigenvalues in decreasing order (there is always at least one zero, and perhaps some negative eigenvalues) where as in Section 1, $\mathbf{\Lambda}$ is the diagonal matrix with the eigenvalues $\lambda_\ell, \ell=1,\ldots,n, $ and $\mathbf{\Gamma}$ is the matrix of the eigenvectors. Write \beq \label{gij} g_{ij}^{(\ell)} = \lambda_\ell (\gamma_{i,\ell} - \gamma_{j,\ell})^2. \eeq Then from \eqref{Xcoord}, the distance between the points $\vect{x}_i^T=({\lambda_1}^{\frac{1}{2}}{\gamma}_{i1},\ldots,{\lambda_n}^{\frac{1}{2}}{\gamma}_{in} ) $ and $\vect{x}_j^T=({\lambda_1}^{\frac{1}{2}}{\gamma}_{j1},\ldots,{\lambda_n}^{\frac{1}{2}}{\gamma}_{jn})$ is given by \beq \label{deltaij} \delta^2_{ij} = \sum_{\ell=1}^n g_{ij}^{(\ell)} \eeq which is an exact identity. If the MDS solution uses the first $p $ eigenvalues (assumed to be nonnegative, $p \leq n $), then the squared Euclidean distances for this MDS solution are given by \beq \label{dij} d^2_{ij} = \sum_{\ell=1}^p g_{ij}^{(\ell)}. \eeq The difference between \eqref{deltaij} and \eqref{dij} is \beq \label{diffij} \delta^2_{ij} - d^2_{ij} = \sum_{\ell=p+1}^n g_{ij}^{(\ell)} \eeq and measures the extent at sites $i,j$ to which the MDS solution fails to recover the starting dissimilarities. Let us fix 2 sites $i,j$ and consider two mutually exclusive possibilities (of course more complicated situations can occur): (a) Suppose $g_{ij}^{(\ell)}$ is near 0 for all $\ell = p+1, \ldots, n$ except for one value $\ell = \ell_1$, say. Further suppose that $\lambda_{\ell_1} > 0$. Then from \eqref{gij} and \eqref{diffij}, we have $$\delta^2_{ij} - d^2_{ij} > 0; $$ (b) Suppose $g_{ij}^{(\ell)}$ is near 0 for all $\ell = p+1, \ldots, n$ except for one value $\ell = \ell_2$, say. Further suppose that $\lambda_{\ell_2} < 0$. Then again from \eqref{gij} and \eqref{diffij}, $$\delta^2_{ij} - d^2_{ij} < 0 .$$ Hence, if $g_{ij}$ given by \eqref{gij} is positive (negative), the Euclidean distance will be smaller than (greater than) the dissimilarity. We now give a numerical example. {\bf Example.} We look at the journey times between a selection of 5 rail stations in Yorkshire (UK) to understand how the eigenvectors of $\bB$ can help to understand the behaviour of a solution of $\bB$ with some negative eigenvalues. There are two rail lines between Leeds and York; a fast line with direct trains, and a slow line that stops at various intermediate stations including Headingley, Horsforth and Harrogate. Here the ``journey time'' is defined as the time taken to reach the destination station for a passenger who begins a journey at the starting station at 12:00 noon. For example, consider a passenger beginning a journey at Leeds station at 12:00. If the next train for York leaves at 12:08 and arrives in York at 12:31, then the journey time is 31 minutes (8 minutes waiting in Leeds plus 23 minutes on the train). The times here are taken from a standard weekday timetable. Table \ref{table:rail} below gives the dissimilarities between all pairs of stations, where the dissimilarity between two stations $S1$ and $S2$ is defined as the smaller of two times: the journey time from $S1$ to $S2$ and the journey time from $S2$ to $S1$. Further the dissimilarity between a station and itself is taken to be 0. \begin{table}[h] \begin{center} \caption{ Dissimilarity matrix $\bD$ for train journey times between 5 rail stations in Yorkshire.} \begin{tabular}{lrrrrr} & A & B & C & D & E\\ (1) A: Leeds & 0 & 23 & 23 & 53 & 31 \\ (2) B: Headingley & 23 & 0 & 11 & 34 & 71\\ (3) C: Horsforth & 23 & 11 & 0 & 34 & 67\\ (4) D: Harrogate & 53 & 34 & 34 & 0 & 44\\ (5) E: York & 31 & 71 & 67 & 44 & 0 \end{tabular} \label{table:rail} \end{center} \end{table} \begin{figure}[h] \begin{center} \includegraphics[width=4in,height=4in]{q4f1.eps} \caption{ Two-dimensional MDS solution for train journey times between 5 rail stations in Yorkshire. A: Leeds, B: Headingley, C: Horsforth, D: Harrogate, E: York.} \label{fig:rail} \end{center} \end{figure} \newpage The eigenvalues of $\bB$ are $$\lambda_1= 3210, \lambda_2= 1439, \lambda_3=61, \lambda_4=0, \lambda_5= -964, $$ and the corresponding eigenvectors in $\mathbf{\Gamma}$ are \begin{verbatim} Eigenvectors [,1] [,2] [,3] [,4] [,5] [1,] 0.08 0.63 -0.06 -0.45 0.63 [2,] -0.48 0.06 -0.66 -0.45 -0.38 [3,] -0.41 0.06 0.75 -0.45 -0.26 [4,] 0.03 -0.77 -0.04 -0.45 0.45 [5,] 0.77 0.02 0.00 -0.45 -0.45 \end{verbatim} We take our MDS solution to be the two dimensional principal coordinates. Figure \ref{fig:rail} plots these two dimensional principal coordinates. Obviously as seen by the eigenvalues, $\bD$ is not a distance matrix. Also we can check that $$71 = \delta_{25} > \delta_{12}+ \delta_{15} = 23 + 31 = 54,$$ which violates the triangle inequality. The eigenvalues are 3210, 1439, 61, 0, -964. The first two are considerably larger than the rest in absolute value, suggesting the 2D MDS solutions should be a good representation. In particular, $\lambda_3=61$ seems negligible, $\lambda_4=0$ is an eigenvalue that always appears with eigenvector $\vect{1}_n$, $\lambda_5= -964$ is smaller than the first two eigenvalues, but not entirely negligible and may cause some distortion in the reconstruction as we now examine. Figure 1 shows that the stations lie roughly on a circle (not surprising since there are two lines between Leeds and York). Also, Headingley and Horsforth are close together, and Leeds is further from Harrogate than from York in terms of the dissimilarity though geographically Harrogate is nearer to Leeds than York. In the MDS solution, the Euclidean distance between Headingley and Horsforth is 7.1, which is smaller than the dissimilarity value 11. On the other hand, in the MDS solution the Euclidean distance between Leeds and York is 45.5, which is larger than the dissimilarity value 31. We can now explain this behaviour using the spectral decomposition of $\bB$, and using the result derived in this section. Let us now denote the stations A, $\ldots$, E by $1,\ldots ,5 $ respectively. Eigenvector entries for selected stations (and the corresponding eigenvalues 61 and -964 respectively)\\ \begin{tabular}{lrr} Station & $j=3$ & $j=5$ \\ Headingley (2) & -0.66 & -0.38\\ Horsforth (3) & 0.75 & -0.26\\ absolute difference & {\bf 1.41} & 0.12 \\ \\ Leeds (1) & -0.06 & 0.63\\ York (5) & 0.00 & -0.45\\ absolute difference & 0.06 & {\bf 1.08} \end{tabular} Hence, the difference between Headingley and Horsforth is dominated by the eigenvector $j=3$ (with positive eigenvalue, 61), whereas the difference between Leeds and York is dominated by the eigenvector $j=5$ (with negative eigenvalue, -964). In fact, the numerical values of the terms \eqref{gij} in the difference between the two distances given by \eqref{diffij} are $$ g_{23}^{(3)} = 121.3, \quad g_{23}^{(4)}= 0,\quad g_{23}^{(5)} = -13.9, $$ and $$ g_{15}^{(3)} = 0.2,\quad g_{15}^{(4)} = 0,\quad g_{15}^{(5)} = -1124.4, $$ so the dominated contributions $g_{23}^{(3)}$ and $g_{15}^{(5)}$ are clearly seen. This discussion explains why in the MDS solution, the Euclidean distance between Headingley (2) and Horsforth (3) is smaller than the dissimilarity value whereas the Euclidean distance between Leeds (1) and York (5) is larger than the dissimilarity value. \section{Acknowledgment} We wish to express our thanks to Wally Gilks and John Kent for their helpful comments and to the University of Leeds for the Example in Section 4 from an Examination paper. The first author would also like to thank the Leverhulme Trust for the Emeritus Fellowship. \section{References} Mardia, K. V., Kent, J. T., and Bibby, J. M. (1979). {\it Multivariate Analysis}. Academic press. \end{document} \begin{align} \bR = \begin{pmatrix} \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\ -\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}}
{'timestamp': '2021-12-30T02:25:30', 'yymm': '2112', 'arxiv_id': '2112.14503', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14503'}
arxiv
\section{Introduction}\label{introduction} Software systems evolve and are typically developed through program evolution cycles that involve frequent code modifications \cite{handsOnDevOps}. Therefore, when software evolves, the program modifications need to be tested to avoid introducing faults and ensure the expected program behavior. To test an evolving program, developers need to perform \textit{regression testing}, i.e., assessing the impact of the change on the program by generating additional test cases targeting the change and its dependencies~\cite{YooH12}. Typically, developers have to write or generate test cases that exercise the changes, stress their dependencies, and check that the program changes behave as intended \cite{ApiwattanapongSCOH06}. Mutation testing is an established software testing technique~\cite{PapadakisK00TH19}. It is typically applied to reveal faults in a program by modifying the program (aka injecting mutants) and generating tests to reveal the faults (i.e., kill the mutants) in the modified program. Mutation testing is an effective approach to improve the test suite's \revise{strengths} by ensuring that it is adequate and diverse enough to kill all injected mutants. In the last decade, mutation testing has focused on selecting or reducing the number of executed mutants to ensure that mutation testing is feasible and scales in practice. To this end, researchers have proposed mutation testing with a specific type of mutants \cite{offut1993}, mutant reduction by detecting equivalent mutants \cite{KintisPJMTH18, ChekamPBTS20} or by focusing on a particular category of mutants \revise{such as subsuming mutants\footnote{Subsuming mutants \cite{jia2009} or disjoint mutants \cite{KintisPM10} is a set of mutants that has no mutant that is killed by a proper subset of tests that kill another mutant.}} or hard-to-kill mutants \cite{PapadakisCT18, KurtzAODKG16, KintisPM10}. Traditional mutation testing involves injecting mutants into the entire code base of the software. However, mutation testing of evolving programs is challenging due to the \textit{scale of the required mutation analysis, the complexity of the program, and the difficulty of determining the impact of the dependencies of the program changes}. The sub-field of mutation testing addressing these issues by targeting the mutation testing program changes is referred to as \textit{commit-aware mutation testing} \cite{ma2020commit}. A few commit-aware mutation testing approaches have been proposed to tackle the challenges of mutation testing of evolving software systems~\cite{petrovic2018, ma2020commit, ma2021mudelta, CACHIA2013}. These approaches suggest that mutation testing of evolving systems should focus on the program changes rather than the entire program. Recent studies have also indicated that commit-relevant mutants can be found on unchanged code due to unforeseen interactions between changed and unchanged code~\cite{ma2020commit, ma2021mudelta}. However, these studies do not provide scientific insights into the nature and properties of commit-relevant mutants and their utility over time. For instance, it is necessary to understand the distribution and program location of commit-relevant mutants to effectively identify, select, or predict commit-relevant mutants. In this paper, we address this challenge by conducting an exploratory empirical study to investigate the properties of commit-relevant mutants. Specifically, we examined the distribution, location, prevalence, predictability, and utility of commit-relevant mutants, as well as subsuming commit-relevant mutants\footnote{\revise{Subsuming commit-relevant mutants is a set of commit-relevant mutants that has no commit-relevant mutant killed by a proper subset of tests that kill another commit-relevant mutant}}. To achieve this, we propose an experimental approach for identifying commit-relevant mutants using the notion of observational slicing \cite{BinkleyGHIKY14}, i.e., the relevance of an instruction to a program point of interest (such as a program state or variable(s)) can be determined by mutating instructions and observing their impact to the point of interest (changes on the target program state or variable). Since we aim to identify mutants relevant to changed instructions, we check the impact of mutants located on the changed code, as performed by observational slicing, on mutants located on unchanged code. In essence, with this approach, we measure the impact of second-order mutants on the first-order ones \cite{KintisPM12, KintisPM15}, which captures the existence of implicit interactions between the changed and unchanged code parts. Overall, our formulation of the commit-aware mutation testing addresses the limitations and challenges of the state of the art~\cite{ma2020commit, ma2021mudelta}, in particular, making it more general and applicable for most evolving systems (\textit{see Section \ref{exp-goals}}). Using this approach, we elicit the properties of commit-relevant mutants and study the advantage of commit-relevant mutant selection in comparison to random mutant selection or mutants located on program changes. To the best of our knowledge, this is the most extensive empirical study of commit-relevant mutants. Specifically, our evaluation setup contains 10,071,875 mutants and 288 commits extracted from five (5) mature open-source software repositories. Our experiments took over 68,213 CPU days of computation. The main objective of this work is to provide scientific insights concerning the application of mutation analysis in testing evolving software systems. The main findings of this paper are summarized as follows: \begin{itemize} \item \textit{Commit-relevant mutants are prevalent}. In our evaluation, \textit{30\%} of mutants are commit-relevant, on average. Hence, \revise{by reducing the number of mutants (by around 70\%) and concentrating merely on those representing change-aware test requirements, considerable cost reductions can be achieved}. \item \textit{Selecting subsuming commit-relevant mutants significantly reduces \revise{the number of mutants}}. \revise{Selection of \textit{subsuming commit-relevant mutants} reduces even further the number of mutants, by about 93\%, on average.} \item \textit{A large proportion of commit-relevant mutants are located outside of the program changes}. The majority of the commit-relevant mutants are located outside the changed methods (\textit{69\%}). \item \textit{Several evaluated commit or mutant related features can not reliably predict (subsuming) commit-relevant mutants}. For instance, (the number of) commit-relevant mutants cannot be reliably predicted by features such as the commit size or mutant operator types. \item \textit{State of the art mutant selection approaches miss a large portion of commit-relevant mutants.} As an example, random mutant selection techniques miss approximately 45\% of subsuming commit-relevant mutants when analyzing the scope of 20 mutants. \item \textit{Commit-relevant mutation testing significantly reduces the text executions in comparison to the state of the art mutant selection methods}. \revise{Specifically, commit-relevant mutation testing reduces the number of test executions by about 16 times compared to random mutant selection.} \end{itemize} \section{Commit-aware Mutation Testing} \label{sec:approach} \subsection{Definition} \revise{ Intuitively, \textit{commit-relevant} mutants are those that are linked with (capture) changed program behaviour, by the committed changes. } \revise{ These mutants are those that a) are killable and are located on the changed lines, because they capture behaviour relevant to the committed changes, and b) those that are killable, are located on unchanged lines and affect the changed, by the commit, program behaviour, because they capture the interaction of the changed and unchanged code. This is approximated by a special form of observational slicing that uses higher order mutants. The idea is that mutants, located on unmodified code, that impact the behavior of mutants located on modified code, are commit-relevant because they interact/depend with the changed code. Consider two first-order mutants $M_X$ and $M_Y$, such that $M_X$ is located on changed code and $M_Y$ is located within the changed code. Then, the higher order mutant ($M_{XY}$) is the one created by combining $M_X$ and $M_Y$. We say that $M_X$ is \textit{commit-relevant } if the higher order mutant ($M_{XY}$) has a different program behaviour from the first order mutants $M_X$ and $M_Y$. That is, $M_X$ is commit-relevant if ($M_{XY}$ != $M_{Y}$) and ($M_{XY}$ != $M_{X}$). Formally, the definition of \textit{commit-relevant mutant} can be formed as: } \begin{definition}[Commit-relevant mutants]\label{def:relevant-mutant} \revise{ A mutant \textit{$M_X$} is relevant to a commit-change, if a) it is killable and is located on the changed code, or b) there is a second order mutant \textit{$M_{XY}$} (formed by the mutant pair of \textit{$M_X$}, located outside the change, and \textit{$M_Y$}, located on the change) that has different behaviour from the two first-order mutants \textit{$M_X$} and \textit{$M_Y$} that it is composed of. } \end{definition} \begin{figure*}[bt] \begin{center} \includegraphics[width=1.0\textwidth,trim={0cm 4cm 0cm 4cm},clip]{figures/Demonstrating_example_v3.pdf} \caption{Example of relevant and not-relevant mutants. Left Sub-Figure: Mutant $M_X^1$ is relevant as mutant \textit{$M_Y$} impacts its behavior. Center Sub-Figure: Mutant $M_X^2$ is non-relevant as mutant \textit{$M_Y$} does not impacts its behavior. Right Sub-Figure: mutant $M_X^3$ is not relevant since there is no behavioral difference for every possible $M_Y$.} \label{fig:Demonstrating_example} \end{center} \end{figure*} \subsection{\revise{Motivating Examples}} \subsubsection*{\textbf{\revise{Simple Example}}} \revise{\autoref{fig:Demonstrating_example} describes three simple scenarios illustrating commit-relevant mutants on a toy code example.} In the code snippet on the left, we observe the example function \textit{fun} that takes two arguments (integer arrays of size \textit{3}). It starts by sorting the arrays' elements, then makes computations, and returns an integer as a result. The {\color{green}green} rectangle on line seven (\textit{7}) represents the line that has been modified in the code. Using Java comments (symbols ``\textit{//}'') on line three (\textit{3}) we represent mutant outside the change $M_X$, and the mutant on the change $M_Y$ on line seven (\textit{7}). Mutant $M_X$ changes the value of variable ``\textit{R}'' to zero (\textit{0}), while the mutant \textit{$M_Y$} changes the value of variable ``\text{L}'' to one (\textit{1}). Consider that our test suite is confirmed just by one test that invokes function \textit{fun} with the following arguments: \textit{z = \{0, 3, 3\} } and \textit{k = \{0, 2, 3\}}. The output of the corresponding input value is observed from the inside of an atomic assertion as the input's actual value. We can see that after comparing obtained values after running each mutant in isolation, given the same test input, the mutant's behavior is different. Following our definition, this suggests that \textit{$M_X$} is relevant to the modification, since the actual execution value output (\textit{fun(z, k)}) for mutant \textit{$M_X$} is \textit{0}, which is different from mutant \textit{$M_Y$} whereas \textit{fun(z, k) = 1}, and \textit{$M_{XY}$} \textit{fun(z, k) = -1}. The code snippet in the middle of the figure presents the scenario in which a mutant is not relevant to the modification. Precisely, let us consider the same mutant $M_Y$ on the change on line \textit{5.+} as before, but now mutant $M_X$ located outside the change is on line \textit{3}. Mutant $M_X$ modifies the assignment statement into \textit{R = 0}. Given the same test input as before (i.e., \textit{z = \{0, 3, 3\} } and \textit{k = \{0, 2, 3\}}), and following the mutants execution behavior, we can observe that mutants show no observable interaction. Therefore, mutant \textit{$M_X$} is not considered relevant for this particular change. The code snippet on the right side shows an additional example of a non-relevant mutant. However, in this example, we observe two mutants that are unreachable from each other. These two mutants, for any test input, do not show observable differential interaction. Therefore, mutant \textit{$M_X$} is considered to be non-relevant to test the corresponding change. \begin{minipage}{\textwidth} \begin{minipage}[b]{\textwidth} \begin{figure}[H] \centering \includegraphics[scale=0.5,trim={0cm 3.4cm 0cm 3.3cm},clip]{figures/Real_case_example.pdf} \caption{\revise{Method (\texttt{read()}) excerpted from the \texttt{BoundedReader.java} program in the Apache commons-io project (version \texttt{81210eb})}} \label{fig:Real_case_example} \end{figure} \end{minipage} \end{minipage} \subsubsection*{\textbf{\revise{Real Example}}} \revise{ \autoref{fig:Real_case_example} presents an excerpt of a program from the Apache commons-io\footnote{https://github.com/apache/commons-io} project, version \texttt{81210eb}. The figure shows an evolution of the program in which the function \texttt{read} was modified in line 142 (from \texttt{org.apache.commons.io.input.BoundedReader.java}). The program change adds a constraints on the function's return value, suggesting that it should return negative one (-1) in case the buffer does not contain any more values, and otherwise it should return the index of the current iteration (i.e., \texttt{i}). Specifically, the previous version of the program always returned \texttt{i} in line 142, but the modified version either returns -1, when \texttt{i} is equals to 0, or \texttt{i} otherwise.} \revise{ Function \texttt{read} takes three parameters, namely, an array of chars \texttt{cbuf}, and two integers \texttt{off} and \texttt{len}. Intuitively, function \texttt{read} aims at modifying a certain number of characters (\texttt{len}) of array \texttt{cbuf}, starting from the given offset position \texttt{off}. The function starts by reading a new character from a different buffer (see built-in \texttt{read()} invocation in line 140), then it proceeds to update \texttt{cbuf} array with the new character, and finally it returns the number of updated characters\footnote{For more information about the implementation of this method, please refer to official implementation documentation page:\cite{junitAPIlink}} Notice that the \texttt{read()} invocation (line 140) returns the fed character as an integer in the range between zero (0) to 65535 (0x00-0xffff), or it returns negative one (-1) if the end of the buffer has been reached. } \revise{ As an example, consider a testing scenario that executes function \texttt{read} with the following inputs: } \noindent \revise{ \hspace*{2cm}\texttt{read([`X', `X', `X', `X'], 1, 2);} } \revise{ \noindent and the buffer accessed by the \texttt{read()} call in line 140 is as: } \noindent \revise{ \hspace*{2cm}\texttt{[`0', `1', `2', `3', `4', `5', `6', `7', `8', `9', `0'];} } \noindent \revise{ For this test case, both versions of the program, the previous one and the recently changed version, will return the same output (i.e., \texttt{len = 2}). Moreover, both versions of the program will produce the same modifications into array \texttt{cbuf} given as input, resulting in: \begin{center} \texttt{[`X', `0', `1', `X']} \end{center} This is an example of a test case that does not exercise the program changes, since the change (line 142) is never executed for this test case. Hence, the test does not show any behavioral difference between the previous version of the program and the current modified version of it. } \begin{minipage}{\textwidth} \begin{minipage}[b]{\textwidth} \begin{table}[H] \caption{\revise{ Test output observation for \autoref{fig:Real_case_example} showing the program behavior (outputs) of original program, the changed program, and the first and second order mutants of the program. The test observations are performed using input \texttt{read([`X',`X',`X',`X'], 1, 2)} and an empty buffer (\texttt{[]}) fed to the built-in function \texttt{read} (in line 140)}} \label{tab:case-study-table} \centering \scalebox{0.9}{ \begin{tabular}{l c c c c c} \toprule & \textbf{\scriptsize{Program Versions}} & \textbf{\scriptsize{Program Changes}} & \textbf{\scriptsize{Code line}} & \textbf{\scriptsize{Test output}} & \textbf{\scriptsize{Commit-Relevance}}\tabularnewline \midrule \scriptsize{Pre-commit} & \scriptsize{Old version \texttt{51f13c84}} & \scriptsize{\texttt{i}} & \scriptsize{\textit{142}} & \scriptsize{0} & \scriptsize{N/A} \tabularnewline \scriptsize{Post-commit} & \scriptsize{New version \texttt{81210eb}} & \scriptsize{\texttt{i == 0 ? -1 : i}} & \scriptsize{\textit{142}} & \scriptsize{-1} & \scriptsize{N/A} \tabularnewline \scriptsize{First-order mutant} & \scriptsize{M1} & \scriptsize{\texttt{== $\Rightarrow$ !=}} & \scriptsize{\textit{142}} & \scriptsize{0} & \scriptsize{\textit{Relevant}} \tabularnewline \scriptsize{First-order mutant} & \scriptsize{M2} & \scriptsize{\texttt{len $\Rightarrow$ 0}} & \scriptsize{\textit{139}} & \scriptsize{2} & \scriptsize{\textit{Non-Relevant}} \tabularnewline \scriptsize{First-order mutant} & \scriptsize{M3} & \scriptsize{i $\Rightarrow$ ++i} & \scriptsize{\textit{139}} & \scriptsize{1} & \scriptsize{\textit{Relevant}} \tabularnewline \scriptsize{First-order mutant} & \scriptsize{M4} & \scriptsize{\texttt{delete statement}} & \scriptsize{\textit{140}} & \scriptsize{2} & \scriptsize{\textit{Non-Relevant}} \tabularnewline \scriptsize{Second-order mutant} & \scriptsize{M12} & \scriptsize{\texttt{== $\Rightarrow$ != $\land$ len $\Rightarrow$ 0}} & \scriptsize{\textit{142 $\land$ 139}} & \scriptsize{2} & \scriptsize{N/A} \tabularnewline \scriptsize{Second-order mutant} & \scriptsize{M13} & \scriptsize{\texttt{== $\Rightarrow$ != $\land$ i $\Rightarrow$ ++i}} & \scriptsize{\textit{142 $\land$ 139}} & \scriptsize{-1} & \scriptsize{N/A} \tabularnewline \scriptsize{Second-order mutant} & \scriptsize{M14} & \scriptsize{\texttt{== $\Rightarrow$ != $\land$ delete statement}} & \scriptsize{\textit{142 $\land$ 140}} & \scriptsize{2} & \scriptsize{N/A} \tabularnewline \bottomrule \end{tabular} } \end{table} \end{minipage} \end{minipage} \subsubsection*{Commit-aware Mutation Testing} \revise{Now, consider that during the mutation testing analysis, four mutants ($M1$ to $M4$) are injected into the function\texttt{read}, as it is shown in \autoref{fig:Real_case_example} via Java comments (``\texttt{//}''). Particularly, \textit{Mutant $M1$} is located on the modified statement in line 142, i.e., it is a mutant withing the program change, and it replaces the condition \texttt{==} (equal) with \texttt{!=} (not equal). \textit{Mutant $M2$} is located on line 139 (outside the change) and replaces the variable \texttt{len} with a constant value zero (0), mutating the condition of the \texttt{for} loop \texttt{i < len} to \texttt{i < 0}. \textit{Mutant $M3$} is also injected on the same statement (line 139) but it uses an unary insertion (\texttt{++i}) to update variable $i$ within the condition check of the \texttt{for} loop, such that condition (\texttt{i < len}) is mutated to (\texttt{++i < len}). Finally, \textit{Mutant $M4$} removes the statement located on line 140 (i.e., \texttt{c = read()}). } \revise{Then, by using our HOM-based approach, we can create higher-order mutants by pairing all four mutants. Precisely, we pair the mutants located outside the change with the mutants on the commit-change (line 142), and we obtain three higher-order mutants $M12$, $M13$, and $M14$. \autoref{tab:case-study-table} illustrates the behavior (outputs) of function \texttt{read} under its previous version, its current changed version, and all the mutants. } \revise{ Consider now a different testing scenario in which the input buffer accessed by the built-in function \texttt{read} in line 140 is empty (i.e., \texttt{[]}). This testing scenario shows the behavioral difference between the previous version and the modified version of the program, since it executes the change (in line 142). We observe that, while the execution of the previous version of the program returns zero (0), the modified version returns negative one (-1). } \revise{ \autoref{tab:case-study-table} highlights the behavior (i.e., output) of each mutant. First, according to the traditional definition of commit-relevant mutants, $M1$ is a commit-relevant mutant, since it is located on the program change~\cite{CACHIA2013}. Additionally, according to our extension of the definition of commit-aware mutation (\textit{see} \autoref{sec:approach}), we compare the output of the second-order mutants and their isolated first-order mutants. We observe that the second-order mutant $M13$ is also a commit relevant mutant. This is because the second order mutant ($M3$) has a different behavior from the isolated first-order mutants (i.e., $M13$ != $M3$, and $M13$ != $M1$). Meanwhile, the other second-order mutants, i.e., $M12$ and $M14$ are not commit-relevant because they have similar behaviors as the isolated first-order mutants (i.e., $M12$ == $M2$, and $M14$ == $M4$). } \subsubsection*{Commit-aware Criteria} \revise{ Let us illustrate the importance of the strict constraint employed in our approach to compare the behaviors of first-order and second-order mutants (e.g., the need to ensure $M13$ != $M3$ \textit{AND} $M13$ != $M1$) using a counter-example. Specifically, we will discuss the rationale for this constraint and why considering a less strict constraint does not suffice (and mutants like, for instance, $M2$ are not commit-relevant, despite the fact that $M12$ != $M1$ but $M12$ == $M2$). Let us consider the example program in \autoref{fig:Real_case_example} and the output behavior observed in \autoref{tab:case-study-table}. Even though $M1$ and $M12$ have different output, inspecting the behavior of $M12$ on the program change using the provided test cases, we observe that the behavior of the second-order mutant $M12$ is not different from that of $M2$. In fact, $M2$ does not execute the program change nor the mutant within the change. Indeed there is no input that can force mutant $M2$ to execute the changed line (in line 142), since the \texttt{for} loop condition will always evaluate to false. This implies that using a less strict constraint (e.g., an ``OR'' operation) in our check, will lead to such mis-identification of commit-relevant mutants, implying that mutants that can never lead to the execution of the program change (e.,g., $M2$) can be mis-classified as relevant to the program change. Thus, it is important to ensure that the behavior of the second-order mutant and that of the isolated first-order mutants are indeed different. } \subsubsection*{Subsumption Relation} \revise{Let us illustrate the subsumption relation of commit-relevant mutants. Consider the two commit-relevant mutants in our example, i.e., \textit{mutant $M3$} that we have identified as commit-relevant, and \textit{mutant $M1$} located on the changed statement (commit-relevant by default). In our example (\autoref{fig:Real_case_example}), both mutants are killed by the initial test input (in \autoref{tab:case-study-table}). Let us consider that the test suite has one additional test, in particular the following test: \begin{center} \texttt{read([`X',`X',`X',`X'], 1, 1)} \end{center} \noindent Given this new test input, we observe that \textit{mutant $M1$} is killed by this test input (output zero (0)), but \textit{mutant $M3$} is not killed by the test (output one (1)). Following the definition of mutant subsumption \cite{ammann_establishing_2014}, we can observe that a test that distinguishes \textit{mutant $M3$}, will also distinguish \textit{mutant $M1$}, but \textit{mutant $M1$} can be distinguished by a test that cannot distinguish \textit{mutant $M3$}. In this situation, we say that \textit{$M3$ subsumes $M1$}, making $M3$ a \textit{subsuming commit-relevant mutant}. This example illustrates a scenario where a subsuming commit-relevant mutants is located outside the program change. The mutant residing outside the change subsumes a mutant residing on the program change, which makes the test requirement of the mutant on the change redundant. We can satisfy both mutants ($M1$ and $M3$) by writing test requirements to identify the subsuming commit-relevant mutant located outside of the committed change (i.e., $M3$), which is the commit-relevant mutant also identified by our approach.} \subsection{State of the Art} Let us provide background on the state of the art in commit-aware mutation testing. There are very few research papers on commit-aware mutation testing. In particular, we highlight the papers on the formalization of the concept as well as techniques for selecting commit-aware mutants. \begin{itemize} \item \textbf{\textit{Formalization of Commit-aware Mutation Testing:}} Ma \textit{et al. }~\cite{ma2020commit} defines and formalizes the concept of commit-aware mutation testing. \revise{ The paper defines commit-relevant mutants as a set of mutants capturing the interactions that affect the changed program behaviors. The paper further shows that there is only a weak correlation between commit-relevant mutation scores and traditional mutation scores, thus, highlighting the need for a commit-aware test assessment metric. In its evaluation, the authors demonstrate the strength of commit-aware mutation in revealing commit-related faults by showing that traditional mutation has about 30\% less chances of revealing commit-introducing faults, in comparison to commit-aware mutation testing.} \revise{ In this work, we propose an alternative approach to identify commit-relevant mutants. In comparison to \cite{ma2020commit}, our approach removes the strict test contract assumption that requires test suites being executable across program versions, i.e., there are not contract changes. In our setup, we address this concern by employing only the post-commit version and the committed change for commit-aware mutation testing, with no restriction on the evolution of the test suite (\textit{see Section \ref{exp-goals}}). } \item \textbf{\textit{Diff-based Commit-aware Mutant Selection:}} Cachia et al.~\cite{CACHIA2013} proposed an incremental mutation testing that limits the scope of mutant generation to strictly changed code regions since the last mutation run. Similarly, Petrovic et al.~\cite{petrovic2018} proposed a diff-based probabilistic mutant selection technique that focuses only on the mutants located within the program changes. These approaches ignore the program dependencies between the committed changes and the unmodified code by design. Hence, in this work, we present and employ an experimental approach that accounts for the dependencies between program changes and unmodified code when identifying commit-relevant mutants to demonstrate the extent to which using mutant from modified code can help. Our approach analyses the effect of second-order mutants, one within the program change and the other in the unmodified code, on the evolving program behavior. \item \textbf{\textit{Machine Learning based Commit-aware Mutant Selection:}} \texttt{Mudelta}~\cite{ma2021mudelta} presents a machine learning and static analysis-based approach for predicting commit-relevant mutants. \revise{This paper illustrates the importance of commit-aware mutation testing, particularly its ability to reduce mutation testing effort and reveal commit-related faults. In comparison to random mutant selection, \texttt{Mudelta} reveals 45\% more commit-relevant mutants, and achieves 27\% higher fault revealing ability in fault introducing commits. In this work, we propose a complementary dynamic analysis approach for commit-aware mutation testing. Specifically, we propose a new HOM-based observation slicing approach for commit-aware mutation testing, that is applicable in the absence of static code features or (large) training data. } \item \textbf{\textit{\revise{Interface Mutation:}}} \revise{ \citet{delamaro2001interface} proposed an inter-procedural mutation analysis approach for generating mutants that are relevant for integration testing, i.e., suitable for testing the interactions between program units. In particular, since interface mutation aims at testing component integrations, it injects mutants on the component contracts (interfaces) and pairs of them at the component call sites and related uses of the interface parameter inside the components bodies in order to capture potential interactions between the caller and called components. This mechanism, of capturing dependences through pairs of mutants, is somehow similar to our approach but more restrictive as it targets interfaces (call sites and method parameter uses). In contrast commit-aware mutation testing aims at identifying relevant dependencies between changed and unchanged code and not between components. } \end{itemize} \subsection{Design Requirements} \label{exp-goals} Our commit-relevant mutation approach aims to fulfill certain requirements to ensure we gather and study a vast number of commits and commit-relevant mutants. These design requirements address some of the limitations and challenges of state of the art ~\cite{ma2020commit, ma2021mudelta, petrovic2018}. In particular, we address the following: \begin{itemize} \item \textbf{\textit{Location of Commit-relevant Mutants:}} In this work, we focus on identifying commit-relevant mutants within and outside the program changes, i.e., within the commit-change as done in prior work~\cite{petrovic2018}, and the unmodified program code. In particular, we are interested in revealing behavioral interactions induced by the program changes on the rest of the unmodified program code. We achieve this by identifying the commit-relevant mutants outside of the program changes. In particular, we employ second-order mutants; we analyze the impact of second-order mutants on the behavior of the evolving program (\textit{see Section \ref{sec:approach-overview}}). \item \textbf{\textit{Test Contract:}} Our experimental approach employs only the test suite from the post-commit program version. In previous work~\cite{ma2020commit}, the experimental design requires the execution of test suites across the pre-commit and post-commit versions of the program. Plus, it implies that the number of tests does not increase or decreases across versions, i.e., the test contract is intact. Therefore, the approach observes the delta between versions by comparing mutants test suites from pre- and post-change commit. This assumption is impractical in several cases since the test suite also evolves as the program evolves, e.g., when implementing new features or fixing bugs. In our work, we observed that this assumption is not common in practice. In particular, in our study, the proportion of commits where the test contract is preserved is less than 40\%. \item \textbf{\textit{\revise{Commit Patches and Hunks}}}: \revise{In our approach for commit-aware mutation testing, we require the commit patches and commit hunks for empirical evaluation and analysis. Indeed, commit properties are vital for commit-aware mutation testing and commonly used by the state of the art techniques~\cite{ma2020commit,ma2021mudelta}. In our work, we employ commit properties (i.e., patches and commit hunks) for both commit-relevant mutant detection and experimental analysis. Particularly, our approach requires the commit patches (i.e., the delta between pre-commit and post-commit versions) to identify the interaction of the mutants within the change and the mutants outside the change. We also employ commit hunks in our experimental analysis, to identify the number of individual code-chunks structure present in a commit. Applying commit hunks in our analysis sheds light on the relationship between altered statements in the commit hunk and the mutants residing outside the commit hunk. } \item \textbf{\textit{Post-Commit Version:}} Our experimental approach requires \textit{the post-commit version of the program to be compilable, executable, and testable}. \revise{These requirements are vital for the dynamic analysis of our approach and they only apply to the \textit{post-commit version} of the program. In contrast, previous work~\cite{ma2020commit} requires two program versions (pre-commit and post-commit) and \textit{assumes a green test suite, no build failures and no compilation errors for both program versions}. In our evaluation setup, we find that these conditions are uncommon (less than 40\% of the cases). To address this concern, we ensure our approach requires the post-commit version of the program, without need for the pre-commit version. This allows collecting significantly more commits for our study, and allows to evaluate a vast amount of commit-relevant mutants. } \item \textbf{\textit{Test Oracle: }} \revise{In this work, we employ test assertions of system units as our test oracle. This is a fine-grained test oracle used by unit tests. Here it is important to note that when we refer to assertions these are \textit{test assertions}, and \textit{not program assertions} and are used for checking the observable behaviour of the program units, as mandated by strong mutation. In practice, we use test assertions to define the mutant behaviour study the impact of mutants and changes on program behaviour. } \item \textbf{\textit{Number of Commits:}} Our empirical study characterized commit-relevant mutants and required a substantial number of commits and commit-relevant mutants. Dues to the flexibility of our experimental approach, in this study, we analyzed significantly (10x) more commits and mutants than previous work~\cite{ma2020commit}. We addressed the significant limitations and assumptions of prior work, which could prevent gathering a sufficient number of commits and commit-relevant mutants. For instance, as stated in the paper \revise{Ma et al.}~\cite{ma2020commit}, it is challenging to find commits in open-source projects that do not break the test contract, i.e., keep the test suite intact. This challenge further inhibits our goal of automatically studying the characteristics of relevant mutants. Addressing the concerns above allows us to gather and study more commits than previous studies. \end{itemize} Our experimental approach aims to target the requirements above to ensure that we gather many commits and cover several realistic corner cases for evolving software systems. Overall, fulfilling these requirements and addressing these concerns enables us to collect significantly more commits and identify significantly more commit-relevant mutants for our study. In particular, our study involved 10x more commits and 6x more commit-relevant mutants than previous studies. \subsection{Approach Overview} \label{sec:approach-overview} Our study aims at investigating the existence and distribution of commit-relevant mutants in evolving software systems. Specifically, we study the relationship between the lines of code changed in a commit hunk and the mutants residing on program locations outside the commit hunk under consideration. Intuitively, we want to study the interaction between two program locations, where one location is part of the commit hunk, and the other is outside the change. We plan to employ high-order mutants (second-order to be more precise) and simulate potential changes in a commit hunk and the mutants outside the commit hunk. This study aims at providing scientific evidence of the relationship and relevance of mutants (test requirements) outside commit hunks that need to be taken into account when testing evolving systems. To determine if a mutant is relevant for a commit hunk, we plan to observe whether the commit changes affect mutants' behavior. Intuitively, suppose a change in a location in the commit hunk (produced by a mutation) affects the outcome of the mutant outside the commit. In that case, we have evidence that there exists an interaction between these two locations, indicating that the mutant is \emph{relevant} for the commit. The absence of interactions indicates either the existence of equivalent mutants \cite{KintisPM12, KintisPM15} or the absence of dependence/relevance. To account for the case of equivalent mutants and ensure the relevance of observations, we sample multiple mutants per statement. Mutants' behavior is (partially) determined by observing their covering test set. Implying that if we want to observe the interaction between mutants on different locations, the test set should make any difference in the mutant's behavior whether they are run in isolation or combined both. More precisely, if we can observe that the behavior of two mutants $M_X$ and $M_Y$ run in isolation differs from the behavior of the second-order mutant $M_{XY}$ (obtained by combining both mutations $M_X$ and $M_Y$), then we can conclude that mutants $M_X$ and $M_Y$ influence each other. Figure \ref{fig:Approach_intro} depicts such a situation, where the test set $\{t_0, t_1\}$ is able to observe that $M_{XY}$'s behavior differs from $M_X$ and $M_Y$'s behavior. For instance, test $t_0$ passes on mutants $M_X$ and $M_Y$ but fails on mutant $M_{XY}$. Thus, we can conclude that locations in which mutations $M_X$ and $M_Y$ were applied to interact with each other. Following a similar idea, consider generating one of the mutants outside the change ($M_X$) and the other one on the change ($M_Y$), and their combination makes a second-order mutant ($M_{XY}$) suitable for observing if there exists an interaction between them. To determine if mutant $M_X$ is relevant for the commit change, we can iterate this process by exploring different high-order mutants $M_{XY}$ by varying mutant on the change $M_Y$, with the aim at finding one combination that evidence their interaction. To compare mutants' behaviors, first, we need an intersection set of tests covering mutants $M_X$, $M_Y$, and $M_{XY}$. Second, we proceed to run these tests to observe a difference between the mutants. Instead of considering only passing and failing output as a standard unit level testing oracle, we instrument tests and contained assertions to obtain and compare actual assertion values. For instance, an assertion like \texttt{assertEquals(0, Z)} can be violated by a (potentially) infinite number of values for \texttt{Z}, all of them violating the assertion. Suppose after executing mutants $M_X$, $M_Y$ and $M_{XY}$, the value of \texttt{Z} is different. In that case, we can observe a difference in their execution, allowing us to determine if there exists an interaction between these mutants, concluding that mutant $M_X$ is relevant for the commit change. Section~\ref{sec:pitest-assert-tool} describes the implementation details on how we instrument test executions to obtain actual assertion values. Figure \ref{fig:Approach_figure_example} illustrates our approach to detect interactions between mutants by comparing their behavioral assertion values. It depicts that after executing each first-order mutant $M_X$ and $M_Y$ in isolation (assertions that cover them), we compare the output values with the value obtained after running second-order mutant $M_{XY}$. If running $M_X$ and $M_Y$ in isolation differs from running $M_{XY}$, we determine that mutant $M_X$ is relevant for the commit change. \begin{figure*}[htp!] \begin{center} \includegraphics[width=0.8\textwidth,trim={0cm 5cm 0cm 4cm},clip]{figures/Approach_figure_example_v3.pdf} \caption{A mutant \textit{$M_X$} is relevant to a commit-change, if any higher order mutant \textit{$M_{XY}$}, shows different behavior from \textit{$M_X$} and \textit{$M_Y$} executed in isolation} \label{fig:Approach_figure_example} \end{center} \end{figure*} \subsection{Algorithm} \label{sec:approach-algorithm} To perform an empirical study toward distinguishing relevant mutants, we generate the first order mutants located around and on the commit change (i.e., $M_X$ and $M_Y$, respectively). The second-order mutants (i.e., $M_{XY}$) are a combination of the previous two. The \emph{mutant-assertion matrices} were obtained by executing the mutants against developer-written and automatically generated test pools. Note that test run status is pass/fall for Java programs; therefore, to observe behavioral differences produced by mutants, we need to focus on test assertions and record assertion execution actual value output of each test on every mutant. Precisely, for every mutant and every test assertion, a mutant-assertion matrix stores the assertion values obtained after running a mutant against a test. As noted, this study performs mutation analysis on commits from Java programs, using Pitest\footnote{http://pitest.org/} as the Java mutation testing tool, and EvoSuite\footnote{https://www.evosuite.org/} as the state of the art test case generation tool. Section \ref{analysis_procedure} provides further details regarding mutants test case generation and test assertions instrumentation. After computing mutant-assertion matrices, we proceed to approximate which mutants are relevant to the change, according to our Definition~\ref{def:relevant-mutant} following the steps incorporated in Algorithm ~\ref{algo:relevant}. The algorithm summarises previously described process, where functions \emph{MutantsonChangeMutantOuput}, \emph{aroundChangeMutantOutput}, \emph{highOrderMutantOutput} return the output of a specific test \textit{assertion} execution per specific \textit{mutant}. Finally, Algorithm~\ref{algo:relevant} returns a set of relevant mutants for a particular commit change. \revise{ This algorithm has a worst-case polynomial time complexity of $O(n^4)$, due to the four nested \texttt{for} loops ($O(n*n*n*n)$). For each of the three inputs fed to the algorithm (\emph{TestSuite}, \emph{MutantsOnChange} and \emph{MutantsAroundChange}), there is a linear-time complexity ($O(n)$). Additionally, there is a linear-time complexity ($O(n)$) for evaluating each test assertion corresponding to the test cases. Overall, the performance of the algorithm depends on the number of mutants in the change, the number of mutants injected in the modified code, the size of the test suite and the number of assertions in each test. Specifically, to derive higher-order mutants, we consider every pair of mutants within and outside the change, we also execute all test cases corresponding to these mutants, and evaluate all test assertions in each test case. This algorithm can be optimized by improving the number of evaluated tests, assertions or pairs of mutants.} \revise{The complexity of this algorithm can be reduced to ($O(log(n) * n^3)$ via a binary search on the pair of mutants (outside the change) that exposes a behavioral difference. Likewise, the complexity can be reduced to cubic complexity ($O(n^3)$) by executing a constant number of test cases/assertions ($O(1)$). For instance, an improvement is achievable by selecting and executing only the most relevant tests for the changes, e.g., from historical test executions in the CI. A reduction is also achievable if only one test assertion is evaluated for each test case, e.g., executing only the assertion that captures the interaction between the pair of mutants has a constant time complexity ($O(1)$). } \setlength{\algomargin}{0.99em} \setlength{\textfloatsep}{13pt} \begin{algorithm} \SetAlgoLined \LinesNumbered \KwData{TestSuite, MutantsOnChange, MutantsAroundChange} \KwResult{Relevant Mutants} $RelevantMuts \leftarrow \emptyset$\; \For{$X \in MutantsAroundChange$}{ \For{$Y \in MutantsOnChange$}{ \For{$test \in TestSuite$}{ \For{$assertion \in test$}{ $Yval \leftarrow onChangeMutantOuput(assertion, Y)$\; $Xval \leftarrow aroundChangeMutantOutput(assertion, X)$\; $XYval \leftarrow highOrderMutantOutput(assertion, Y, X)$\; \If{$Yval \neq XYval \land Xval \neq XYval$}{ $RelevantMuts \leftarrow RelevantMuts \cup \{X\}$\; \textbf{jump to line 2 and take next mutant $X$}\; } } } } } \Return $RelevantMuts$ \; \caption{Approximate Commit-relevant Mutants Set} \label{algo:relevant} \end{algorithm} \section{Background}\label{mutation_testing} \subsection{Mutation Testing} Mutation is a test adequacy criterion in which test requirements are characterized by mean of \emph{mutants} obtained by performing slight syntactic modifications to the original program (for instance, the relational expression $\texttt{a > b}$ can be mutated into $\texttt{a < b}$). Intuitively, these mutants aim at representing artificially injected faults that can be used to assess the effectiveness and thoroughness of a test suite in detecting these seeded faults. Then, the tester starts by analyzing the mutants and proceeds to design test cases to \emph{kill} them, i.e., to distinguish the observable behavior between the mutant and the original program. Hence, the adequacy of a test suite concerning the mutation criterion, called \emph{mutation score}, is computed as the ratio of killed mutants over the total number of mutants. Notice that the number of mutants not necessarily represent the number of test cases required to cover all of them since several mutants can be redundant. On the one hand, there may exist mutants that cannot be killed by any test since they are functionally \emph{equivalent} to the original program. On the other hand, one test may kill other mutants at the same time. Thus, the effort put into analyzing and executing redundant mutants is wasted; hence it is desirable to analyze only the mutants that add value. \subsection{Subsuming Mutants} \label{sec:subsuming_mutants} Subsuming relations aims at finding the minimal set of mutants required to cover all (killable) mutants~\cite{ammann_establishing_2014}. Intuitively, this set of mutants has minimal redundancies and represents a nearly optimal mutation testing process with respect to cost \cite{PapadakisHHJT16, PapadakisCT18}. More formally, let us consider that $M_1$, $M_2$, and $T$ be two mutants and a test suite, respectively. Consider also that $T_1 \subseteq T$ and $T_2 \subseteq T$ are the set of tests from $T$ that kill mutants $M_1$ and $M_2$, respectively, where $T_1 \neq \emptyset$ and $T_2 \neq \emptyset$ indicating that both $M_1$ and $M_2$ are killable mutants. We say that mutant $M_1$ subsumes mutant $M_2$, if and only if, $T_1 \subseteq T_2$. In case $T_1=T_2$, we say that mutants $M_1$ and $M_2$ are indistinguishable. The set of mutants that are both killable and subsumed only by indistinguishable mutants are called \emph{subsuming mutants}. For instance, assuming that $T_1=\{t_1,t_2\}$ and $T_2=\{t_1,t_2,t_3\}$, one can notice that every time we run a test to kill mutant $M_1$ (i.e., $t_1$ or $t_2$) we will also kill mutant $M_2$. While the vice versa does not hold since if we kill mutant $M_2$ by $t_3$, we will not kill mutant $M_1$. In this case we say that $M_1$ subsumes $M_2$. \revise{Several researchers have studied the impact and prevalence of subsuming mutants for traditional mutation testing~\cite{PapadakisHHJT16, PapadakisCT18, alipour2016evaluating, guimaraes2020optimizing}. For instance, \citet{alipour2016evaluating} demonstrated that subsuming mutants can reduce traditional mutation testing effort by up to 80\%. In particular, in their empirical study on mutation test reduction, found that subsuming mutants can reduce the number of mutants requiring analysis by up to 80\%. Their study demonstrated the importance of subsuming mutants in traditional mutation testing, emphasizing that there is strong inter-dependency among mutants. In their empirical evaluation of \textit{traditional mutation testing} (involving four C projects and thousands of mutants), the paper found that test case reduction based on a single mutant can reduce mutation testing effort (in terms of the number of mutant test executions) by 33 to 80\%~\cite{alipour2016evaluating}. Likewise, \citet{guimaraes2020optimizing} empirically demonstrated that identifying dynamic subsumption relations among mutants reduces traditional mutation test execution time by 53\%. \citet{delamaro2001interface} also demonstrated that identifying the inter-procedural relation among mutants in two program units helps to identify interface mutants, i.e., the mutants that are relevant for mutation testing during system integration. } \revise{However, despite the evidence of the impact of subsuming mutants on traditional mutation testing and integration testing, their impact on commit-aware mutation testing remains unknown. Thus, \textit{in this paper, we study the prevalence and distribution of mutants relevant for a committed change and the extent to which subsuming relations are maintained.} } \subsection{High-Order Mutants} Depending on the number of mutation operators we apply to the original program, we can categorize the obtained mutants by the number of simple changes one has to introduce to form them. That is, \emph{first-order mutants} (FOM) is obtained by making only one simple syntactic change to the original program. Second-order mutants (SOM) are obtained by making two syntactic changes to the original program (or applying one mutation to first-order mutants). In the general case, higher-order mutants (HOM)~\cite{jia2009} are produced after the successful application of \textit{n} mutations to the original program. At the very beginning, using higher-order mutants in mutation testing was not considered viable because of the \emph{Coupling Effect} proposed by DeMillo et al. \cite{demillo1978}. It stated that ``Test data that distinguishes all programs differing from a correct one by only simple errors is so sensitive that it also implicitly distinguishes more complex errors''. However, later on, \citet{offut1992} defined first-order mutants as simple faults while characterizing higher-order mutants as complex artificial defects. In this study, we plan to use second-order mutants as the means for studying whether mutants located outside the commit change interacts with the mutants located within the change. Then we use this information to determine if mutants are relevant or not for given commit changes. Details are presented later in Section~\ref{sec:approach}. \begin{figure}[bt] \centering \includegraphics[scale=0.30,trim={0cm 3.5cm 0cm 3.5cm},clip]{figures/Figure_program_evolution_v_3.pdf} \caption{\revise{Typical evolution of a software and its test suite showing three versions ($v_1$ to $v_3$) of a program (\texttt{main}) and and its test suite (\texttt{test}). The {\color{green} green} portions of the program (\texttt{main}) symbolize the \textit{program changes} (e.g., a commit), and the explosions symbolize the \textit{mutants} injected into the program. In the test suite (\texttt{test}), $t_i$ symbolizes a \textit{test case} $i$, and the {\color{green} green} rectangles represent changes in the test suite (i.e., addition and modification of tests). The test suite and source code evolve as the program evolves through versions. As the size of the program increases, we can observe that the number of mutants increases as well. This eventually leads to a substantial number of irrelevant mutants that result in waste of efforts. In the figure, with {\color{red} red} the mutants that are commit-relevant and with {\color{yellow} yellow} the irrelevant ones. Focusing only on commit-relevant mutants reduces the number of mutants requiring attention and leads to significant cost reductions. Additionally, the set of commit-relevant mutants quantifies the extent to which practitioners have tested the program behaviors affected by the change. } } \label{fig:testrig} \end{figure} \subsection{Testing Evolving Systems} Software systems evolve frequently, hence, it is pertinent to provide methods and tools to analyze the impact of the program changes. \emph{Regression testing} helps in this respect by re-running the test suite on the new version of the code to ensure that the previously developed functionality behaves as expected. Software evolves for many reasons (e.g., due to bug fixes, code refactoring or new features). Therefore it is important to understand how to test the program change, if it is enough to test only the changed lines, as well as how many test requirements and test cases will need to be analyzed. \revise{Notably, developers are burdened with the challenge of testing evolving systems, specifically, how to effectively analyse the difference in the program behaviors induced by their changes. These are the main challenges of regression testing, and in this work, we aim to study these challenges via the lens of mutation testing.} \revise{Generally, as the software evolves, the test suite also evolves. Concretely, as the program changes (e.g., due to new features or bug fixes), new tests are added or old tests may be modified to exercise those changes. Figure \ref{fig:testrig} illustrates the evolution of a program and its test suite during a typical software development process, showing changes in four versions of the program (\texttt{main}) and the test suite (\texttt{test}). In this example, we illustrate that analyzing all mutants is costly, as the number of mutants (both red and yellow in \autoref{fig:testrig}) is independent of the program changes (is actually depended on the size of the programs) and increases as the program size increases. Hence, traditional mutation testing will be costly, since it uses more mutants than required. More importantly, by doing so, developers will have to analyze mutants that are not relevant to what they actually committed. In this work, we study how to address these challenges using commit-aware mutation testing. } A common approach to address these challenges is to leverage code coverage information, i.e., analyzing the test coverage of a particular change, to decide if the change needs further test cases or not. However, previous works~\cite{Fowler,KurtzAODKG16} have shown that many severe integration issues arise from unforeseen interactions triggered between introduced change and the rest of the software. \revise{Therefore, there is a need for change-aware test metrics to guide effective regression testing and allow developers to quantify the extent to which they tested the error-prone program behaviors affected by their changes.} We plan to use mutation testing to address these interactions by targeting suitable mutants that demonstrate an (implicit) interaction between the changed lines and the unmodified part of the program (i.e., the code outside the change). \revise{These mutants form the change-relevant requirements and should be used to determine whether test suites are adequate and provide guidance in improving the test suite.} \section{Conclusion}\label{sec:conclusion} We presented an empirical evaluation of the characteristics of commit-relevant mutants. In particular, we have studied the prevalence, location, effectiveness, and efficiency of commit-relevant mutants. We have also examined the comparative advantage of commit-relevant mutants compared to two baseline methods, i.e., random mutant selection and selecting mutants within program changes. Notably, we found that commit-relevant mutants are \textit{highly prevalent} (30\%), and primarily located outside of program changes (81\%). In addition, we observed that effective selection of commit-relevant mutants affords a significant testing advantage. Specifically, it has the potential of significantly reducing the cost of mutation, and it is significantly more effective and efficient than random mutant selection and analysis of only mutants within the program change. We also investigate the predictability of commit-relevant mutants by considering typical proxy variables (such as the number of mutants within a change, mutant type, and commit size) that may correlate with commit-relevant mutants. However, our empirical findings show that these candidate proxy features do not reliably predict commit-relevant mutants, indicating that more research is required to develop tools that successfully detect this kind of mutants. \section{Discussion}\label{Discussion} \subsection{Summary of Findings} Commit-relevant mutation testing allows developers to identify and select the mutants necessary for testing the program changes to avoid regression bugs and newly introduced failures. This paper presents an empirical study that examines the prevalence and characteristics of commit-relevant mutants and provides scientific insights concerning the mutation testing of evolving software systems. Our main empirical findings include the following: \begin{enumerate} \item Commit-relevant mutants, at unit level, are \textit{highly prevalent} (30\%) and most commit-relevant mutants (81\%) are \textit{located outside of program commit changes}. Hence, it is important to conduct mutation analysis of evolving systems to determine the influence of the program changes on the rest of the unmodified code. \item Adequate selection of (subsuming) commit-relevant mutants significantly reduces \revise{the number of mutants involved (approximately 93\%)}; thus, there is a huge benefit to developing effective and practical techniques for the selection of (subsuming) commit-relevant mutants in evolving systems. \item Predicting (subsuming) commit-relevant mutants is not a trivial task. In our evaluation, we studied several candidate \textit{proxy variables} that \emph{do not reliably predict} commit-relevant mutants, including the number of mutants within a change, mutant type, and commit size. Hence, we encourage the development of statistical or machine learning approaches and program analysis techniques to predict or identify commit-relevant mutants automatically. \item Selecting commit relevant mutants is \textit{significantly more effective and efficient than random mutant selection and the analysis of only mutants within the program change}. Commit-relevant mutation testing can reduce testing effort \revise{(i.e., number of test executions)} by up to \revise{16} times, and by half, compared to random mutant selection and mutants within a change, respectively. \end{enumerate} Firstly, our evaluation results show that most commit-relevant mutants located outside of the commit changes due to the interaction of changes with the unmodified program code. However, in our evaluation, commit-relevant mutants that capture evolving software behavior are located all around the program changes. Besides, we observe that effective selection of commit-relevant mutants significantly reduces the number of mutants requiring analysis. Thus, we encourage researchers to investigate automated methods for identifying and selecting commit-relevant mutants, for instance, using statistical analysis or program analysis. In addition, we observed that commit-relevant prediction and selection is a challenging task. For example, many proxy variables could not reliably predict commit-relevant mutants in our analysis (\RQ2 to \RQ4). To buttress this, we further conducted a correlation analysis of the features of commit-relevant and non-relevant mutants using control and data flow features selected from Chekam \textit{et al. }~\cite{ChekamPBTS20}. The goal is to determine if mutants' features previously used for other prediction tasks, for instance, for selecting fault revealing mutants ~\citet{ChekamPBTS20}, can also distinguish commit-relevant mutants. \autoref{fig:RQ4-features_correlation} presents our findings using a heat map, where each map coordinate represents Spearman correlation coefficient calculated between two features on the coordinates. These features characterize relevant and not relevant mutants, labeled with suffix "R" or "N", respectively. Notably, we observe that there are no strong positive or negative correlations among these features. This implies that these features can not directly help in distinguishing between commit-relevant and non-relevant mutants. However, we can observe two cases of a medium positive correlation between the same class features, in particular, \textit{CfgDepth} and \textit{NumInDataD} between both classes show correlation.\footnote{\textit{CfgDepth} means the depth of a mutant in the control flow graph, i.e., the number of basic blocks to follow to reach the mutant, and \textit{NumOutDataD} refers to the number of mutants on expressions on which a mutant $m$ is data-dependent.} This phenomenon is expected since there will be more data-dependent expressions as the depth of a mutant in the control flow graph increases. \begin{figure*}[bt!] \begin{center} \includegraphics[width=1.\textwidth]{figures/Heatmap_Mutants_properties_spearman.pdf} \caption{Correlation between features of relevant and non-relevant mutants labeled with suffixes ``R" and ``N", respectively. The features examined include the following: \texttt{CfgDepth} - \textit{Depth of a mutant in Control Flow Graph, i.e., the number of basic blocks to follow in order to reach the mutant}; \texttt{NumOutDataD} - \textit{Number of mutants on expressions data-dependent on a mutant expression}; \texttt{NumInDataD} - \textit{Number of mutants on expressions on which a mutant $m$ is data-dependent}; \texttt{NumOutCtrlD} - \textit{Number of mutants on expressions control-dependent on a mutant}; and \texttt{NumInCtrlD} - \textit{Number of mutants on expressions on which $m$ is control-dependent}. } \label{fig:RQ4-features_correlation} \end{center} \end{figure*} Furthermore, we found that commit-relevant mutant selection considerably improves the effectiveness and efficiency of testing evolving systems, especially in comparison to the random mutant selection, and using the mutants within the program changes (\RQ5 and \RQ6). Overall, these empirical findings shed more light on the challenge of mutation testing of evolving systems and provide directions for future research into the selection and prediction of commit-relevant mutants. \subsection{Implications} \revise{ The main insight of our study is \textit{the need to pay attention to the effective identification, selection or prioritization of commit-relevant mutants}. This is particularly important to reduce the effort required for mutation-based regression testing. Notably, an effective commit-aware mutant selection method can significantly reduce the number of mutants involved. We also shown that \textit{commit-relevant mutants are located both within and outside program changes}. Precisely, we demonstrate that beyond the committed changes, other program locations are also important for commit-aware mutation testing. Hence, it is important to identify the relevant program locations for commit-aware mutant injection. To achieve this, we encourage the use of program analysis techniques (e.g., slicing) that determines the program dependencies between changes and the rest of the program, such that mutant injection is focused on selecting such dependencies to effectively reduces the search space and cost for mutation testing. It is also pertinent to note that \textit{the subsumption relation of mutants can help in reducing considerably the effort during commit-aware mutation testing}. Indeed, it is important to prioritize subsuming mutants during mutation testing of evolving systems. } \revise{ To achieve the aforementioned goals, i.e., automate the identification and selection of commit-relevant mutants to aid developers, we turn to the research community to develop and investigate the techniques required for effective commit-aware mutation testing. Thus, the takeaway of this study is the need to develop: a) novel techniques for \textit{selecting, prioritizing and predicting commit-relevant mutants}; and b) \textit{commit-aware test metrics} to determine the adequacy of commit-aware mutation testing. Although the problem of mutant selection/identification of the relevant mutants is active for traditional mutation testing, this is hardly well-studied for commit-aware mutation testing. This is an important problem since several studies~\cite{ma2020commit, ma2021mudelta} (including this study) have demonstrated that traditional (random) mutation testing is significantly costly for evolving software. } \revise{ This paper has further illustrated that dynamic approaches (like observation slicing) can complement static or machine learning based approaches in effectively identifying commit-relevant mutants. We have also observed that commit-relevant mutants cannot be predicted using only the committed changes or program dependence properties. This implies that the current state-of-the-art is not generally applicable for commit-aware mutation testing in practice. Thus, for more effective approaches, we believe researchers need to consolidate the knowledge from several sources, including the commit difference, mutant properties, the semantic behavior of mutants, and the semantic divergence produced by the change. To this end, we encourage further investigation of the effectiveness of such techniques for commit-aware mutation testing, and the development of newer program analysis based approached (e.g., symbolic execution or search-based techniques) for identifying commit-aware mutants. } \revise{ Finally, previous research~\cite{ma2021mudelta} has shown that commit-aware mutation testing requires different test metrics from traditional mutation testing. Thus, we encourage the researchers to define new test metrics targeting the changes and their dependencies, and investigate their effectiveness for commit-aware mutation testing. Overall, we expect that addressing these challenges will reduce the performance gap between the state-of-the-art in traditional mutation testing and commit-aware mutation testing. } \section{Experimental Setup}\label{Setup} \subsection{\revise{Goals}}\label{exp-goals} \revise{ The main goal of our study is to investigate the prevalence and characteristics of commit-relevant mutants in evolving software systems in terms of their program location and relationship to \textit{commit hunks} and \textit{mutant types}. We also study their effectiveness and efficiency in testing evolving systems in comparison to the state-of-the-art. Specifically, our empirical goal is to achieve the following three main goals: \begin{enumerate} \item study the \textit{properties of commit-relevant mutants}, in terms of their prevalence, mutant types, location and proportions, as well as the\textit{ subsumption relation of commit-relevant mutants} (RQ1, RQ2 and RQ4); \item examine the \textit{relationship between commit-relevant mutants and commit properties} (e.g., commit size) (RQ3); \item investigate the benefit of commit-relevant mutation testing, in terms of their \textit{effectiveness} and \textit{efficiency} in comparison to the baselines (RQ5 and RQ6). \end{enumerate} } \revise{ Overall, our study aims at providing insights on the properties of commit-relevant mutants and at demonstrating their importance and effectiveness in testing evolving systems. } \subsection{Research Questions}\label{rqs} As we aim at assessing the potential of mutation testing in evolving systems, we investigate the following research questions (\RQ s). \begin{description} \item[\RQ1] \textbf{Commit-Relevant Mutants:} What is the \emph{prevalence} of ``commit-relevant mutants'' among the whole set of mutants? \revise{ \begin{description} \item[\RQ1.1] How are commit-relevant mutants distributed in the program? \item[\RQ1.2] Are commit-relevant mutants located within or outside the developers' committed changes? \item[\RQ1.3] Is there any correlation between the number of commit-relevant mutants located within program changes and the number of commit-relevant mutants outside the changes? \end{description} } \item[\RQ2] \textbf{Subsuming Commit-Relevant Mutants:} What is the \emph{proportion} of ``subsuming commit-relevant mutants'', i.e., the number of commit-relevant mutants that subsumes other commit-relevant mutants, such that testing only these subsuming mutants is sufficient to test all other commit-relevant mutants? \item[\RQ3] \textbf{Commit Size:} Is there a relationship between the \textit{size of the commit} (i.e., number of commit hunks) and the number of (subsuming) commit-relevant mutants? \item[\RQ4] \textbf{Commit-Relevant Mutant Types:} What is the \emph{distribution of mutant types} in commit-relevant mutants? \item[\RQ5] \textbf{Comparative Effectiveness: } How \textit{effective} are (subsuming) commit-relevant mutants, in comparison to the \textit{baselines} (i.e., random mutation and ``commit-only mutation'')? \item[\RQ6] \textbf{Test Executions: } What is the \textit{performance} of (subsuming) commit-relevant mutants in comparison to the \textit{baselines}, in terms of the number of \textit{required test executions}? \end{description} RQ1 aims at improving our understanding of the locations, prevalence, and number of relevant mutants in relation to committed changes. The answer to the question allows having a rough view of the relevant mutant's distribution within and outside committed code. Answering RQ2 will show the extent to which the relevant mutant sets have redundancies. Previous work \cite{PapadakisHHJT16} has shown that redundant mutants inflate mutation scores with the unfortunate effect of obscuring its utility. We, therefore, would like to validate whether relevant mutant sets also suffer from such inflation effects. RQs 3 and 4 analyze the relation between commit size and prevalence of mutant types in relevant mutant sets to check whether there are levels/thresholds at which relevant mutants do not yield much benefits. Finally, RQs 5 and 6 aim at quantifying the potential benefits of using relevant mutants during project evolutions concerning cost and effectiveness. \subsection{Analysis Procedure}\label{analysis_procedure} We focus our empirical study on commits of Java programs as selected subjects. To perform the mutation analysis, we employ Pitest\footnote{http://pitest.org/}~\cite{pitest}, one of the state-of-the-art Java mutation testing tools. We approximate the set of commit-relevant mutants by following the algorithm introduced in Section~\ref{sec:approach}. Besides the approximated set of commit-relevant mutants located outside of commit-change, we also record and consider as commit-relevant all those mutants residing on the location of commit-change (in our approach, \textit{$M_Y$} mutants). This corresponds to work done by \cite{petrovic2018}, whereas the commit-relevant mutants set is made out of mutants located on the commit diff, i.e., statements modified or added by commit. To make our approximation robust, we follow previous studies process steps \cite{KurtzAODKG16,ammann_establishing_2014,PapadakisK00TH19}. Our approach uses mutant-assertion matrices to identify mutants interactions that constitute, up to our knowledge, the first study conducted on test assertion level for Java programming language (bypassing standard tests passing/failing mutation behavior for Java programs). Mutant-assertion matrices were computed by running large test pools built by considering developer tests and adding automatically generated tests using EvoSuite\footnote{https://www.evosuite.org/}~\cite{FraserZ12}, a state of the art test case generation tool. From the computed mutant-assertion matrices, we obtain three sets of mutants: \textit{mutants on a change}, \textit{mutants relevant to a change} and \textit{mutants not relevant to a change}. To answer \RQ1 we study the prevalence and location of commit-relevant mutants in every commit by analyzing the average number of relevant/non-relevant mutants and their distribution. We address \RQ2 by studying the proportion of subsuming commit-relevant mutants among all commit-relevant mutants and all subsuming mutants. This will estimate an extra possible reduction we can achieve if we focus only on subsuming mutants. We consider traditional passing/failing test behavior to compute the set of subsuming mutants per subject (notice that this information is also captured when mutant-assertion matrices were built). To address \RQ3 and \RQ4, we perform a similar statistical analysis. Still, we study any correlation between the number of commit-relevant mutants and the size of commit hunks, and the type of mutants. In \RQ5 and \RQ6, we simulate a mutation testing scenario where the tester starts by picking a mutant for analysis for which a test to kill it is developed. During this simulation, for each analyzed mutant, we randomly pick the test to kill it from the pool and compute which other mutants are collaterally killed by the same test. The process proceeds by picking a survived mutant until every mutant has been killed. We consider a mutant as equivalent if there is no test in the pool that kills it. This kind of simulation has been used in various related works to assess the effectiveness of mutation testing techniques~\cite{KurtzAODKG16,ammann_establishing_2014,PapadakisK00TH19,ma2020commit}. We consider four different mutant selection techniques when answering \RQ5 and \RQ6. Two of them we use as \emph{baselines}, where one consists of \emph{randomly} selecting \revise{from the set of all} mutants, and the other one consists of selecting only the mutants on the change. Another selection technique consists of selecting from the pool of commit-relevant mutants, while the last technique consists of selecting subsuming commit-relevant mutants. We aim to obtain the best-effort evaluation by maximizing effectiveness and minimizing the effort. We focus on the first 20 mutants picked by a tester to test commit changes, while we measure effectiveness in terms of the \emph{commit-relevant mutation score} reached by the selected mutants that guide the testing process. Simultaneously, we measure the computational effort in terms of the number of \emph{test executions} required to accomplish the same effect over the different baselines (different mutants pools). \revise{In this simulation, we are interested in the test executions with the tests derived by the analysed mutants. The dependent variable is the test sets, while the independent variable is the test executions.} We iterate the process (killing all selected mutants) 100 times and compute the relevant mutation score and computation effort. \subsection{Subject Programs and Commits}\label{subject_programs} We focus our empirical study on commits of a set of well-known, well-tested, and matured Java open-source projects taken from Apache Commons Proper repository\footnote{https://commons.apache.org}. The process of mining repositories, data analysis, and collection, was performed as follows: \begin{enumerate} \item Our study focuses on the following projects: \texttt{commons-collections, commons-lang, comm\\ons-net, commons-io, commons-csv}. These projects differ in size while having the most extended history of evolution. We extracted commits from the year 2005 to 2020. \revise{To extract commit patches and hunks in our setup, we employ \texttt{PyDriller}\footnote{\url{https://pydriller.readthedocs.io/en/latest/intro.html}} (\texttt{V1.15}) to mine commits from the selected projects\footnote{\texttt{PyDriller} is an open-source Python framework that helps developers mine software repositories and extract information given the GIT URL of the repository of interest.}. We applied \texttt{PyDriller} to query the project's information such as commits hash id, modifications date, modified source code, modification operation, and hunks of the commits and quickly exported such information into a JSON file.} \item We kept only commits that use JUnit4+\footnote{https://junit.org/junit4/} as a framework to write repeatable tests since it is required by EvoSuite~\cite{FraserZ12}, the test generation tool we use for automatically augmenting test suites. \item We filtered out those commits that do not compile, do not have a green test suite (i.e., some of the tests are failing), or do not affect a program's source code (i.e., commits that only change configuration files). Some commits with failing tests are filtered out since Pitest requires a green test suite to perform mutation testing analysis. \item Due to the significant execution time for commits containing several files, we set a limit for 72h of execution on a High-Performance Computer to generate and execute mutants per commit. Please note that the test suites contain developer-written and automatically generated tests, where both are used to create mutation matrices. All experiments were conducted on two nodes with 20 physical cores and 256GB of RAM. Specifically on Intel Skylake Xeon Gold 2.6GHz processors, running on Linux Ubuntu OS across four threads. \end{enumerate} Overall, we generated 9,368,052 high-order mutants and 260,051 first-order mutants, over 288 commits, that required 68,213 CPUs days of execution. Table \ref{tab:subjects} summarises the details of the mined commits. Column ``\# Commits'' reports the number of commits mined per project, column ``\# LOC'' (Lines Of Code) indicates a subject scope in terms of lines of code, ``Maturity" reports on the date of first commit, column ``\# FOM'' (First-Order Mutant) indicates the total number of First Order Mutants generated for those commits, ``\#Mutants on Change'' indicates the number of First Order Mutants generated on the changed lines, column ``\#HOM'' (High-Order Mutant) indicates the total number of High Order Mutants generated, column ``\# Dev. Tests'' (Developer written Tests) reports on the number of developer written test cases, and column ``\# Evosuite Tests'' reports on the number of automatically generated tests. {\Large \begin{table}[!bt] \centering \caption{Details of Subjects Programs and Studied Commits} \label{tab:subjects} \scalebox{.9}{ \begin{tabular}{l r r r r r r r r r r} \toprule \textbf{\scriptsize{Commons Projects}} & \textbf{\scriptsize{\# LOC}} & \textbf{\scriptsize{\# Maturity}} & \textbf{\scriptsize{\# Commits}} & \textbf{\scriptsize{\# FOM}} & \textbf{\scriptsize{\# Mutants on Change}} & \textbf{\scriptsize{\# HOM}}& \textbf{\scriptsize{\# Dev. Tests}} & \textbf{\scriptsize{\# EvoSuite Tests}} \tabularnewline \midrule \scriptsize{collections} & \scriptsize{74,170} & \scriptsize{14/04/2001} & \scriptsize{45} & \scriptsize{27,417} & \scriptsize{2,026} & \scriptsize{1,192,188} & \scriptsize{4,797} & \scriptsize{1,285} \tabularnewline\midrule \scriptsize{io} & \scriptsize{29,193} & \scriptsize{25/01/2002} & \scriptsize{30} & \scriptsize{24,970} & \scriptsize{1,115} & \scriptsize{668,448} & \scriptsize{914} & \scriptsize{286} \tabularnewline\midrule \scriptsize{text} & \scriptsize{22,933} & \scriptsize{11/11/2014} & \scriptsize{46} & \scriptsize{47,847} & \scriptsize{4,155} & \scriptsize{2,073,829} & \scriptsize{1,084} & \scriptsize{322} \tabularnewline\midrule \scriptsize{csv} & \scriptsize{4,844} & \scriptsize{25/01/2002} & \scriptsize{101} & \scriptsize{66,862} & \scriptsize{3,577} & \scriptsize{1,968,137} & \scriptsize{6,144} & \scriptsize{2,833} \tabularnewline\midrule \scriptsize{lang} & \scriptsize{85,709} & \scriptsize{19/07/2002} & \scriptsize{66} & \scriptsize{102,072} & \scriptsize{3,891} & \scriptsize{3,885,341} & \scriptsize{7,574} & \scriptsize{959} \tabularnewline\midrule \textbf{\scriptsize{Total}} & \scriptsize{216,489} & \scriptsize{N/A} & \textbf{\scriptsize{288}} & \textbf{\scriptsize{269,168}} & \textbf{\scriptsize{14,764}} & \textbf{\scriptsize{9,787,943}} & \textbf{\scriptsize{20,513}} & \textbf{\scriptsize{5,685}} \tabularnewline\midrule \bottomrule \multicolumn{9}{l}{\footnotesize \textit{ ``\# LOC'' - Lines Of Code, ``\# FOM'' - First Order Mutants, ``\# HOM'' - Higher Order Mutants, ``\# Dev. Tests'' - Developer written Tests} }\\ \end{tabular} } \end{table} } \subsection{Metrics and Measurements}\label{metrics} \textbf{Statistical Analysis:} To answer our research questions, we performed several statistical analyses to evaluate correlations among several variables. For instance, in \RQ1, we analyzed whether the number of commit-relevant mutants correlates with the number of mutants residing on a change and whether the number of subsuming commit-relevant mutants correlates with the number of subsuming mutants. In this study, we employ \revise{two} correlation metrics, namely \textit{Kendall rank coefficient ($\tau$) (Tau-a)}, \revise{and \textit{Spearman's rank correlation coefficient ($\rho$ - (rho)) }}, with the level of statistical significance set-up to $p-value$ 0.05. The Kendall rank coefficient ($\tau$), measures the similarity in the ordering of studied scores, while \revise{Spearman's $\rho$ (rho) measures how well the relationship between two variables can be described using a monotonic function \cite{myers2004spearman}.} \revise{The correlation metrics calculate values between -1 to 1, where a value close to 1 or -1 indicates strong correlation, while a value close to zero indicates no correlation at all. } Additionally, to facilitate comprehension of our figures, we employed \textit{coefficient of determination} (R$^2$ trendline) as a statistical measure that describes the proportion of the variance in the dependent variable that is predictable from the independent variable(s). \smallskip\noindent \textbf{Mutation-specific Measures:} We also employed mutation-specific metrics such as \textit{the commit-relevant mutation score} and \textit{subsuming commit-relevant mutation score}, to measure the effectiveness and efficiency of the selected mutants that guide the testing process. \revise{We measure how the test suite effectiveness progresses when we analyze mutants from the different mutant sets (e.g., all mutants, relevant mutants, subsuming relevant, etc.). Similarly, we measure efficiency by counting the number of test executions involved (to identify which mutants are killed by the test suites) when test suite progresses.} \subsection{Implementation Details} \label{subsection:implementation_details} Our commit-relevant mutant identification approach is implemented in approximately 5 KLOC of Python code, ~600 LOC in Shell scripts and 3 KLOC of Java. It employs several external tools and libraries including \texttt{Evosuite}, \texttt{git-diff }and \texttt{PitTest}. We have also implemented additional infrastructure on \texttt{PitTest} to ensure analysis of evolving software and extract assertion information. In the following, we describe each of these tools. \subsubsection{\texttt{EvoSuite \revise{(V1.1.0)}}} To obtain a rich test suite for our study, we collected developer-written tests and automatically generated tests. For our mutation testing analysis, we augment developers' test suites with test cases automatically generated with \texttt{EvoSuite}~\cite{FraserZ12}. \texttt{EvoSuite} is an evolutionary testing tool that generates unit tests for Java software. In our analysis, we run \texttt{EvoSuite} against all several coverage criteria (e.g., line, branch, mutation, method, etc.); we also executed \texttt{EvoSuite} with default configurations, especially concerning running time. \subsubsection{\texttt{Pitest (\revise{V1.5.1})} and \texttt{git-diff}} Pitest does not have built-in functionality to satisfy the requirements of our experiment. Therefore, we extended the framework for High Order Mutants~\cite{Laurent} on top of Pitest that takes as an input the \texttt{gitdiff} output\footnote{https://git-scm.com/docs/git-diff}. Based on the statement difference between the versions, the framework extends the mutants generation functionality by generating, i.e., mapping, mutants on the change, with the mutants around the change. Thus, creating second-order mutants for that particular commit file. Our framework is configured to generate the extended set of mutants available in Pitest, introduced by Laurent \textit{et al. } \cite{LaurentPKHTV17}. Kintis \textit{et al. } \cite{KintisPPVMT18} has also shown that this extended set of mutants is more powerful than the mutant sets produced by other mutation testing tools. \subsubsection{\texttt{Pitest Assert}} \label{sec:pitest-assert-tool} \texttt{Pitest (V1.5.1)} creates killing matrices and identifies whether a mutant is killed or not, based on test case oracle prediction (test fails or passes). These matrices were not suitable for our experimental procedure. Therefore, we built a framework on top of Pitest to extract additional information concerning each test case assertions (from tests that cover mutants). Our framework performs bytecode instrumentation of each test executed on a specific mutant, using ASM\footnote{https://asm.ow2.io/} as an all-purpose Java bytecode manipulation and analysis framework. By instrumenting each test case assertion, we can obtain execution information. More precisely, each assertion has a unique test name where it locates, assertion function name, assertion line number, and assertion actual execution value. If an assertion triggers an exception, we keep track of the stack-trace execution. However, for this study's purpose, we disregard the assertions that trigger the exception from our relevant mutants calculation (please refer to Algorithm \ref{algo:relevant}) since we only aim at actual mutants' observable behavioral output. Hence, the mutant-assertion matrix is a weighted matrix. For each (mutant, test-assertion) pair, the value corresponds to the actual assertion value obtained by running the test on the mutant, or the exception stack trace if an assertion throws an exception. \revise Concretely, we employ the \textit{JUnit4}\footnote{https://junit.org/junit4/} testing framework which contains a public class (called \texttt{Assert}) that provides a set of assertion methods to specify test conditions. Typically, these methods (e.g., \texttt{Assert.assertEquals(expected value, actual value)}) directly evaluate the assertion's conditions, then returns the final assertion's output (e.g., conditions not satisfied, pass, or fail). To obtain the value of parameters within the assert statement, in our framework, we use \texttt{Pitest Assert} to instrument each assertion method. Such that we serialize the provided input values in the assert statement before they propagate to conditional checks, i.e., before the conditional check is reached in \textit{org.junit.Assert\footnote{https://junit.org/junit4/javadoc/4.13/org/junit/Assert.html}} and the output values are fed to \textit{org.hamcrest.Matcher\footnote{http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html}} for evaluation. Specifically, we serialize both the expected and actual values after they propagate as input parameters of the assert statement. This allows to assess the input parameters of the \texttt{assert} statement (e.g., an expression or a method call (\texttt{assertEqual(foo(), bar())})) for concrete values. Hence, in our setup, we compare the output values of both the expected and actual values present in each assertion. However, our experimental framework does not directly account for the potential dependencies within assertions and test cases, we address this concern in the \textit{threats to validity} (\textit{see} \autoref{ValidityThreats}). Our test assertion framework is built on top of \texttt{PiTest} and is publicly available. } \subsection{Research Protocol}\label{protocol} \autoref{fig:Process_pipeline} highlights our experimental protocol which proceeds as follows: For each project (e.g., \textit{commons-collections}) and each mined commit (e.g., hash: \textit{03543e5f9}, we first \textit{augment the developers' test suite} with automatically generated tests using EvoSuite~\cite{FraserZ12}. Next, we \textit{obtain the commit changes} (a.k.a hunks) of the commit using the \texttt{git-diff} tool, in order to identify the changed and unchanged program statements. We then \textit{generate both first-order and second-order mutants} for the program, using Pitest Assert as our extension of Pitest Mutation Testing tool~\cite{pitest}. After mutant generation, we \textit{execute every mutant to obtain the mutant-assertion matrices}, which provides information about test assertion type, position and value. Finally, we execute our relevant mutant detection algorithm~\ref{algo:relevant} to identify commit-relevant mutants. \begin{figure}[bt!] \begin{center} \includegraphics[width=0.95\textwidth,trim={0cm 8cm 0cm 7cm},clip]{figures/Process_pipeline_v3.pdf} \caption{Research Protocol} \label{fig:Process_pipeline} \end{center} \end{figure} Our result analysis proceeds after computing mutant-assertion matrices and identifying commit-relevant mutants. We then perform the data gathering and analysis required to answer every research question (\RQ s). In particular, we compute subsuming mutant relations necessary to answer \RQ2, and perform the mutation testing simulation needed to answer \RQ5 and \RQ6. \section{Related Work}\label{related_work} In this section, we discuss closely related work in the areas of change impact analysis, regression testing, test augmentation, and commit-aware mutation testing. \smallskip \noindent \textbf{\textit{Program slicing:}} A related line of work regards the formulation of dynamic or observation-based slicing \cite{BinkleyH05, BinkleyHK07, BinkleyGHIKY14}. These techniques aim at identifying relevant program statements and not mutants. Though, they could be used in identifying relevant mutant locations, in which every located mutant could be declared as relevant. \revise{For instance, \citet{guimaraes2020optimizing} proposed the use of dynamic program slicing to determine the subsumption relations among mutants, in order to detect redundant mutants and reduce the number of tested mutants. In their evaluation, the authors demonstrate that using dynamic subsumption relation among mutants reduces mutation testing time by about 53\%, on average.} \revise{Similarly, \citet{delamaro2001interface} proposed interface mutation to reduce the mutation testing effort required during system integration. The goal of the paper is to apply interface mutants as a test adequacy criterion for system integration testing. The paper demonstrates that inter-procedural program slicing is applicable for mutation analysis, particularly for integration testing. Their approach leverages the data flow dependencies between two system units to determine the set of mutants that are relevant for the integration of both units.} This is because many non-killable or irrelevant mutants located in dependent statements will be considered as relevant. This is evident from the previously reported results of Binkley \textit{et al. } \cite {BinkleyH05, BinkleyHK07} that showing simple changed slices occupying 35-70\% of the entire programs. \smallskip \noindent \textbf{\textit{Change-Impact Analysis:}} It is important to analyze and test the impact of program changes on evolving software systems. To this end, researchers have proposed several automated methods to assess the impact of program changes on the quality of the software, e.g., in terms of correctness and program failures. For instance, researchers have employed \textit{program analysis} techniques (such as program slicing) to identify relevant coverage-based test requirements, specifically, by analyzing the impact of all control and data dependencies affected by the changed code to determine all tests that are affected by the change~\cite{RothermelH94,Binkley97}. Unlike these works, in this paper, we focus on performing change impact using commit-aware mutation testing, in particular, we empirically evaluate the properties, distribution and prevalence of (subsuming) commit-relevant mutants. \smallskip \noindent \textbf{\textit{Regression Testing:}} The field of regression testing investigates how to automatically generate test cases for evolving software systems to avoid regression bugs. Researchers have proposed several approaches in this field for decades~\cite{YooH12}. The closest work to ours is in the area of regression mutation testing~\cite{ZhangMZK12} and predictive mutation testing~\cite{0050ZHH0019, MaoCZ19}. The goal of regression mutation testing is to identify change-affected mutants (i.e., mutants on execution trace affected by changes), and incrementally calculate mutation score. Meanwhile, predictive mutation testing seeks to estimate the mutation score without mutant execution using machine learning classification models trained on different static features~\cite{MaoCZ19}. These approaches are focused on speeding up test execution and mutation score computation while testing evolving software systems. In contrast, in this paper, we focus on identifying the test requirements (mutants) relevant to the program changes. i.e., the mutants that need to be analyzed and tested by the engineer, and we provide a more refined and precise mutation testing score, specially adapted for commit-relevant mutants. \smallskip \noindent \textbf{\textit{Test Augmentation:}} This line of research aims to automatically generate additional test cases to improve the (fault revealing) quality of existing test suites. This is particularly important when a software system changes (often); hence, it is vital to generate new tests that exercise the program changes. Researchers have proposed several test augmentation approaches to trigger program output differences~\cite{QiRL10}, increase coverage~\cite{XuKKRC10} and increase mutation score~\cite{SmithW09JSS,SmithW09EMSE}. Some test augmentation approaches have been developed to address code coverage problems using propagation-based techniques~\cite{ApiwattanapongSCOH06,SantelicesCAOH08,SantelicesH10,SantelicesH11}. Other approaches employ symbolic execution for test augmentation by generating tests that exercise the semantic differences between program versions by incrementally searching the program path space from the changed locations and onwards, this includes approaches such as differential symbolic execution \cite{PersonDEP08}, KATCH \cite{MarinescuC13} and Shadow symbolic execution \cite{KuchtaPC18}. These techniques rely on dependency analysis and symbolic execution to decide whether changes can propagate to a user-defined distance by following the predefined propagation conditions. Hence they are considerably complex and computationally expensive, for instance, because they are limited by the state explosion problem of symbolic execution. These papers are complementary to our work since the aim is to generate additional tests to improve existing test suites. However, our work is focused on test augmentation to exercise code changes, albeit using mutation testing. \smallskip \noindent \textbf{\textit{Commit-Aware Mutation Testing:}} The goal of commit-aware mutation testing is to select mutants that exercise program changes in evolving software systems. The problem of commit-relevant test requirements has not been studied in depth by the mutation testing literature \cite{PapadakisK00TH19}. The closest work to ours in this area includes the formalization of commit-aware mutation testing~\cite{ma2020commit}, diff-based commit-aware mutant selection (i.e., mutants within program changes only)~\cite{petrovic2018}, and a machine learning-based mutant selection method~\cite{ma2021mudelta}. Petrovic \textit{et al. }~\cite{petrovic2018} presents a diff-based probabilistic mutation testing approach that is focused on selecting mutants within committed program changes only. Unlike this paper, this approach ignores the dependencies between program changes and the unmodified code. \texttt{Mudelta}~\cite{ma2021mudelta} presents a machine learning-based approach for selecting commit-relevant mutants. Ma \textit{et al. }~\cite{ma2020commit} defines commit-relevant mutants and evaluates their relationship with traditional mutation test criteria, emphasizing the importance of commit-aware mutation testing. Unlike these works, we conducted an in-depth empirical study to understand the characteristics of commit-relevant mutants to shed more light on their properties and provide scientific insights for future research in commit-aware mutation testing. In particular, in comparison to Ma \textit{et al. }~\cite{ma2020commit}, our work impose more generalizable and easy to fulfill requirements on the programs and test contracts. For instance, Ma \textit{et al. }~\cite{ma2020commit}, determines commit-aware mutants by comparing mutants test suites from both pre- and post-commits, under the assumption that the test contract is intact and remains the same across both program versions. However, this critical requirement considerably limits the application and adoption of the approach of Ma \textit{et al. }~\cite{ma2020commit} in practice. Our empirical study observed that test contracts frequently change across versions in evolving software systems (>60\%). \section{Experimental Results}\label{Results} \smallskip\noindent \subsection{\RQ1: Commit Relevant Mutants} We start by studying the proportion of \emph{commit-relevant mutants} that affect the commit changes out of \emph{all mutants} by using the pipeline just introduced in Section~\ref{sec:approach}. Thus, in this RQ, we consider as commit-relevant mutants all mutants identified by our approach, including the set of killable mutants residing on modified statements. We distinguish commit-relevant mutants in the categories of those located on changed and unchanged code to demonstrate This allows us to estimate the potential reduction in terms of the number of mutants requiring analysis and the number of test executions required to cover them if the tester focuses testing only on commit-relevant mutants instead of the whole set mutants, \revise{or on the mutant set consisting of all mutants residing on the modification}. Additionally, we evaluate the properties of commit-relevant mutants that can inform their selection among all mutants. Thus, we examine the location of commit-relevant mutants, whether they are mostly located within the commit or outside the committed changes. We also assess whether there is a correlation between the number of identified commit-relevant mutants and the number of commit-relevant mutants within the committed change to determine if the number of mutants within a commit can serve as a proxy to determine the number of commit-relevant mutants. {\Large \begin{table}[htp] \centering \caption{Details of the Prevalence of Commit-relevant Mutants. } \label{tab:prevalence-commit-relevant-mutants} \scalebox{.9}{ \begin{tabular}{l r r r r r r r} \toprule \textbf{\scriptsize{Project}} & \textbf{\scriptsize{\# Commits (C)}} & \textbf{\scriptsize{\# C. All R. M.}} & \textbf{\scriptsize{\# C. No R. M.}} & \textbf{\scriptsize{\# Relevant}} & \textbf{\scriptsize{\# Not Relevant}} & \textbf{\scriptsize{Ratio}} & \textbf{\scriptsize{Reduction Ratio}} \tabularnewline \midrule \scriptsize{commons-collections} & \scriptsize{45} & \scriptsize{2} & \scriptsize{4} & \scriptsize{6,833} & \scriptsize{18,558} & \scriptsize{32,31\%} & \scriptsize{67,69\%} \tabularnewline\midrule \scriptsize{commons-io} & \scriptsize{30} & \scriptsize{0} & \scriptsize{3} & \scriptsize{6,052} & \scriptsize{17,803} & \scriptsize{28,70\%} & \scriptsize{71,30\%} \tabularnewline\midrule \scriptsize{commons-text} & \scriptsize{46} & \scriptsize{1} & \scriptsize{4} & \scriptsize{8,810} & \scriptsize{34,882} & \scriptsize{27,10\%} & \scriptsize{72,90\%} \tabularnewline\midrule \scriptsize{commons-csv} & \scriptsize{101} & \scriptsize{4} & \scriptsize{0} & \scriptsize{27,441} & \scriptsize{35,844} & \scriptsize{47,39\%} & \scriptsize{53,61\%} \tabularnewline\midrule \scriptsize{commons-lang} & \scriptsize{66} & \scriptsize{1} & \scriptsize{2} &\scriptsize{15,724} & \scriptsize{82,457} & \scriptsize{19,22\%} & \scriptsize{80,78\%} \tabularnewline\midrule \textbf{\scriptsize{Total}} & \textbf{\scriptsize{288}} & \textbf{\scriptsize{8}} & \textbf{\scriptsize{13}} & \textbf{\scriptsize{64,860}} & \textbf{\scriptsize{189,544}} & \textbf{\scriptsize{N/A}} & \textbf{\scriptsize{N/A}} \tabularnewline\midrule \textbf{\scriptsize{Average}} & \textbf{\scriptsize{58}} & \textbf{\scriptsize{N/A}}& \textbf{\scriptsize{N/A}} & \textbf{\scriptsize{225}} & \textbf{\scriptsize{658}} & \textbf{\scriptsize{29,58\%}} & \textbf{\scriptsize{70,42\%}} \\ \hline \bottomrule \multicolumn{8}{l}{\footnotesize \textit{ ``\# C. All R. M.'' - Number of Commits with all relevant mutants, ``\# C. No R. M.'' - Number of Commits with no relevant mutants} }\\ \end{tabular} } \end{table} } \begin{figure*}[htp] \begin{center} \includegraphics[width=\textwidth]{figures/Box_plot_Distribution_sort_not_relevant.pdf} \end{center} \caption{Distribution of mutants across all commits showing the proportion of non-relevant mutants (in \textit{ \color{blue} blue}) as well as commit-relevant mutants within committed changes (in \textit{\color{red} red}) and outside committed changes (in \textit{\color{green} green}) } \label{fig:RQ1-Distribution_plot} \end{figure*} \begin{figure}[bt!] \centering \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Ratio_of_commit-relevant_mutants_located_within_a_change_scaled_100.pdf} \captionof{figure}{Proportion of commit-relevant mutants within the commit (18.56\%) and outside the commit (81.44\%)} \label{fig:RQ1-ratio_ouside_methods_i} \end{minipage}% \hspace{0.4cm} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Ratio_of_commit-relevant_mutants_located_within_changed_methods.pdf} \captionof{figure}{Proportion of commit-relevant mutants within the change method (30.05\%) and the outside changed methods (69.95\%) } \label{fig:RQ1-ratio_ouside_methods_ii} \end{minipage} \end{figure} \subsubsection{\textit{\textbf{RQ1.1: }\revise{What is the proportion of commit-relevant mutants out of all mutants?}}} \autoref{tab:prevalence-commit-relevant-mutants} and \autoref{fig:RQ1-Distribution_plot} illustrate the distribution of commit-relevant mutants among all mutants. In our evaluation, we found that \textit{only about one in three ($\approx$30\%) mutants are commit-relevant}, on average. In particular, we observed that only about 225 mutants are relevant to a commit out of 833 mutants, on average. \revise{This implies that an \textit{effective commit-aware mutation testing technique can reduce significant mutation testing effort, both computational when executing mutants and manual when analysing mutants. }} In addition, we found some (21) outliers in our analysis of commit-aware mutants, see columns ``\# C. All R. M.'' (Number of Commits with all Relevant Mutants) and ``\# C. No R. M.'' (Number of Commits with No Relevant Mutants): In particular, we found that only 2.8\% of commits (8) had 100\% commit-relevant mutants, this portrays the importance of mutant selection for evolving software systems. On the other hand, our evaluation results show that \revise{in 4.5\% of the commits (13) we found no commit-relevant mutants outside the change}; this suggests that it is pertinent to develop commit-aware mutation testing techniques that discern relevant from non-relevant mutants. Overall, these findings demonstrate the importance of developing commit-aware test selection for evolving software systems, in particular, in selecting relevant mutants to reduce testing effort. \begin{result} One in three (approximately 30\%) mutants are commit-relevant; hence, selecting commit-aware mutants can significantly reduce \revise{mutation testing cost}. \end{result} \subsubsection{\textit{\textbf{RQ1.2: }\revise{Where are commit-relevant mutants located in the program, i.e., how many commit-relevant mutants are within or outside the committed changes?}}} In our evaluation, most (81\%) commit-relevant mutants are outside of developers' committed changes (\textit{see} \autoref{fig:RQ1-ratio_ouside_methods_i}). Making only about one in five (19\%) commit-relevant mutants being within the committed changes of developers. For instance, a developer that tests \textit{all commit-relevant mutants within the changed method} will test only 30\% of commit-relevant mutants, and miss almost 70\% of commit-relevant mutants (\textit{see} \autoref{fig:RQ1-ratio_ouside_methods_ii}). This result suggests that to test the impact of developer changes on the program effectively, it is important to not only test within the committed changes. It is also highly pertinent to test the interaction of committed changes with the rest of the unmodified program. \begin{result} Most (81\% of) commit-relevant mutants are located outside of the commit, and \\only a few (19\% of) commit-relevant mutants are within the commit. \end{result} \begin{figure}[htp] \centering \begin{minipage}{.3\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Scatter_plot_correlations_relevant_mutants-mutants_on_change_spearman_kendall.pdf} \captionof{figure}{ \revise{ Correlation Analysis between the number \textit{mutants within a change} and the number of \textit{commit-relevant mutants}} \label{fig:RQ1-correlation_plot_i} \end{minipage}% \hspace{0.2cm} \begin{minipage}{.3\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Scatter_plot_correlations_not_relevant_mutants-mutants_on_change_spearman_kendall.pdf} \captionof{figure}{ \revise{ Correlation Analysis between the number of \textit{mutants within a change} and the number of \textit{non-relevant mutants}} } \label{fig:RQ1-correlation_plot_ii} \end{minipage} \hspace{0.2cm} \begin{minipage}{.3\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Scatter_plot_correlations_relevant_mutants-not_relevant_mutants_spearman_kendall.pdf} \captionof{figure}{ \revise{ Correlation Analysis between the number of \textit{non-relevant mutants} and \textit{commit-relevant mutants}} } \label{fig:RQ1-correlation_plot_iii} \end{minipage} \end{figure} \subsubsection{\textit{\textbf{RQ1.3: }\revise{Is there a correlation between the number of commit-relevant mutants and the number of mutants within the change?}}} Our evaluation results show that \textit{there is a weak trend between the number of commit-relevant mutants and the number of mutants within the commit}. Our statistical correlation analysis shows that there is a \textit{weak correlation} between both variables. \revise{In particular, we found a Spearman and Kendall correlation coefficients of 0.212 and 0.141, respectively. Indeed, both the Spearman and Kendall correlation coefficients are statistically significant (with p-values 0.0006 and 0.0007, respectively)}. \revise{Figures~\ref{fig:RQ1-correlation_plot_i}, \ref{fig:RQ1-correlation_plot_ii} and \ref{fig:RQ1-correlation_plot_iii} summarize the results of the different studied correlations.} These correlation results suggest that there is a weak relationship between the number of mutants within a change and the number of commit-relevant mutants, but \textit{no robust and predictable pattern or trend between both variables}. This implies that \textit{the number of mutants within the commit can not reliably predict the number of commit-relevant mutants} (in unmodified code regions), and vice versa. \begin{result} There is a statistically significant weak positive correlation between the number of commit-relevant mutants and the number of mutants within the change (\revise{Spearman} and Kendall correlation coefficients of \revise{0.212} and 0.141, respectively). \end{result} \smallskip\noindent \subsection{\RQ2: Subsuming Commit Relevant Mutants} In this section, we investigate the prevalence of \emph{subsuming commit-relevant mutants} among \emph{commit-relevant mutants}. Estimating the proportion of subsuming commit-relevant mutants is important to demonstrate the further reduction (in number of mutants to analyse and test executions) achieved by ``selecting" or ``optimizing'' for effectively identifying \emph{subsuming commit-relevant mutants}, in comparison to \emph{commit-relevant mutants}, \emph{subsuming mutants} and \emph{all mutants}. The two subsumption relations (i.e., one for the commit-relevant mutants and the other one for all mutants) are computed by following the definition introduced in Section~\ref{sec:subsuming_mutants}. Additionally, we examine the correlation between the number of subsuming commit-relevant mutants and the number of commit-relevant mutants within a change and subsuming mutants; this is important to determine if these variables are related can predict or serve as a proxy for determining subsuming commit-relevant mutants. \begin{figure*}[htp] \begin{center} \begin{minipage}{.45\textwidth} \centering \vspace{-0.55cm} \includegraphics[width=1.0\linewidth]{figures/venn_diagram_proportions.pdf} \captionof{figure}{Venn diagram showing the proportion of ``commit-relevant mutants'' (29.58\% in \textit{\color{orange} orange})) and ``subsuming commit-relevant mutants'' (6.13\% in \textit{\color{purple} purple}) among all mutants (in \textit{\color{pink} pink}).} \label{fig:venn_3a_categories_i} \end{minipage}% \hspace{0.2cm} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Venn_diagram_Categories_numbers.pdf} \captionof{figure}{Venn diagram showing the number and intersections among ``commit-relevant mutants within commit changes'' (in \textit{\color{blue} blue}),``subsuming commit-relevant mutants'' (in \textit{\color{orange} orange}) and ``subsuming mutants'' (in \textit{\color{pink} pink}). } \label{fig:venn_3a_categories_ii} \end{minipage} \end{center} \end{figure*} \textit{What is the proportion of ``subsuming commit-relevant mutants'' among commit-relevant mutants, such that a test suite that distinguishes a(ll) subsuming commit-relevant mutant(s) covers (all) other commit-relevant mutants?} \autoref{fig:venn_3a_categories_i} illustrates the proportion of \emph{subsuming commit-relevant mutants} and their intersection with \emph{commit-relevant mutants} as well as all mutants. In our evaluation, we found that \textit{``subsuming commit-relevant mutants'' are significantly smaller than commit-relevant mutants and all mutants}. About one in 20 mutants is a \emph{subsuming commit-relevant mutant}, and about one in five (5) commit-relevant mutants is a subsuming commit-relevant mutant. Specifically, ``subsuming commit-relevant mutants'' represent 20.72\% and 6.13\% of all commit-relevant mutants and all mutants, respectively. This suggests it is worthwhile to identify and select subsuming relevant mutants from all (commit-relevant) mutants. Invariably, generating only subsuming commit-relevant mutants reduces the number of mutants to analyze by 79\% and 93\% compared to generating commit-relevant mutants and all mutants, respectively. This result implies that developing automated mutation testing methods that effectively identify, select or generate subsuming commit-relevant mutants can significantly reduce \revise{mutation testing cost}. \begin{result} Selecting ``subsuming commit-relevant mutants'' can reduce the number of mutants to be considered by about 79\% and 93\% in comparison to commit-relevant mutants and all mutants, respectively. \end{result} \textit{What is the proportion of ``subsuming commit-relevant mutants'' among ``subsuming mutants'' and ``commit-relevant mutants within a change''?} \autoref{fig:venn_3a_categories_ii} illustrates the intersections between all three types of mutants. Notably, \textit{most (92.98\% -- 18,117 out of 19,484) subsuming commit-relevant mutants are subsuming mutants as well, and they represent 26.42\% of all subsuming mutants (68,553)}. This implies that searching for subsuming commit-relevant mutants among subsuming mutants (instead of all mutants) is beneficial in reducing the search scope. We also observed that all subsuming commit-relevant mutants within committed changes are subsuming mutants. Meanwhile, about one in five (19.36\% -- 3,772 out of 19,484) subsuming commit-relevant mutants are within the developers' committed changes; they represent 28.38\% (3,772 out of 13,290) of all mutants within the change. This suggests that less than one in three mutants within the change are subsuming commit-relevant mutants. Hence, it is important to search for subsuming commit-relevant mutants outside of the committed changes since most subsuming commit-relevant mutants (81\%, 15,772) are outside the committed changes. \begin{result} Most (92.98\% of) subsuming commit-relevant mutants are subsuming mutants, while a few (19.36\% of) subsuming commit-relevant mutants are located within committed changes. \end{result} \begin{figure*}[htp] \begin{center} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Scatter_plot_correlations_minimal_relevant_mutants-mutants_on_change_spearman_kendall.pdf} \captionof{figure}{ \revise{ Correlation Analysis between the number mutants within a change and the number of subsuming commit-relevant mutants} \label{fig:RQ2-correlation_plot_i} \end{minipage}% \hspace{0.2cm} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Scatter_plot_correlations_minimal_relevant_mutants-minimal_mutants_spearman_kendall.pdf} \captionof{figure}{ \revise{ Correlation Analysis between the number of subsuming mutants and the number of subsuming commit-relevant mutants} } \label{fig:RQ2-correlation_plot_ii} \end{minipage} \end{center} \end{figure*} \textit{Is there a correlation between the number of subsuming commit-relevant mutants and the number of mutants within a change?} Our correlation analysis shows that \textit{there is a weak positive correlation between the number of commit-relevant mutants within a change and the number of subsuming commit-relevant mutants} (\textit{see} \autoref{fig:RQ2-correlation_plot_i}). \revise{Both Spearman and Kendall correlation coefficients report a weak positive correlation, with correlation coefficients 0.222 and 0.148, respectively, (\textit{see} \autoref{fig:RQ2-correlation_plot_i}).} \revise{In particular, the correlation coefficients are statistically significant with p-values less than 0.05, specifically, 0.0003 and 0.0004 for Spearman and Kendall coefficients, respectively}. This result suggests that the number of mutants within a change can not strongly predict the number of \revise{subsuming commit-relevant mutants}; hence, it is important to identify all commit-relevant mutants that interact with the committed changes, and not only test the change itself. \begin{result} The number of mutants within a change can not reliably predict the number of subsuming commit-relevant mutants since there is only a weak positive correlation between both variables. \end{result} \begin{figure*}[bt!] \begin{center} \includegraphics[width=\textwidth]{figures/Chart_14.pdf} \caption{Distribution of the proportion of commit-relevant mutants (in \textit{\color{gray} gray}) and subsuming commit-relevant mutants (in \textit{\color{red} red}); Commits are sorted from left to right in ascending order of the proportion of subsuming relevant mutants } \label{fig:RQ2-Distribution_minimal_relevant} \end{center} \end{figure*} \textit{What is the relationship between the number of subsuming commit-relevant mutants and the number of subsuming mutants?} \autoref{fig:RQ2-correlation_plot_ii} illustrates the distribution and correlation between the number of subsuming mutants and the number of subsuming commit-relevant mutants. In this figure, the trending line shows that \textit{there is a moderate positive correlation between both variables}. \revise{Indeed, both Spearman and Kendall correlation coefficients reports a \textit{moderate positive relationship} between both variables, with correlation coefficients 0.476 and 0.368, respectively, (\textit{see} \autoref{fig:RQ2-correlation_plot_ii}). The correlation coefficients also show that the positive relationship is statistically significant (p-value < 0.05)}. As expected, we observed that the proportion of subsuming relevant mutants per commit increases (trendline $R^2$=0.881) as the proportion of commit-relevant mutants increases (\textit{see} \autoref{fig:RQ2-Distribution_minimal_relevant}). Overall, this result implies that these variables can serve as a proxy to each other, hence predicting one variable could help identify the other. In particular, this implies that selecting subsuming mutants significantly increases the chances of selecting subsuming commit-relevant mutants. \begin{result} There is a moderate positive relationship between the number of subsuming commit-relevant mutants and the number of subsuming mutants, such that one can predict the other and vice versa. \end{result} \smallskip\noindent \subsection{\RQ3: Commit Size} In this section, we investigate if there is a relationship between the number of (subsuming) commit-relevant mutants and the size of the commit, measured in terms of the number of commit hunks. In particular, we pose the following question: \textit{Is there a relationship between the number of commit hunks and the number of (subsuming) commit-relevant mutants?} \autoref{fig:RQ3-distribution_hunks_i} illustrates the relationship between the number of commit-relevant mutants and the number of commit hunks. For commit-relevant mutants, we found that the number of \emph{commit-relevant mutants} (moderately) \emph{increases} (trendline $R^2$=0.125) as the number of commit-hunks increases. This implies that there is \emph{positive direct relationship} between the size of the commit and the number of \emph{commit-relevant mutants}. However, \autoref{fig:RQ3-distribution_hunks_ii} shows that the number of \emph{subsuming commit-relevant mutants} (moderately) \emph{decreases} (trendline $R^2$=0.023) as the number of commit-hunks increases. These results suggest that there is an \emph{indirect relationship} between the size of the commit and the number of \emph{subsuming commit-relevant mutants}. The size of the commit does not directly predict the number of subsuming commit-relevant mutants. Indeed, the number of \emph{subsuming commit-relevant mutants} decreases as the average size of the commit increases. Overall, this result demonstrates the effectiveness and importance of \emph{subsuming commit-relevant mutants} in reducing testing effort, even for large commit changes. \begin{result} The number of ``commit-relevant mutants'' increases as the size of the commit increases; however, the number of ``subsuming commit-relevant mutants'' decreases as the size of the commit increases. \end{result} \begin{figure*}[htp] \begin{center} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Chart_18.pdf} \captionof{figure}{Average Number of Commit-relevant mutants per commit \label{fig:RQ3-distribution_hunks_i} \end{minipage}% \hspace{0.2cm} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Chart_19.pdf} \captionof{figure}{Average Number of Subsuming Commit-relevant mutants per commit} \label{fig:RQ3-distribution_hunks_ii} \end{minipage} \end{center} \end{figure*} \begin{figure*}[bt!] \begin{center} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/commit_relevant_operators_distribution.pdf} \captionof{figure}{Prevalence of Commit-relevant Mutant Types \label{fig:RQ4-test_mutants_operators} \end{minipage}% \hspace{0.2cm} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/subsuming_relevant_operators_distribution.pdf} \captionof{figure}{Prevalence of Subsuming Commit-relevant Mutant Types} \label{fig:RQ4-test_sub_mutants_operators} \end{minipage} \end{center} \end{figure*} \begin{figure*}[bt!] \begin{center} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Histogram_Ratio_of_relevant_mutants_operators.pdf} \captionof{figure}{Ratio of Commit-relevant Mutants over All Mutants per Mutant Type \label{fig:RQ4-ratio_relevant_mutants_operators} \end{minipage}% \hspace{0.2cm} \begin{minipage}{.45\textwidth} \centering \vspace{-0.4cm} \includegraphics[width=1.0\linewidth]{figures/Histogram_Ratio_of_subsuming_relevant_mutants_operators.pdf} \captionof{figure}{Ratio of Subsuming Commit-relevant Mutants over All Mutants per Mutant Type} \label{fig:RQ4-ratio_sub_mutants_operators} \end{minipage} \end{center} \end{figure*} \smallskip\noindent \subsection{\RQ4: Commit-relevant Mutant Types} Let us investigate the prevalence of \emph{mutant types} among (subsuming) commit-relevant mutants, using 25 distinct mutant group types from Pitest~\cite{pitest}. This is important to determine whether the generation, selection or identification of commit-relevant mutants can be improved by focusing on specific mutant types. \textit{What is the prevalence of mutant types among (subsuming) commit-relevant mutants?} \autoref{fig:RQ4-test_mutants_operators} illustrates the prevalence of mutant types among commit-relevant mutants. Our evaluation results show that some mutant types are highly prevalent, such as \textit{Unary Operator Insertion Mutators (UOIMutators)}, \textit{Relational Operator Replacement Mutator (RORMutators)} and \textit{Constant Replacement Mutator (CRCRMutators)}. \revise{ On one hand, UOIMutators inject a unary operator (increment or decrement) on a variable, this may affect the values of local variables, arrays, fields, and parameters~\cite{pitest}, while RORMutators replace a relational operator with another one, e.g., ``$<$'' with ``$>$'' or ``$<=$'' with ``$<$''. On the other hand, CRCRMutators mutates inline constants. For further detauls about the mutant types, the table of constants and other mutation operators can be found in the official PiTest documentation\footnote{http://pitest.org/quickstart/mutators/}.} Specifically, 50.77\% of the commit-relevant mutants are of one of these three mutant types. This is mainly related to the fact these three mutation operators produced the majority (54.5\%) of the mutants considered in our study. Precisely, \autoref{fig:RQ4-ratio_relevant_mutants_operators} shows that the \emph{distribution} of commit-relevant mutants is clearly \emph{uniform} per mutant type. That is, in general, between 20\% and 30\% of the mutants for each type result to be commit-relevant. This indicates that mutants type does not increase or reduce the chances for mutants of being commit-relevant. The outliers of \autoref{fig:RQ4-ratio_relevant_mutants_operators}, corresponding to mutant types \revise{Bitwise Operator Mutator} (\textit{OBBNMutators}) and \revise{Invert Negatives Mutator} (\textit{InvertNegsMutat}), are because of the low number of mutants for these types: 13 out of 81 (16\%) mutants are commit-relevant in the case of \textit{OBBNMutators} mutant type, while 3 out of 5 (60\%) mutants are commit-relevant for \textit{InvertNegsMutat} mutant type. \revise In particular, OBBNMutators mutates (i.e., reverses) bitwise ``AND'' (\&) and ``OR'' ($|$) operators, while InvertNegsMutat operators inverts the negation of integers and floating-point numbers.} Similarly, Figures \ref{fig:RQ4-test_sub_mutants_operators} and \ref{fig:RQ4-ratio_sub_mutants_operators} show that the ratio of subsuming commit-relevant mutants per mutant type follows a uniform distribution as well. Typically, between 5-7\% of the mutants per mutant type turn to be subsuming commit-relevant. The outlier of \autoref{fig:RQ4-ratio_sub_mutants_operators} corresponds to \textit{InvertNegsMutat} mutant type, where none of the 3 commit-relevant mutants identified for this mutant type are subsuming (because of mutants of a different mutant type subsume them). \begin{result} The distribution of (subsuming) commit-relevant mutants per mutant type is uniform. Typically, between 20-30\% (5-7\%) of the mutants per mutant type are (subsuming) commit-relevant. \end{result} \smallskip\noindent \subsection{\RQ5: Effectiveness of Commit-relevant Mutants Selection} This section simulates a mutation testing scenario where the tester selects a mutant for analysis for which a test to kill it is developed. Note that a test case that is designed to kill a mutant may collaterally kill other mutants. Consequently, opening a space to examine the effectiveness of the test suites developed when guided by different mutant selection strategies. Accordingly, this study compares the following mutant selection strategies: “random mutants selection,” “mutants within a change,” and (subsuming) commit-relevant mutants. We measure their effectiveness in terms of the \textit{Relevant Mutation Score} (RMS) and \textit{Minimal-Relevant Mutation Score} (RMS*), which intuitively measures the number of (subsuming) commit-relevant mutants killed by the different test suites. Specifically, we investigate the extent to which selecting and killing each aforementioned mutant types improves the test suite quality, in terms of the number of (subsuming) commit-relevant mutants killed by the test suite. Then we pose the question: \textit{How many (subsuming) commit-relevant mutants are killed if a developer or test generator selects and kills random mutants or only mutants within a change?} \begin{table}[] \caption{Comparative Effectiveness of selecting and killing (subsuming) commit-relevant mutants in comparison to ``\revise{all mutants}'' and ``mutants within a change'' by observing RMS (Relevant Mutation Score) and RMS* (Subsuming Relevant Mutation Score)} \resizebox{\textwidth}{!}{ \begin{tabular}{c|cccccccccc|cccccccccc|} \cline{2-21} & \multicolumn{10}{c|}{\textbf{RMS}} & \multicolumn{10}{c|}{\textbf{RMS*}} \\ \hline \multicolumn{1}{|c|}{\textbf{Selection Strategy/Interval}} & \textit{\textbf{2}} & \textit{\textbf{4}} & \textit{\textbf{6}} & \textit{\textbf{8}} & \textit{\textbf{10}} & \textit{\textbf{12}} & \textit{\textbf{14}} & \textit{\textbf{16}} & \textit{\textbf{18}} & \textit{\textbf{20}} & \textit{\textbf{2}} & \textit{\textbf{4}} & \textit{\textbf{6}} & \textit{\textbf{8}} & \textit{\textbf{10}} & \textit{\textbf{12}} & \textit{\textbf{14}} & \textit{\textbf{16}} & \textit{\textbf{18}} & \textit{\textbf{20}} \\ \hline \multicolumn{1}{|c|}{\textbf{Random}} & 46.67 & 70.59 & 82.42 & 88.10 & 91.95 & 95.26 & 95.74 & 96.85 & 97.50 & 98.05 & 11.11 & 35.00 & 54.17 & 66.13 & 75.00 & 81.25 & 85.71 & 88.24 & 90.89 & 92.76 \\ \cline{1-1} \multicolumn{1}{|c|}{\textbf{Within a change}} & 46.48 & 59.52 & 65.91 & 67.48 & 68.42 & 69.47 & 69.96 & 70.18 & 70.40 & 71.09 & 11.95 & 25.00 & 28.95 & 32.31 & 33.33 & 33.67 & 34.38 & 34.88 & 35.23 & 35.29 \\\cline{1-1} \multicolumn{1}{|c|}{\textbf{Commit-Relevant}} & 75.00 & 95.05 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 40.74 & 83.72 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 100 \\ \cline{1-1} \multicolumn{1}{|c|}{\textbf{Subsuming Commit-Relevant}} & 80.00 & 98.51 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 65.75 & 95.35 & 100 & 100 & 100 & 100 & 100 & 100 & 100 & 100 \\ \hline \end{tabular} } \label{tab:RQ5-median-developer_simulation} \end{table} \begin{figure*}[bt!] \centering \begin{subfigure}[t]{0.49\textwidth} \centering \includegraphics[width=\textwidth]{figures/Box_plot_Simulation_relevant_ms_v3.pdf} \caption{Relevant Mutants Progression} \end{subfigure} \begin{subfigure}[t]{0.49\textwidth} \centering \includegraphics[width=\textwidth]{figures/Box_plot_Simulation_minimal_relevant_ms_v3.pdf} \caption{Subsuming Relevant Mutants Progression} \end{subfigure} \caption{ Comparative Effectiveness of selecting and killing (subsuming) commit-relevant mutants in comparison to ``random mutants'' and ``mutants within a change''} \label{fig:RQ5-developer_simulation} \end{figure*} \autoref{tab:RQ5-median-developer_simulation} and \autoref{fig:RQ5-developer_simulation} demonstrates how the effectiveness of the developed test suites progresses when we analyze up to 20 mutants from the different mutant pools. We observed that when the same number of mutants are selected from the different pools, better effectiveness is reached by test suites developed for killing (subsuming) commit-relevant mutants. For instance, a test suite designed to kill six (6) selected (subsuming) commit-relevant mutants will achieve 100\% of RMS and RMS*. However, a test suite designed to kill six randomly selected mutants will achieve 82.42\% RMS and 54.17\% RMS*, while a test suite that kills six mutants within a change will achieve 65.91\% RMS and 28.95\% RMS*, respectively. More precisely, even after selecting 20 mutants, neither random selection \revise{from all mutants} nor within a change selection achieved 100\% of RMS and RMS*. This result demonstrates the significant advantage achieved by selecting (subsuming) commit-relevant mutants. Moreover, we observed that random selection \revise{from all mutants} is up to 1.6 times more effective than selecting mutants within a change. For instance, selecting 20 random mutants achieves 98.05\% RMS and 92.76\% RMS*, while selecting 20 mutants within a change only achieves 71.09\% RMS and 35.29\% RMS*. This result demonstrates the importance of selecting mutants \emph{outside} developers' committed changes. \begin{result} Selecting and killing (subsuming) commit-relevant mutants led to more effective test suites. They significantly reduced the number of mutants requiring analysis compared to random mutant selection and selecting mutants within a change. \end{result} \smallskip\noindent \subsection{\RQ6: Test Executions} In this section, we study the \emph{efficiency} of the different mutant sets in terms of the number of \emph{test executions} \revise{required to run the tests resulting from the analysis of 2-20 mutants. We thus, approximate the \revise{computational} demands involved when using all mutants, relevant mutants, (subsuming) relevant mutants and mutants located within commit changes. } \revise{\autoref{fig:RQ6-developer_simulation} illustrates the number of test executions required by the test suites \revise{derived by the analysis of 2-20 mutants}. We found that the analysis of commit-relevant mutants significantly reduces the number of required test executions by \revise{4.28} times on average over different intervals of analysed mutants (and \revise{16} times when using subsuming commit-relevant mutants) in comparison to \revise{test execution required when analysing all mutants}. For instance, users will need to perform \revise{601} test executions when deriving tests based on the \revise{analysis of 2} mutants, from the set of all mutants, compared to \revise{185 or 52} test executions needed by the use of commit-relevant mutants or subsuming commit relevant mutants, respectively. } \revise{The difference increases with the number of analysed mutants. Thus, for the 2 analysed mutants, the difference in test execution is 2.8 times. For 4 mutants, 3.65, and 6 mutants, the difference in test execution is 4 times comparing all mutants and the commit-relevant mutants. We can also observe an increase in the difference between test executions needed by the use of subsuming commit relevant mutants and all mutants over different intervals. This difference is 11.55 times, 14.68 and 16 for analysed 2,4 and 6 mutants, respectively. Overall, we can compare test execution needed by using commit-relevant and subsuming commit-relevant mutants and observe a 4 times difference on average, with no considerable differences between intervals. } \begin{result} Selecting subsuming commit-relevant mutants reduces test execution cost \revise{(i.e., the number of test executions,}) by up to \revise{16} times compared to all mutants. \end{result} \begin{figure*}[bt!] \centering \includegraphics[scale=0.3]{figures/Box_plot_Simulation_computational_effort_v5.pdf} \caption{Efficiency, number of test executions required when deriving test suite sizes (in the range [2, 20]).} \label{fig:RQ6-developer_simulation} \end{figure*} \section{Threats to Validity}\label{ValidityThreats} Our empirical study and findings may be limited by the following validity threats. \smallskip \noindent \textbf{\textit{External Validity:} }This refers to the generalizability of our findings. We have empirically evaluated the characteristics of commit-relevant mutants on a small set of open-source Java programs, test cases, and mutants. Hence, there is a threat that our experimental protocol and findings do not generalize to other mutants, programs, or programming languages. \revise{Additionally, there is the threat that our findings do not generalize to other Java projects, since our subject programs are all from the Apache Commons project and may share similar characteristics in terms of architecture, implementation, coding style and contributors.} We have mitigated these threats by conducting our experiments on five (5) matured Java programs with a varying number of tests and a considerably large number of mutants. In our experiments, we had 288 commits and 10,071,872 mutants with 25 different groups of mutant types. In addition, our subject programs have 216,489 KLOC and 17 years of maturity, on average. Hence, \revise{we are confident that our empirical findings hold for the tested (Java) projects, programs, commits, and mutants. } \revise{ Furthermore, we encourage other researchers to replicate this study using other (Java) programs, projects and mutation tools. } \revise{ In our experiments we used Pitest \cite{pitest} to perform our analysis. However, it is likely that the use of a different mutation tool may impact our findings, since it may contain different operators than Pitest. While this is possible, recent empirical evidence \cite{KintisPPVMT18} has shown that Pitest has one of the most complete sets of mutation operators that subsumes the operators of the most popular mutation testing tools in almost all cases. Nevertheless, we are confident on our results since Pitest includes a large sample of mutants the general results are unlikely to change with different types of simple mutations. } \smallskip \noindent \textbf{ \textit{Internal Validity:}} This threat refers to the \textit{incorrectness} of our implementation and analysis, especially if we have correctly implemented/deployed our experimental tools (e.g., Evosuite, Pitest and Pitest assert), performed our experiment as described and accounted for randomness in our experiments. We mitigate the threat of incorrectness by (manually) testing our implementation, tools, and experimental protocol on few programs and commits to ensure our setup works as expected. \revise{Specifically, we performed manual testing by examining five (5) representative Apache programs containing about 500 LoC per commit on average. While we inspected in total about 20 commits with over 30 LoC in patch sizes, on average.} We also address the threat of randomness in our experiments by repeating our experiments 100 times to mitigate any random or stochastic effects. \smallskip \noindent \textbf{\textit{Construct Validity:}} This refers to the \textit{incompleteness} of our experimental approach, in terms of \textit{identifying all commit-relevant mutants}. Despite the soundness of our approach, it only provides an approximation of commit-relevant mutants, such that the set of identified commit-relevant mutants is only a subset of the total number of all commit-relevant mutants. This is due to the finite set of test cases and mutants employed in our experiments. We have mitigated this threat by ensuring we have a reasonably large set of mutants and test cases for our experiments. For instance, following the standards set up by previous studies \cite{KurtzAODKG16,ammann_establishing_2014,PapadakisK00TH19}, we augmented developers' written tests by automatically generating additional tests (using EvoSuite), to expand the observable input space for commit-relevant mutants. Our experimental findings are also threatened by the potential noise introduced by \textit{equivalent mutants}. First, notice that commit-relevant mutants come either from lines within the change or outside the change. On the one hand, considering our \autoref{algo:relevant} for identifying commit-relevant mutants outside the change, you can notice that in case that mutant $X$ is equivalent, then condition $Yval \neq XYval$ in Line 9 will evaluate to \emph{false}, since mutants $Y$ and $XY$ will be equivalent as well, then mutant $X$ will not be considered as commit-relevant. On the other hand, our approach selects by default all the mutants within the change as commit-relevant, so there is a potential threat in selecting some equivalent mutant, even though mutants within the change are a small fraction concerning the total number of mutants. To mitigate this threat, we employ standard methods in mutation testing to reduce the probability of generating equivalent mutants, for instance, by applying \texttt{Pitest} to ensure no common language frameworks are mutated. \revise{ Furthermore, our experimental approach is limited by our measure of mutant execution effort (i.e., efficiency), as well as the granularity of our test assertion checks. Firstly, in our experiments, we have estimated the efficiency of commit-aware mutation testing using the \textit{number of mutant test executions}. This measure is limited because it assumes that all tests have similar execution time (on average). Thus, there is a threat that our measure of efficiency may not be representative of actual execution time, especially if some mutants/tests have a longer execution time than others. Though, we argue that number of mutant test executions generalizes better than execution or CPU time because it is independent of the infrastructure, level of parallelization and test execution optimizations used. Consider the case of a test execution optimization that avoids issues caused by infinite loops. This optimization will result in significantly different execution times than if not employing them. Similarly, parallelization impacts the requested execution time if different strategies are used. Therefore, execution time measurements can be more accurate than the number of mutant executions that we use only if one uses the same infrastructure, parallelization, and mutant test execution optimizations. In our case, we ran our experiments in our University HPC\footnote{https://hpc.uni.lu/} with a heavy parallelization scheme. Therefore, we feel that its test execution results are hard to generalize to other environments. We also note, that there are many test execution optimizations \cite{PapadakisK00TH19, WangLXL21} that are not implemented yet by the existing mutation testing tools, fact that may reduce the generalization of our results. } \revise{ To determine the interactions between mutants, we employ a coarse-grained assertion check in our experiments. Specifically, our assertion checks are at the assert parameter level. As an example, given a first-order mutant and a second-order mutant, we directly check the equality of the parameter values (i.e., the expected and actual outcomes) for both mutants. This raises the threat of missing more fine-grained assertion properties, especially the effect of dependencies within assertions and test cases. Our approach may mask such dependencies, e.g., if there is a dependency between the expected and actual value within the assertion. Indeed, this assertion check may limit the number of observed commit-relevant mutants, as a more fine-grained approach (e.g. one that accounts for such dependencies) may reveal more commit-aware mutants. In the future, we plan to investigate the effect of assertion granularity on (commit-aware) mutation testing. Finally, we also encourage other researchers to investigate the effect of these issues (i.e., assertion granularity and test execution effort) on the performance of commit-aware mutation testing. }
{'timestamp': '2021-12-31T14:49:59', 'yymm': '2112', 'arxiv_id': '2112.14566', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14566'}
arxiv
\subsection{Experimental Settings} We train the target classification networks with batch size 32 in advance and then freeze the parameters. We train the invertible framework for 50 epochs. The hyper-parameters are set as $\alpha=0.01, \beta=1, \gamma=0.005, \epsilon=2$ and $\delta=0.01$. Adam is adopted as the optimizer, and the batch size is 8. The learning rate is $10^{-4}$. The models are all trained on NVIDIA RTX 3090 and the training finishes in a week. \noindent\textbf{Dataset and Evaluation.} We evaluate our proposed RAEG on three typical datasets, namely, CelebA-100, Caltech-101 and Mini-ImageNet. We divide the images in each category or class into training set and test set at a ratio of $9:1$ and resize all the images to $256 \times 256$ pixels. We employ peak signal to noise ratio (PSNR) and structural similarity (SSIM) in our quantitative image comparisons. We report the Top-1 accuracy during evaluation. \noindent\textbf{Benchmark.} There is no previous work that can simultaneously ensure the robustness of the adversary and provide invertibility. RAE and RIT embed the difference between the original and the adversarial image. However, most robust AE methods \cite{shi2021generating,zhong2021undetectable} introduces too much distortion, which exceeds the maximum capacity of state-of-the-art RDH schemes according to our experiments. Therefore, it is hard to simultaneously ensure robustness and invertibility based on RAE and RIT. We implement respectively RIT and RAE using IGSM and CW as AE and RDH-OVT \cite{zhang2012reversible} as RDH. \section{Introduction} Deep learning and neural network models have achieved great success in various fields including image classification and face recognition. Such superior performance causes concerns for both individuals and companies. On the one hand, individuals concern that their data will be analyzed by unauthorized models, leading to privacy leakage. On the other hand, large-scale datasets are necessary to train a satisfying deep model. However, data collecting and labelling are time-consuming and expensive. Therefore, datasets are always seemed as digital properties. Organizations, companies and researchers may charge for their carefully labeled or annotated private datasets and only those authorized are expected to use these datasets. However, unauthorized malicious employees may steal the dataset and send it to the company's competitors, resulting in economic losses for the company. As a result, it is vital to protect the data from both instance-level as well dataset-level. Adversarial Examples (AE) ~\cite{szegedy2013intriguing,carlini2017towards} are specialised in confusing neural networks to make unreliable decisions. The generated examples are indistinguishable with normal ones to the human eye but function drastically different. However, since the generation of AE is gradually irreversible, it also bans the legal users from utilizing the resources. Reversible Adversarial Example (RAE) ~\cite{liu2018reversible} aims to alleviate this issue by reverting AE using reversible data hiding (RDH). The method first generates the adversarial image using existing AE methods, then embeds the adversarial perturbation into the adversarial image, and generates the stego image using RDH. Due to the characteristic of reversibility, the adversarial perturbation and the original image can be recovered. \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{figures/teaser.pdf} \caption{A practical example of RAEG. The data owner transforms his valuable images into non-recognizable, non-trainable adversarial images, despite using defensive methods like JPEG compression or ComDefend \cite{jia2019comdefend}. Legal users can revert the protection process with trivial loss.} \label{image_teaser} \end{figure} Yin \emph{et al.}~\cite{yin2019reversible} adopted Reversible Image Transform (RIT) instead of histogram shifting to improve the performance of RAE. However, RAE and RIT are fragile to adversarial defense methods, including Gaussian filtering, JPEG compression, etc. Therefore, the malicious attackers can easily obtain an approximate version of the original images using adversarial defense. In this paper, we propose Reversible Adversarial Example Generation (RAEG) via an invertible neural network (INN), which takes the defense operations into consideration in the process of generation. In detail, the original image is fed into a U-shaped invertible neural network to obtain the adversarial image. Through the backward process of INN, we recover the original image with trivial loss. To enhance the robustness of RAEG against defensive operations, we mimic typical image processing operations and require that the protected images through these defenses still capable of fooling networks. Several classifiers with typical architecture are selected as targets for RAEG to attack with. Successful data protection model should enforce both the generated protected images and the attacked images to mislead the targeted models. Figure~\ref{image_teaser} illustrates a practical application where the images are perturbed by RAEG for copyright protection. Even though the attacker processes the images using traditional blurring process or adversarial defense methods, he cannot successfully recover the images for network training. However, the authenticated receivers can successfully revert the protection process and train their networks based on the recovered images. Therefore, the data owner is not required to launch an unnecessary extra dataset transmission which is time and network consuming. Extensive experiments demonstrate that RAEG can better protect the data with slight distortion against image purifying operations than previous methods. The models trained upon protected images or their defensed versions are mal-functioned compared to normal ones. Besides, the proposed method can almost perfectly restore the original image, while the previous methods can only restore a blurry version. Our main contributions are summarized as follows: \begin{itemize} \item We propose a reversible adversarial example generation method based on invertible neural network to protect the dataset. To the best of our knowledge, this is the first work to introduce invertible neural network for generating adversarial examples. \item Considering defense operations, e.g., JPEG compression, we utilize the neural network to mimic these operations and force the generator to resist these operations. \item Extensive experiments show that the quality of adversarial images is considerable, and the ability of misleading the classification model with defense operations is better than traditional RAE methods. \end{itemize} \begin{figure*}[t] \centering \includegraphics[width=1.0\textwidth]{figures/fig1_new2.pdf} \caption{Network overview of RAEG. The generator transforms the original image into the protected image. The attack layer simulates the most commonly seen image processing attacks. We ensemble several classifiers as the joint targeted networks that the generated images should evade from. The inverse process of the generator recovers the original image.} \label{image_framework} \end{figure*} \input{relatedwork} \section{Method} \subsection{Overview} The sketch of our RAEG framework is presented in Figure \ref{image_framework}, which consists of a generator, an attack layer for defense simulation, several pre-trained targeted classifiers and a discriminator. The generator $\mathbf{G}$ is built on an INN, where given $\mathbf{I}$, we generate the protected version $\mathbf{I}_{\emph{prt}}$ using the forward pass. We introduce an attack layer to simulate the real-world image redistribution stage as well as enhance the robustness of the generated adversarial example. Afterwards, we emsemble several pre-trained classifiers as the joint targeted networks. We require that both $\mathbf{I}_{\emph{atk}}$ and $\mathbf{I}_{\emph{prt}}$ should mislead the joint prediction of the emsemble models. In the backward pass, we inversely run $\mathbf{G}$ to recover $\mathbf{I}$. Finally, we introduce a discriminator to keep high visual quality of the adversarial image. \subsection{Network Architecture} \noindent\textbf{The Generator. } As shown in Figure~\ref{image_framework}, the generator $\mathbf{G}$ is composed of three stacked downscaling modules and three upsampling modules. Each module contains a Haar downsampling or upsampling transformation layer and four double-sided affine coupling layers. After the Haar wavelet transformation, the input image or the feature map is decomposed into one low-frequency representation and three high-frequency representations in the vertical, horizontal, and diagonal direction. The wavelet transform is an invertible symmetric transformation, which will not affect the following invertible operations. Afterwards, the frequency representations are fed to double-side affine coupling (DSAC) block, which are the crucial parts in the invertible process. DSAC block first splits the input image or the feature map $\boldsymbol{x}^i$ into two parts, denoted as $\boldsymbol{x}_1^i$ and $\boldsymbol{x}_2^i$. Then, we apply double-side affine transformations to both $\boldsymbol{x}_1^i$ and $\boldsymbol{x}_2^i$: \begin{equation} \begin{split} \boldsymbol{x}_1^{i+1} &= \boldsymbol{x}_1^i \odot \exp(\theta_1(\boldsymbol{x}_2^i)) + \phi_1(\boldsymbol{x}_2^i) \\ \boldsymbol{x}_2^{i+1} &= \boldsymbol{x}_2^i \odot \exp(\theta_2(\boldsymbol{x}_1^{i+1})) + \phi_2(\boldsymbol{x}_1^{i+1}), \end{split} \end{equation} where $\theta(\cdot)$ and $\phi(\cdot)$ produce the scale and shift coefficients. The output sub-band feature maps of each block are then concatenated into a complete output feature map, denoted as $(\boldsymbol{x}_{1}^{i+1}, \boldsymbol{x}_{2}^{i+1})$. In the reverse process, the input feature map is first split into two sub-band feature maps $\boldsymbol{x}_{1}^{i+1}$ and $\boldsymbol{x}_{2}^{i+1}$, and then use double-side affine transformations to get two reversed output sub-band feature maps $\boldsymbol{x}_1^i$ and $\boldsymbol{x}_2^i$: \begin{equation} \begin{split} \boldsymbol{x}_2^i &= (\boldsymbol{x}_2^{i+1} - \phi_2(\boldsymbol{x}_1^{i+1})) \oslash \exp(\theta_2(\boldsymbol{x}_1^{i+1})) \\ \boldsymbol{x}_1^i &= (\boldsymbol{x}_1^{i+1} - \phi_1(\boldsymbol{x}_2^i)) \oslash \exp(\theta_1(\boldsymbol{x}_2^i)), \end{split} \end{equation} where $\oslash$ denotes element-wise division. Finally, we concatenate two output sub-band feature maps into the reversed feature map $\boldsymbol{x}^i$. Noted that $\theta(\cdot)$ and $\phi(\cdot)$ are not required to be invertible. We use the residual block to construct the sub-nets. Spectral Normalization (SN)~\cite{miyato2018spectral} instead of the traditional batch normalization is adopted in each block, since it helps stabilizing the training. \noindent\textbf{The Defense Simulation.} Similar to~\cite{zhu2018hidden}, we mimic typical image preprocessing by differentiable layers. Our defense layer contains five types of typical digital attacks, including Gaussian noise, Gaussian blurring, scaling, random cropping and JPEG compressing. Since JPEG simulation in previous works are reported to have over-fitting problem in that the compression mode is always fixed, we propose to generated the pseudo-JPEG images $\mathbf{I}_{\emph{jpg}}$ by interpolating the results among different methods with varied quality factors. \begin{equation} \mathbf{I}_{\emph{jpg}}=\sum_{\mathcal{J}_{k}\in \mathcal{J}}\sum_{QF_{l}\in[10,100]}\epsilon\cdot\mathcal{J}_{k}(\mathbf{I}_{prt}, QF_{l}), \end{equation} where $QF$ stands for the quality factor, $\sum_{\mathcal{J}_{k}\in \mathcal{J}}\epsilon=1$ and $\mathcal{J} \in $\{JPEG-SS\cite{liu2021jpeg}, JPEG-Mask\cite{zhu2018hidden}, MBRS\cite{jia2021mbrs}\}. \noindent\textbf{The Ensemble Targeted Networks. } We employ four targeted classifiers with different architectures, i.e., VGG16, ResNet-50, ResNet-101 and DenseNet-121. The networks are pre-trained on clean $\mathbf{I}$. \noindent\textbf{The Discriminator. } Finally, we introduce a discriminator $\mathbf{D}$ to improve the quality of $\mathbf{I}_{\emph{prt}}$, which distinguishes the generated images $\mathbf{I}_{\emph{prt}}$ from the original image $\mathbf{I}$. \begin{figure}[!t] \centering \includegraphics[width=0.49\textwidth]{figures/123.pdf} \caption{Inversion test of RAEG. We perform different kinds of attacks on the protected images before reconstruction, e.g., JPEG with QF=70 on (a), Gaussian Blur on (b) and rescaling on (c). RAEG can still reverse the images despite the presence of the attacks.} \label{image_comparison} \end{figure} \begin{figure}[!t] \centering \includegraphics[width=0.49\textwidth]{figures/protected.pdf} \caption{Showcase of protected images among RAE-IGSM, RIT-IGSM and RAEG. The visual quality of RAE-generated images are of good quality yet the robustness is much lower (specified in Table~\ref{table_comparison}).} \label{image_protected} \end{figure} \subsection{Loss Functions} The objective functions include the reconstruction loss $\mathcal{L}_{prt}$, the classification loss $\mathcal{L}_{\emph{loc}}$ and the adversarial loss $\mathcal{L}_{\emph{adv}}$. In the following, $\alpha$, $\beta$, $\gamma$, $\delta$ and $\epsilon$ are hyper-parameters. \noindent\textbf{Reconstruction Loss.} We employ a protection loss $\mathcal{L}_{prt}$ and a recovery loss $\mathcal{L}_{\emph{rec}}$ respectively to encourage $\mathbf{I}_{\emph{prt}}$ and the recovered image $\hat{\mathbf{I}}$ to resemble $\mathbf{I}$. For $\mathcal{L}_{\emph{rec}}$, we have \begin{equation} \mathcal{L}_{prt}=\lVert\mathbf{I}-\mathbf{I}_{\emph{prt}}\rVert_{1}. \end{equation} For $\mathcal{L}_{\emph{prt}}$, we additionally employ the perceptual loss $\mathcal{L}_{\emph{per}}$ by employing a VGG16 feature extractor. We compare the feature maps of $\mathbf{I}$ and $\mathbf{I}_{prt}$ from the second max-pooling layer. \begin{equation} \mathcal{L}_{per} = \alpha\cdot\sum_{i=1}^N \frac{1}{H \cdot W \cdot C}|\phi_{pool_i}^{gt} - \phi_{pool_i}^{pred}|_1+\lVert\mathbf{I}-\hat{\mathbf{I}}\rVert_{1}, \end{equation} where $H, W, C$ refer to the height, weight and channel number of features. \noindent\textbf{Discriminator Loss.} For the discriminator loss, we update $\mathcal{D}$ by minimizing the binary classification loss: \begin{equation} \mathcal{L}_{dis} = \mathbb{E}_{\mathbf{I}} \log (\mathcal{D}(\mathbf{I})) + \mathbb{E}_{\mathbf{I}_{\emph{prt}}} \log (1 - \mathbf{D}(\mathbf{I}_{\emph{prt}})). \end{equation} The generator aims to fool the discriminator to make wrong predictions on whether an image is an original image or a generated image. The GAN loss $\mathcal{L}_\emph{GAN}$ is therefore: \begin{equation} \mathcal{L}_\emph{GAN}=\mathbb{E}_{\mathbf{I}_{\emph{prt}}} \log ( \mathcal{D}(\mathbf{I}_{\emph{prt}})). \end{equation} \noindent\textbf{Classification Loss.} We use the negative cross entropy (CE) loss to encourage $\mathbf{I}_{\emph{prt}}$ to be wrongly predicted by the targeted models. Considering that the $\ell_1$ distance term alone might not be powerful enough to recover the trivial details of $\mathbf{I}$, we add an additional CE loss to further encourage $\hat{\mathbf{I}}$ to be correctly classified. Therefore, the classification loss is defined as: \begin{equation} \mathcal{L}_\emph{cls}=\emph{CE}(\emph{f}(\hat{\mathbf{I}}),l)-\epsilon\cdot~\emph{CE}(\emph{f}(\mathbf{I}_\emph{prt}),l). \end{equation} \noindent\textbf{Total Loss.} The total loss is defined as follow: \begin{equation} \mathcal{L} = \mathcal{L}_{prt} + \beta\cdot \mathcal{L}_{rev} + \gamma\cdot\mathcal{L}_{cls} + \delta \mathcal{L}_{\emph{GAN}}. \end{equation} \input{sec-experiment} \section{Conclusion} In this paper, we design a U-shaped invertible image transfer network to nullify the dataset by generating acceptable perturbations to alter their intrinsic properties. The reversibility of the image transfer network ensures the performance of authorized users. Extensive experiments demonstrate that the proposed method can effectively nullify the images with acceptable distortion. \bibliographystyle{IEEEbib} \section{Related work} \subsection{Adversarial Attack and Defense} The concept of the adversarial attack is first proposed by Szegedy et al.~\cite{szegedy2013intriguing}. IGSM~\cite{kurakin2016adversarial} iteratively uses the gradients of the loss with respect to the input image to create a new image that maximizes the loss. C\&W~\cite{carlini2017towards} is an efficient optimization objective for iteratively finding the adversarial examples with the smallest perturbation. Many other AE methods have been proposed in the past decades \cite{zhong2021undetectable}. There exist different adversarial defense methods. Most representative methods are based on image denoising, e.g., ComDefend~\cite{jia2019comdefend} and image reconstrution, e.g., DIPDefend~\cite{dai2020dipdefend}. Besides, traditional image processings such as JPEG compression, Gaussian filter can also serve as lightweight denoising methods. Adversarial training is another powerful technique for defense. To counter the defensive methods, there are also some robust AE methods \cite{shi2021generating}, but the perturbation is much larger and the robustness is not generalized. \subsection{Reversible Adversarial Example} Liu et al.~\cite{liu2018reversible} aim at to restoring the original image from the reversible adversarial image using RDH method. In detail, the adversarial image is generated by the existing AE methods, e.g. C\&W. Then, RAE try to hide the difference into the adversarial image using RDH. Due to the limited capacity of RDH, the information of the difference is usually too large, and they alternatively downsample the images and hide the resized difference. \textit{Therefore, the original image cannot be perfect restored. Besides, the adversarial defense methods can easily invalidate the RAE.} To perfectly restore the original image, Yin et al.~\cite{yin2019reversible} introduce reversible image transform (RIT) for generating reversible adversarial example. The essence of RIT is permuting the blocks, e.g. $2\times2$, of the original image to match the adversarial image. Then some additional information, e.g., block index, should be embedded into the permuted image using RDH to generate the final image. It can be easily inferred that the permutation causes large distortion, e.g., severe block artifacts. \textit{The adversarial ability of RIT degrades a lot resulting from the distortion. } \section{Experiment} \input{exp_setting} \subsection{Qualitative and Quantitative Analysis} \noindent\textbf{Qualitative Results.} Figure~\ref{image_comparison} and Figure~\ref{image_protected} provides examples of RAEG inversion test and RAEG-generated protected images where $\mathbf{I}$ are acceptably modified for protection. The perturbation is generally represented by contrast change or local area modification. With $\mathbf{I}$ kept secret, the overall quality of $\mathbf{I}_{\emph{prt}}$ is decent enough for normal usage of these images. The average PSNR between $\mathbf{I}$ and $\mathbf{I}_{\emph{prt}}$ in these examples is 28.12dB. In contrast, RIT cannot generate visual-satisfactory protected images in that there are noticable distortions. Please zoom in for details. The quality of generated image by RAE is the best, but the robustness of adversary is limited according to the following tests. In Figure~\ref{image_comparison}, the protected images cannot be categorized by traditional classifiers while the reversed images can, and $\hat{\mathbf{I}}$ is nearly same as the $\mathbf{I}$. \noindent\textbf{Quantitative Comparisons.} Table~\ref{table-psnr-acc} presents the numerical results of our RAEG under various parameters. Their exist a trade-off between the adversary and the visual quality of the protected image. PSNR$\approx$28dB in RAEG provides a considerable trade-off, so we adopt this experimental setting during comparison. As for the recovered image $\hat{\mathbf{I}}$, the PSNR is around 40dB and SSIM is greater than 0.97. Table~\ref{table_comparison} compares the accuracy of the target models on images generated by different RAE methods and RAEG. our RAEG significantly outperforms RAE methods against typical attacks, including low quality JPEG compression, resize. Besides, we also report the anti-defense capability against two state-of-the-art methods, namely, ComDenfend \cite{jia2019comdefend} and DIPDefend \cite{dai2020dipdefend}. The results are also promising that the attackers cannot effectively increase the classification accuracy. \noindent\textbf{Prevention of Training Pirated Models.} We further explore the performance of RAEG on protecting the whole dataset. We assume that the attacker can obtain the whole dataset from collecting enough $\mathbf{I}_{\emph{prt}}$, and he trains his own ResNet-50/ResNet-101/DenseNet-121 network based on these images. As can be seen from Table~\ref{table-retrain}, the three pirated models cannot be well trained on the protected dataset, even if he pre-processes $\mathbf{I}_{\emph{prt}}$ using ComDefend. In contrast, a verified recipient can train his networks well by inverting $\mathbf{I}_{\emph{prt}}$. The results clearly point out the effectiveness of RAEG to protect the whole dataset. \begin{table}[!t] \footnotesize \centering \caption{Results of RAEG under various settings. $A$, $P$, $S$ respectively denote Accuracy, PSNR and SSIM.} \begin{tabular}{c|c|c|c|c|c|c|c} \hline Dataset & $A_{ori}$ & $A_{prt}$ & $A_{rev}$ & $P_{prt}$ & $P_{rev}$ & $S_{prt}$ & $S_{rev}$ \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}Caltech\\-101\end{tabular}} & 0.953 & 0.654 & 0.944 & 30.504 & 45.499 & 0.900 & 0.989 \\ & 0.980 & 0.479 & 0.977 & 27.256 & 45.260 & 0.848 & 0.985 \\ & 0.956 & 0.166 & 0.941 & 24.167 & 41.684 & 0.728 & 0.963 \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}CelebA\\-100\end{tabular}} & 0.823 & 0.147 & 0.750 & 31.878 & 43.542 & 0.955 & 0.996 \\ & 0.820 & 0.060 & 0.823 & 28.720 & 48.042 & 0.901 & 0.998 \\ & 0.833 & 0.020 & 0.643 & 25.928 & 38.575 & 0.872 & 0.989 \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}Mini-\\ImageNet\end{tabular}} & 0.926 & 0.211 & 0.889 & 30.415 & 42.262 & 0.893 & 0.983 \\ & 0.948 & 0.068 & 0.941 & 27.366 & 39.361 & 0.871 & 0.979 \\ & 0.942 & 0.086 & 0.933 & 25.947 & 40.209 & 0.830 & 0.979 \\ \hline \end{tabular} \label{table-psnr-acc} \end{table} \begin{table} \footnotesize \centering \caption{Training networks based on different datasets. The accuracies are from ResNet-50/ResNet-101/DenseNet-121.} \begin{tabular}{c|c|c} \hline \multirow{2}{*}{Dataset} & \multicolumn{1}{c|}{Trained on $\mathbf{I}_{atk}$} & \multirow{2}{*}{Trained on $\hat{\mathbf{I}}$} \\ & using ComDefend & \\ \hline Caltech-101 & 0.473 / 0.552 / 0.591 & 0.974 / 0.971 / 0.967 \\ \hline Mini-ImageNet & 0.526 / 0.565 / 0.597 & 0.935 / 0.955 / 0.952 \\ \hline CelebA-100 & 0.243 / 0.252 / 0.260 & 0.805 / 0.807 / 0.801 \\ \hline \end{tabular} \label{table-retrain} \end{table} \subsection{Ablation Study} \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{figures/ablation.pdf} \caption{Ablation study on the quality of $\mathbf{I}_{\emph{prt}}$. The performances from the partial setups have noticeable defects.} \label{image_ablation} \end{figure} \begin{table}[t] \footnotesize \centering \caption{Ablation study on robustness, visual quality and generalization of RAEG.} \begin{tabular}{c|c|c|c|c} \hline Setting & $P_{rev}$ & $A_{prt}$ & $A_{tran}$ & $A_{def}$\\ \hline $\mathbf{G}$ using ``Enc-Dec" architecture & 31.37 & 0.479 & 0.569 & 0.803 \\ \hline w/o discriminator & 37.53 & 0.241 & 0.265 & 0.491 \\ \hline w/o VGG loss & 38.62 & 0.197 & 0.247 & 0.343\\ \hline Training with one victim & $\textbf{42.61}$ & $0.124$ & $0.267$ & $0.673$ \\ \hline Full Implementation & $40.14$ & $\textbf{0.093}$ & $\textbf{0.082}$ & $\textbf{0.122}$ \\ \hline \end{tabular} \label{table_ablation} \end{table} For space limit, we conduct ablation studies on Mini-ImageNet. The accuracies are reported based on a pretrained ResNet-50. Figure~\ref{image_ablation} and Table~\ref{table_ablation} respectively showcase and provide average results from several partial setups. For fair comparison, we let $P_{prt}\approx27$dB in each test. \noindent\textbf{Effectiveness of INN Architecture.} A typical alternative of INN is to model image protection and image recovery independently using Encoder-Decoder-based networks. However, invertible neural network learns stable invertible distribution mapping, where the forward and back propagation operations are in the same network. From Table~\ref{table_ablation}, we observe that INN-based RAEG provides a better performance. \noindent\textbf{Influence of the Perceptual Loss and the Discriminator.} As show in Table~\ref{table_ablation}, without the perceptual Loss and the discriminator, the overall performance will decline, and more visually unpleasant distortions appear. The results indicate that they do improve the visual quality. \noindent\textbf{Investigation on the Target Model.} Training with one target model can improve the visual quality of $x_{rev}$, but it greatly degrades the robustness in the test stage, which highlights the necessity of training with emsemble targeted networks. The reason is that the attack model can easily find the weakness of a fixed classifier through iteration and utimately produces a fixed pattern. It results in poor performance generalization.
{'timestamp': '2021-12-30T02:21:50', 'yymm': '2112', 'arxiv_id': '2112.14420', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14420'}
arxiv
\section{Introduction} \label{sect:intro} Learned systems, particularly learned database systems, have been a recent research hot spot~\cite{zhou2020database, han2021CEbenchmark, kraska2019sagedb}. As part of this trend, a considerable number of researchers have proposed integration of machine learning models into relational database systems in order to optimize overall system performance and cope with the ever increasing amounts of data that are being processed in modern data intensive applications. As part of this trend, machine learning based methods for a wide range of problems have been proposed. Most efforts appear to have been spent on problems related to query planning and optimization, where machine learning models may be used e.g. for cardinality estimation~\cite{han2021CEbenchmark, wu2020bayescard, hilprecht2019deepdb, yang2019deep, zhu2020flat}, join order selection~\cite{marcus2018deep}, cost prediction~\cite{siddiqui2020cost, vu2021learned} or query planner steering through hint set proposals~\cite{marcus2020bao}. In addition to the above, other lines of research have focused on learned data structures~\cite{kraska2018case} used for efficiently querying large indices~\cite{nathan2020learning, marcus2018deep, perera2021no, sabek2021case}, automatic database configuration tuning, accurate query run time prediction and other problems~\cite{zhou2020database}. As is the case with many publications in the machine learning space, on paper the reported results do indeed look impressive and suggest significant performance gains, if such methods were ever deployed in the real world. Yet, as most prior research has been justified on the basis of numerical experiments, performed \textit{outside} of real systems, there has been a striking absence of work focusing on the practical deployment of ML-based methods \textit{inside} real world systems. The central goal of this work is to present a concrete proposal on how this notable gap between theory and practice may be closed. For this aim, we propose here the \textsf{Baihe}\xspace SysML framework. \textbf{\textsf{Baihe}\xspace} is a general framework developed for integrating machine learning models into a relational database systems, meaning that its fundamental architecture should provide a blueprint for other implementation projects in the AI4DB and SysML space. To exemplify its applicability and generate some more robust evidence for the actual usefulness of prior research in AI4DB, we have developed the \textsf{Baihe}\xspace extension for \textsf{PostgreSQL}\xspace, a widely used, highly successful and extensible relational database system. This article is now structured as follows: In Section \ref{sect:background}, we first discuss general challenges for the implementation of AI-driven databases and then present our long term vision for AI4DB. Based on this, we then describe the rationale and fundamental principles for \textsf{Baihe}\xspace's design. Later on, in Section \ref{sect:design} we present the concrete design and features of \textsf{Baihe}\xspace in the case of \textsf{PostgreSQL}\xspace and further discuss implementation specifics. After show a typical example use case for \textsf{Baihe}\xspace on query optimizer in Section~\ref{sect:example}, we conclude this article in Section \ref{sect:conclusion}. \section{Background and Design Rationale} \label{sect:background} On a fundamental level, the nature of and requirements on a database system appear to be at odds with the inherently stochastic nature of machine learning. Database developers, users, and administrators expect rock-solid, stable and most of all deterministic behavior. On the other hand, machine learning models may produce predictions with hard to estimate error bounds and their generalization ability may fail catastrophically, once the input data distribution changes. Moreover, failures may not be readily detectable, since they might only be visible through a change in some numerical value rather than a concrete and meaningful error message. Moreover, since training of a machine learning model generally amounts to solving a mathematical optimization problem, often through the use of stochastic optimizers, model training is difficult to automate, requires close supervision by experts and may thus not be fully regarded as a well defined process. Hyperparameters, useful termination criteria and evaluation guidelines all need be carefully developed on both a per-model and per-dataset basis. All of this makes it very difficult to integrate automated training procedures into a system with strong requirements on robustness and stability. As challenging as this may sound, we still believe that the practical combination of machine learning and databases into the next generation of database systems is not a hopeless endeavor. To see this, we first note that some core components of a database system \textit{already} rely on \textit{statistical} estimates. Modern query optimizers in particular rely on such estimates e.g. in the context of cardinality and cost estimation, which are in turn used for join-order-selection and other automated decision making. The vision outlined by e.g. SageDB~\cite{kraska2019sagedb} has made a compelling case for using more advanced probabilistic methods - powered by machine learning - to improve existing issues arising from the relatively simple statistical estimations which are still part of the standard implementations of today's database systems. Second, we believe that issues related to using machine learning enabled components inside a database system, should merely be regarded as \textit{additional requirements} on the engineering of such systems. Hence, we argue that one should in principle be able to satisfactorily fulfil these requirements, \textit{if} they are properly taken into account during the system design phase and possibly enhanced through system-algorithm co-design. We hope to exemplify and support this point of view through the \textsf{Baihe}\xspace framework presented in this work. \subsection{Learned Databases: Brief Overview} \label{sect:learned_db} Before presenting the high-level architecture of \textsf{Baihe}\xspace and the rationale behind it, we first review related literature and describe the current stage and a future vision for learned database systems. We categorize learned databases into four levels, corresponding roughly both with historical development, as well as the amount of ``intelligence'' added by learned components. \begin{enumerate} \item \textbf{Primary utilization in DBMS:} Many available commercial and open-source DBMS have a long tradition of using collected statistics and statistical estimators to support some of their data management functions. Some of these methods serve as an integral parts of some components. For example, cardinality estimation (\textsf{CardEst}\xspace) consists of estimating data distribution properties used later as input for query optimization (QO). While for instance SQL Server and \textsf{PostgreSQL}\xspace build histograms and collect frequently occurring values for table attributes, MySQL and MariaDB apply a sampling strategy for \textsf{CardEst}\xspace. With respect to non-integral functions, basic statistical methods are used for advisory functions, such as index or view advisors, or knob tuning and SQL rewriters~\cite{zhou2020database}. \item \textbf{Individually learned components:} With the recent increased interest in machine learning, an increased amount of work has tried to design ML-based models to replace certain components in DBMS. In this context, the most representative works address QO and indexing. For QO, a variety of supervised and unsupervised models have be proposed for \textsf{CardEst}\xspace~\cite{han2021CEbenchmark, wu2020bayescard, hilprecht2019deepdb, yang2019deep, zhu2020flat, hasan2019multi}, cost estimation~\cite{siddiqui2020cost, vu2021learned} and join order selection~\cite{marcus2018deep, sabek2021case}. Meanwhile, a number of learned data structures structures are proposed for single and multi-dimensional indexing~\cite{kraska2018case, nathan2020learning, perera2021no}. It has been shown such ML-based methods often exhibit superior performance, when evaluated in numerical experiments outside of actual systems or tightly controlled experimental setups inside of real systems (e.g. through injecting cardinality from an outside file). However, many problems relevant to real-world deployment, such as e.g. explainability vs. predictive power, robustness or fault tolerance remain largely unaddressed. \item \textbf{Comprehensively learned modules:} On top of individually learned components, current work further moves forward by trying to substitute an entire functional module, e.g. the QO, executor or storage engine with a machine learning model. Some approaches combine multiple learned components together, learn to steer existing modules~\cite{marcus2020bao}, or even attempt to "learn" an entire module in an end-to-end fashion~\cite{marcus2019neo}. Although most work of this type claims to achieve incredible performance gains, many proposed solutions appear to be impractical for actual deployment in real-world DBMS. The reasons for this are two fold. First, learned modules of this type are highly task specific and data dependent, which may cause serious shortcomings, including but not limited to: cold start problems, lack of generalization, tuning difficulties. Second, replacing an entire module may cause compatibility risks and may require substantial engineering efforts. Therefore, at this stage, even evaluating a learned module inside a real DBMS is a difficult task. \item \textbf{AI-Native databases:} Some very recent work even proposes to redesign the whole architecture of DBMS to fully adapt AI models for data management. For example,~\cite{wu2021unified} proposes a "one model for all architecture", which learns a shared representation of data and query knowledge and then fine-tunes smaller models for each specific task.~\cite{li2019xuanyuan} proposes "AI-designed databases", where AI is integrated into the life cycle of database design, development, evaluation, and maintenance, hoping to provide optimal performance for every scenario. Although this appears to be an intriguing vision, it is clear they are still far away from any useful implementation. \end{enumerate} Hence, regarding ``AI for DB'', we observe that: 1. This field is very prosperous. The research efforts range from individual components to complete modules to even the whole architectures, and include many scenarios (QO, indexing, execution, storage and etc). Enough evidence has shown that AI-based solutions could indeed improve database performance and have the potential to play significant roles in next-generation DBMS. 2. Current work mainly focuses on ``AI'' solutions but is not concerned with how to actually deploy them ``for DB''. In addition to that, more realistic tests for newly proposed methods relying on e.g. existing extension functionalities of DBMS are rarely described in the literature, possibly because it requires deep expertise beyond the design of ML models. Such expertise requires a comprehensive understanding of both AI and DB perspectives and a systematic co-design of both algorithm and systems. Therefore, we believe that a SysML framework such as \textsf{Baihe}\xspace, which supports both evaluation and deployment of AI-driven solutions in real systems is crucial for the further development of the AI for DB field. \subsection{High Level Architecture of \textsf{Baihe}\xspace: Fundamental Design Choices and Trade-Offs} \label{subsect:high_level} \begin{figure*}[h] \centering \includegraphics[width=0.65\linewidth]{baihe_high_level.pdf} \caption{High Level View of \textsf{Baihe}\xspace's Architecture.} \label{fig:arch} \end{figure*} We now briefly describe the high level design of \textsf{Baihe}\xspace and discuss the rationale and design philosophy behind it. We note that this design should rather be considered as a design blueprint resp. design pattern, which may then have to be adapted to a specific host database system. As an example we present \textsf{Baihe}\xspace for \textsf{PostgreSQL}\xspace in Section \ref{sect:design}. The core part of \textsf{Baihe}\xspace is an extension which plugs directly into a database host system through an existing extension mechanism. This extension is the central component of \textsf{Baihe}\xspace, as it \begin{enumerate} \item intercepts the query planning and execution process, so that individual steps may be substituted with model inference calls, \item contains a clone of the host system's planner ("shadow planner"), which can be conveniently extended and modified, so that core functionality may be overwritten without interfering with the host system itself, \item provides convenient configuration facilities, \item controls collection of training data. \end{enumerate} Most of the above functionality is encapsulated in the Integration Layer component, which is the central control unit for \textsf{Baihe}\xspace. Model inference is decoupled from the extension itself, this means that for every model a new background worker process is used. These processes communicate with the \textsf{Baihe}\xspace extension and return results for inference requests. If the host system supports it, the control of these processes is managed using the host systems process management capabilities. Finally, \textsf{Baihe}\xspace needs a support library. This component allows for simple access to collected training data, such as e.g. query runtime statistics or saved query plans. Furthermore, it provides functionality for convenient deployment of trained models into the host system. The design above is based on the following high-level requirements: \begin{itemize} \item Separation from the core system. \item Minimal third party dependencies. \item Robustness, stability and fault tolerance. \item Usability and configurability. \end{itemize} For the remainder of the section we now describe the impact of these requirements on our design in more details. \newline \textbf{Separation from the Core System.} Both commercial and open source RDBMS have been and are being actively maintained and supported over long periods of times. Commercial license and support agreements may span years or even decades, so that customers may receive regular updates and critical patches, especially those addressing security issues. In order to impact existing processes as little as possible, all while avoiding a development of an entirely new database system, we have chosen to develop \textsf{Baihe}\xspace as an extension on top of an existing system, so that we may keep it as separate from the host system as possible. In this way, we avoid unnecessary doubling of maintenance efforts and allow for a quicker pace of development. \textbf{Minimal Third Party Dependencies.} Modern ML stacks are characterized by a large number of dependencies, comprising low level numerical libraries and GPU kernels, intermediate ML framework and runtime codes (typically implemented in C++), as well as high level integration code typically written in Python. To train and use what may now even be considered relatively simple deep models, a large number of packages and libraries at these three levels must be present on a host system. In practice, this typically leads to a high degree of maintenance efforts for both production, as well as test and development environments. This is particularly problematic in more traditional organizations, such as financial institutions, where - due to security or legal reasons - individual software packages may have to go through a specific vetting and approval process. We have thus designed \textsf{Baihe}\xspace such that it requires a minimal amount of external dependencies beyond those required by the core system. \textbf{Robustness, Stability and Fault Tolerance.} For most modern applications databases are among the most fundamental and mission-critical components. It is thus imperative that additional deployment of ML-based components into such systems does not impact existing service level agreements or interfere with related operational requirements. Therefore, errors arising from e.g. model-based predictions, which might influence an individual session or the system as a whole should be detected and mitigated through fallbacks to existing core functionality. \textbf{Usability and Configurability.} To further ease the burden of integration, it should be possible to control and configure \textsf{Baihe}\xspace through standard mechanisms offered by the host system. In the concrete case of a system such as \textsf{PostgreSQL}\xspace this means that \textsf{Baihe}\xspace should be able to be configured through the usual \textsf{PostgreSQL}\xspace configuration files, as well as provide a set of user defined functions as well as stored procedures, such that \textsf{Baihe}\xspace functionality may be configured, activated or deactivated through any authorized command session and without requiring any restarts of the system as a whole. Based on the above four points we may now formulate more concrete design goals with respect to the machine learning aspects. \textbf{Model Support.} As a general framework, \textsf{Baihe}\xspace should support deploying models for a range of different tasks, such as e.g. cardinality estimation, join order selection, query run time prediction. Furthermore, it should support models for learned data structures, such as e.g. learned indices. With respect to the models themselves, \textsf{Baihe}\xspace should offer support for both neural network, resp. deep learning based, model families, as well as more traditional ones, such as e.g. probabilistic graphical models, decision trees, random forests or gradient boosted trees. \textbf{Model Training.} As we have discussed in the previous section - despite the recent progress in AutoML~\cite{zhou2020database} - model training still requires close expert supervision supported by suitable tooling allowing for thorough model evaluation and rapid experimentation. In \textsf{Baihe}\xspace we thus prefer to decouple model training from the rest of the system as much as possible. While \textsf{Baihe}\xspace should still provide suitable functionality for training data collection, as well as tools for model export and deployment, we believe that training itself should be set up in a separate environment under control by specialist users such as data scientists or machine learning engineers. Once training has achieved satisfactory progress, a model can then be deployed using a well-defined deployment process. \textbf{Model Inference and Deployment} In order to avoid expensive serialization and de-serialization steps one might want to integrate a model directly into e.g. the planner component of the host system. On the other hand, to maintain the maximal amount of flexibility with respect to software dependencies and computing resources needed for inference, one might also consider implementing model inference in a completely separate service process outside of the control of the host system. We believe that both of these extremes would clash with requirements on robustness and stability, as well as maintenability of the host system. In \textsf{Baihe}\xspace we thus choose to isolate inference in a separate process, but keep this process under management by the host system. To eliminate the need for expensive serialization steps we furthermore propose process co-location, so that existing shared memory facilities may be used as much as possible. While current (practical) models in the SysML space, even deep ones, can still be considered relatively light-weight~\cite{han2021CEbenchmark, zhu2020flat}, we hence believe that computational resources needed by the inference process would in general not adversely affect the core databases process on the same machine. In the long term, should there be the need for computationally more expensive models to be deployed in the system, one could address this problem, at least in cloud environments, through on-demand attachable resources. As a consequence of the co-location requirement, one could imagine having to install additional packages on the machine running the host system, which would be needed to run model inference (e.g. ML framework runtimes etc.). To address this issue \textsf{Baihe}\xspace should provide proper tools allowing for exporting models such that they can readily be used with as little extra dependencies as possible. To achieve this goal, we propose to make use of the recent advances in the context of ML model compilers~\cite{ben2019modular}, which make it possible to compile models together with custom CPU or GPU based math kernels into highly efficient binary code, that may be accessed through a C-ABI. Nevertheless, \textsf{Baihe}\xspace should support a "Development Mode", where models may be developed and tested in the host system without intermediate compilation and build steps. \section{System Design and Implementation} \label{sect:design} \input{system_design} \section{Example Use Case: Learned Query Optimizer for \textsf{PostgreSQL}\xspace} \label{sect:example} We describe now a typical use case of for \textsf{Baihe}\xspace: deploying a learned query optimizer into \textsf{PostgreSQL}\xspace. More concretely, we discuss here the following two variants: \begin{enumerate} \item QO with individual components: cardinality estimation and cost model substituted with separately trained components. \item End-2-End QO: Here, the entire query optimizer is substituted by a trained model. \end{enumerate} \subsection{QO with individually learned components} \textsf{CardEst}\xspace models and ML-based cost models are supported out-of-the box. The shadow planner in the \textsf{Baihe}\xspace integration layer intercepts all requests for a cardinality estimate for a query touching a set of tables $T$ with set of query predicates $Q$. The tuple $(T,Q)$ is obtained from internal query parse tree structures, serialized and passed into a trained model running in a background worker. The model then returns a selectivity $0 \leq s \leq 1$, which is passed on to the planner. Training data collection for a \textsf{CardEst}\xspace model depends on whether the model is based on query-driven or data-driven \textsf{CardEst}\xspace. Specifically, data-driven \textsf{CardEst}\xspace methods build unsupervised models over the tabular data, then the cardinality of any query could be estimated over this model. For data driven \textsf{CardEst}\xspace no additional data collector is needed, since models may be trained simply using (samples of) table data and schema information provided by the user (the latter being required for models supporting multi-table \textsf{CardEst}\xspace). Query-driven \textsf{CardEst}\xspace methods build the supervised models mapping featurized queries to the cardinality. For a query driven model, we first define a data collector, which, for every query, saves the entire query plan, together with all statistics collected during the execution (i.e. the entire output of EXPLAIN ANALYZE). Training code can then load this data and convert it to the required form of $(\text{Subquery}, \text{Cardinality})$ records needed for training. Once a \textsf{CardEst}\xspace model has been trained it may then easily be registered as a model of "CARDEST" type using a call to the corresponding \textsf{Baihe}\xspace procedure. To make the model active, a background worker is started using another \textsf{Baihe}\xspace procedure call and the session variable "baihe\_ce\_model" is set to the model identifier. Then, all subsequent queries for this session will use learned cardinality from the deployed model. The process works similar in the case of cost models. Out of the box, the \textsf{Baihe}\xspace will shadow planner intercepts all cost-estimation call on a node-level (e.g. sequential scan, index scan, etc.). Then, a record depending on a variable number of features (depending on node type), is built and sent to a cost estimation model running in a background worker, which then returns a predicted cost in terms of cost units. To collect training data, we register a data collector with the same settings as used for query-driven \textsf{CardEst}\xspace. In this way, for every node in a query plan we obtain all features required for training a meaningful model, with the most important features being node type, estimated cardinality, actual cardinality and the time needed to execute a node. \subsection{End-2-End Learned QO} Some recent work also presents methods for learning a query plan directly. Such methods take a query as input, apply a certain featurization scheme and return an entire query plan as output. For our example we take a closer look at two major representatives of this line of work, namely NEO~\cite{marcus2019neo} and BAO~\cite{marcus2020bao} and show how they could be deployed using \textsf{Baihe}\xspace. NEO applies tree convolution networks to extract features from structured query plans and learns a function, called value network, mapping plans to execution latency. Then, a best-first search strategy is used to find a near-optimal query plan as measured by the value network. To deploy NEO, we first register a data collector as used for query-driven \textsf{CardEst}\xspace in the previous subsection. Then, we a background workers which implements value network inference and the best-first search strategy, respectively. During query execution, we intercept the planning process at the highest level in the \textsf{Baihe}\xspace integration layer (right after the \textsf{Baihe}\xspace extension is first called by the host system) and forward the query to the the background worker, evaluates the value network worker and returns a query plan after running the best-first search. This plan is directly sent to the \textsf{PostgreSQL}\xspace engine for execution. BAO adapts a different strategy than NEO. It learns to steer but not the replace the QO. Specifically, it also learns a latency prediction network which maps a query plan to its execution latency. For each query, it generates several plans corresponding to different hint sets and then selects the plan with the minimum predicted latency. Hence, to deploy BAO, data collection and model deployment need to be configured in exactly the same way as BAO and NEO. Note that the above discussion only concerns the case where both the BAO and NEO models have been trained to a certain point and then remained unchanged after deployment. However, both models have been designed to be updated in an online-manner, so that they may possibly adjust to changes in the underlying data and workload, without having to be explicitly retrained. While online updates are not directly supported yet, we note that model code running inside background workers could easily be written in such a way that incoming inference request data may simultaneously be used to updated the model running inside a worker. However, we note that - at least for now - it is then the responsibility of each such background worker to properly manage model state, ensure that model updates don't block future inference requests and deal with errors that might occur during online updates. \section{Open Source Release and Future Plans} \label{sect:conclusion} As development of \textsf{Baihe}\xspace has started only recently, it is not yet available for general use. However, we plan to release a first version of \textsf{Baihe}\xspace for \textsf{PostgreSQL}\xspace under an open source license in the beginning of 2022. This version should contain all of the essential functionality needed to build and experiment with learned query optimizers as described in the previous subsection. Later on, in the second half of 2022, we plan to release an extended version of \textsf{Baihe}\xspace which has seen first tests under real world conditions and supports production-mode deployments. The reasons for this release schedule are as follows: \begin{itemize} \item First, We hope to encourage community participation in the development of \textsf{Baihe}\xspace as soon as possible. \item Second, We wish to serve the DB research community by providing a flexible and easy to use experimental platform for for future research into AI4DB, hoping to establish a standardized and realistic test bed for future models and algorithms. \end{itemize} Overall, we hope to have provided convincing arguments for the soundness and practicality of \textsf{Baihe}\xspace as a design blueprint. The ongoing development of \textsf{Baihe}\xspace for \textsf{PostgreSQL}\xspace should further help refining this blueprint and serve as an implementation guide for other database systems. Besides the ongoing development, there are many avenues for future work. For instance, the current version of \textsf{Baihe}\xspace has been designed with most applications revolving around query optimization. However, one could envision \textsf{Baihe}\xspace to be used in the context of learned indices, database configuration tuning or other advisory functions. Another aspect that has been left out for now concerns the training process itself, as well as models which may benefit from online training. Integrating training and online updates of possibly large models directly into \textsf{Baihe}\xspace should certainly provide for many interesting system design challenges. Finally we note that the development of production mode deployment needs a custom model compiler infrastructure, which further adds to the many engineering and research challenges that accompany this line of work. We encourage the entire community to actively participate and accept some of these challenges. \bibliographystyle{ACM-Reference-Format} \subsection{\textsf{Baihe}\xspace Integration Layer and IPC Module} The \textsf{Baihe}\xspace integration layer is the central control unit of the \textsf{Baihe}\xspace extension: It is accessed from the host system by implementing some of the hooks already defined in \textsf{PostgreSQL}\xspace, where it implements \textsf{Baihe}\xspace's high level logic. All functionality for communication with background workers, as well as necessary process management for background workers is encapsulated in the IPC Module. The IPC module makes extensive use of Postgres core APIs used for management of shared memory, as well as process management. Additionally, the \textsf{Baihe}\xspace Integration Layer defines user defined functions and session variables which are necessary for controlling model handling and data collection, e.g. starting and stopping background workers, defining which models should be used in which situations, as well as defining when and how training data should be collected. \textbf{Shadow Planner.} To allow for a maximum degree of flexibility with respect to models providing input for query planning, the \textsf{Baihe}\xspace extension contains a customized duplicate of the core \textsf{PostgreSQL}\xspace planner as a "Shadow Planner" component. In this way we can achieve the following: First, we may freely add new hooks into the planner without having to modify core source code\footnote{Currently, \textsf{PostgreSQL}\xspace itself offers e.g. no hooks to overwrite cardinality estimation for e.g. single table queries or join size estimates}. Second, the behavior of the planner as a whole may be adjusted and new ideas tested without having to interfere with the core source. As an additional benefit, this reduces overall compilation and build times. Currently, in addition to the existing hooks originating from the original \textsf{PostgreSQL}\xspace code, we have equipped the shadow planner with the following hooks: \begin{itemize} \item Cost Model: we add an additional hook per "node" in a query plan. This allows for overwriting cost predictions for such operations as sequential scan, index scan, nested loop join, hash join etc. Furthermore, we incorporate hooks for estimating costs of query predicates making use of operations beyond comparison operators for numerical values. We plan to further support hooks for overwriting the cost estimation of user defined functions etc. \item Cardinality Estimation: We add hooks at several levels of the cardinality estimation process, such as cardinality estimation for a query involving a single table or a join between two tables. \end{itemize} To improve the interplay between hooks and planner code, we furthermore design the concrete hook signatures and calling code with error handling mechanisms allowing for seamless fallback to standard planner behavior in the case of errors originating e.g. from erroneous model inference calls. We discuss how shadow planner and related hooks are specifically used for query optimization task in Section~\ref{sect:example}. \subsection{Data Collection} The design of \textsf{Baihe}\xspace's data collection module borrows heavily from the popular \textsf{pg\_stat\_statements} extension for \textsf{PostgreSQL}\xspace. However, since \textsf{Baihe}\xspace targets data collection for training machine learning models, it takes a more dataset-centric point of view. More concretely, \textsf{Baihe}\xspace data collection is designed around the notion of "Data Collectors". Users may define and activate several Data collectors at the same time, where each data collector may be defined as a set of filter conditions plus a versioned data set identifier. In this way users may for each Data Collector specify the following: \begin{itemize} \item \textit{Filter conditions}: For which query type (SELECT, INSERT, ...) involving which tables should this data collector be applied? \item \textit{Dataset identifier and version}: For reproducibility a debugging purposes it is essential to keep track of exactly which data was used to train a specific model version. Hence, any data set collected is identified through both a dataset identifier as well as a version number. \item \textit{Features}: For some dataset and model combinations, only queries themselves might need to be collected, while for others it might be necessary to also collected generated query plans, together with estimated costs and actual run times both on query plan, as well as plan-node level. Users may flexibly specify, which features should be saved by a data collector \end{itemize} Data collection may be controlled entirely through a standard command session. After a data collector has been defined through a call to a \textsf{Baihe}\xspace stored procedure, the data collection process itself may also be started and stopped by running start and stop routines exposed from the \textsf{Baihe}\xspace extension through custom stored procedures. See Figure \ref{fig:usage_data} for an example. While a Data Collector is active, all collected data will be stored in shared memory.In the case of very large datasets, shared memory content may be temporarily stored on disk. Once data collection is stopped, a data set with incremented version identifier will be written to disk and made available in a table specified in the Data Collector's configuration. Training data may then easily be accessed through SQL. \subsection{Model Integration} \begin{figure*}[h] \centering \begin{subfigure}{8.5cm} {\color{darkgray} \textsf{\#\# Define a data collector}} \\ {\color{darkgray} \textsf{\#\# Filter queries by tables and query type}} \\ \textsf{CALL {\color{blue} DEFINE\_DATA\_COLLECTOR} ( ``CardEstCollector'', \\ \{ ``tbl\_users'', ``tbl\_items'', … \}, \{ ``SELECT'' \} ); } \\ {\color{darkgray} \textsf{\#\# Start data collection}} \\ \textsf{CALL {\color{blue}START\_DATA\_COLLECTOR} ( ``CardEstCollector'', \\ ``Data\_Set\_1'', ``tbl\_training\_data'' ); } \\ {\color{darkgray} \textsf{\#\# Stop data collection}} \\ \textsf{CALL {\color{blue}STOP\_DATA\_COLLECTOR} ( ``Data\_Set\_1''); } \\ \caption{Configuring data collection for a single cardinality estimation model. Only data related to SELECT queries touching certain tables is collected. Data collection can be started and stopped.} \label{fig:usage_model} \end{subfigure} \hfill \begin{subfigure}{8.5cm} {\color{darkgray} \textsf{\#\# Model Registration}} \\ \textsf{CALL {\color{blue} REGISTER\_MODEL} ( ``MyCardEstModel'', ``CARDEST'', \\ \{ ``tbl\_users'', ``tbl\_items'', … \}, ``tbl\_my\_cardest\_model\_stats'' ); } \\ {\color{darkgray} \textsf{\#\# Start Background Process for Model}} \\ \textsf{CALL {\color{blue} START\_MODEL} ( ``MyCardEstModel'' ); } \\ {\color{darkgray} \textsf{\#\# Stop Background Process for Model}} \\ \textsf{CALL {\color{blue} RESET\_MODEL} ( ``MyCardEstModel'' ); } \\ \caption{Deploying a trained model into the system: The model is used only for queries touching certain tables and maybe activated or deactivated when requested by the user.} \label{fig:usage_data} \end{subfigure} \hfill \caption{Example configuration sessions for \textsf{Baihe}\xspace} \label{fig:usage} \end{figure*} Along the lines of our requirements on minimization of dependencies and model inference and deployment as described in Section \ref{sect:background}, model inference takes place in background worker processes. For every model registered in \textsf{Baihe}\xspace, a user can request \textsf{Baihe}\xspace to start a background worker process, which will \begin{enumerate} \item Load the saved model from disk \item Connect to the \textsf{Baihe}\xspace shared memory space \item Wait for incoming inference requests on a message queue. \item Once an inference request is received, the background worker will run the request through the loaded model and return inference results (which may possible also just a flag indicating that an error has occurred). \end{enumerate} Once a query is submitted by a client to the corresponding \textsf{PostgreSQL}\xspace backend process, the query planning and execution process will be intercepted by the \textsf{Baihe}\xspace extension and depending on model type, a number of inference requests will be sent to the correct background workers. All communication is implemented asynchronously, so that a backend may fall back to standard functionality in case a background worker is not available. Out of the Box \textsf{Baihe}\xspace allows for the integration of custom models for query runtime prediction, as well as cost and cardinality estimation. Models of these types may be used directly without changes to the \textsf{Baihe}\xspace extension source code. More specific types of models, requiring e.g. new hooks at certain places in the planner code, may easily be supported with slight changes to the \textsf{Baihe}\xspace extension code. Similar to the data collection functionality described in the previous subsection, \textsf{Baihe}\xspace's model handling facilities are controlled and configured using a number of stored procedures and user defined functions implemented in the \textsf{Baihe}\xspace extension. A simple usage example is displayed in Figure \ref{fig:usage_model}: Through a standard command session users with the right permissions may request models to be registered and the corresponding background workers to be started or stopped. This allows for model updates without having to restart the entire system. As mentioned previously in Section \ref{sect:background} \textsf{Baihe}\xspace's focus is on model inference only. This means that the training process itself, that is solving the optimization process for a certain combination of model and training data, does not run in any \textsf{Baihe}\xspace components. Instead, the usual development process can be outlined as follows: \begin{enumerate} \item Training data is selected and downloaded using the \textsf{Baihe}\xspace support library, implemented as a Python packages. \item A model can then be defined and trained, preferably using a framework supported by \textsf{Baihe}\xspace's production mode. Currently supported frameworks are sklearn and Tensorflow. Training is controlled entirely by an expert user, such as e.g. a data scientist or machine learning engineer. \item Once the model has been trained and evaluated, it may be deployed using the \textsf{Baihe}\xspace support library. \begin{itemize} \item \textit{Development mode}: In this mode, the model is deployed as a Python model on the database servers file system, together with an automatically created environment containing all the model's dependencies. A background worker then uses an embedded Python interpreter to access the model. \item \textit{Production mode}: In this mode, \textsf{Baihe}\xspace's support library is used to compile the model including trained parameters into a shared library that is loaded dynamically by a background worker. The shared library does not depend on any external numerical or ML framework libraries. Model code itself will be compiled together with a number of math kernels (implementing e.g. matrix multiplications, convolutions, etc.) into a self contained component with a standardized interface. \end{itemize} \end{enumerate}
{'timestamp': '2021-12-30T02:23:41', 'yymm': '2112', 'arxiv_id': '2112.14460', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14460'}
arxiv
\section{Introduction} In many time series anomaly detection applications one only has access to unlabeled data. This data is usually mostly nominal but may contain some (unlabeled) anomalies. Examples of this setting are e.g.\ the widely used anomaly detection benchmarks SMAP, MSL \citep{Hundman2018telemanon}, and SMD \citep{omnianomaly} This ``true'' unsupervised setting with \emph{mixed} data can be contrasted with the ``nominal-only'' setting, where one assumes access to ``clean'' nominal data. In practice, techniques that (explicitly or implicitly) assume access to nominal data can often also successfully be applied to mixed data by assuming it is nominal, as long as the proportion of anomalies is sufficiently small., they are however biased by training on some anomalous data. While some time series anomaly detection model rely on the one class classification paradigm which does not suffer from this assumption \cite{thoc, ncad}, the vast majority of the current time series anomaly detection methods are either forecasting methods \citep{shipmon2017time, zhao2020multivariate} or reconstruction methods \citep{omnianomaly, donut, lstmvae, Zhang2019mscred}. Forecasting methods detect anomalies as deviations of observations from predictions, while reconstruction methods declare observations that deviate from the reconstruction as anomalous. In both cases, a probabilistic model of the observed data is assumed and its parameters are learned. However, by training the model on the observed data which contains both normal and anomalous data points, the model ultimately learns the wrong data distribution. \citet{ehrlich2021spliced} propose an approach to make the model robust to the anomalous points, still the aim is to learn the distribution of both the normal and the anomalous points. We propose to address this issue using a simple technique based on latent indicator variables that can readily be combined with existing probabilistic anomaly detection approaches. By using latent indicator variables to explicitly infer which observations in the training set are anomalous, we can subsequently suitably account for the anomalous observations while training the probabilistic model. Probabilistic models that use latent (unobserved) indicator variables to explicitly distinguish between nominal and anomalous data points are well-established in the context of robust mixture models \citep[e.g.][]{fraley1998many} and classical time series models \citep[e.g.][]{wang2018robust}. However, these techniques have not yet been utilized in the context of recent advances in \emph{deep} anomaly detection and time series modeling, presumably due to the (perceived) increased complexity of the required probabilistic inference and training procedure. We show that combining latent anomaly indicators with a Monte Carlo Expectation-Maximization (EM) \citep{wei1990monte} training procedure, results in a simple yet effective technique that can be combined with (almost) all existing deep anomaly detection and time series forecasting techniques. We demonstrate the effectiveness of our approach with a simple model for anomaly detection on the Yahoo anomaly detection dataset and on the electricity dataset for forecasting from a noisy training set. \section{Background} For non-time series data, one common approach of formalizing the notion of anomalies is to assume that the observed data is generated by a mixture model \citep{ruff2020unifying}: each observation $\B{x}$ is drawn from the mixture distribution $p(\B{x}) = \alpha p^{+}(\B{x}) + (1-\alpha)p^{-}(\B{x})$, where $p^{+}(\B{x})$ is the distribution of the nominal data and $p^{-}(\B{x})$ the anomalous data distribution. Typically one assumes a flexible parametrized distribution for $p^+$ and a broad, unspecific distribution for $p^{-}$ (e.g.\ a uniform distribution over the extent of the data). This mixture distribution can equivalently be written using a binary \emph{indicator latent variable} $z$ taking value $0$ with probability $p(z=0) = \alpha$ and value 1 with probability $p(z=1)=1-\alpha$, and specifying the conditional distribution \begin{equation} p(\B{x}|z) = \begin{cases} p^{+}(\B{x}) & \text{if}\ z = 0\\ p^{-}(\B{x}) & \text{if}\ z = 1, \end{cases} \end{equation} so that $p(\B{x}) = \sum_z p(\B{x}|z)p(z) = \alpha p^{+}(\B{x}) + (1-\alpha)p^{-}(\B{x})$. In this setup, anomaly detection can be performed by inferring the posterior distribution $p(z|\B{x})$ (and thresholding it if a hard choice is desired). Yet another way of representing the same model is generatively: first, draw $\B{y}^+ \sim p^+(\cdot)$, $\B{y}^- \sim p^-(\cdot)$, and $z \sim \text{Bernoulli}(1-\alpha)$, and then set $\B{x} = \mathbf{I}[z=0] \, \B{y}^+ + \mathbf{I}[z=1] \, \B{y}^-$, i.e.\ the observation $\B{x}$ is equal to $\B{y}^+$ if it is nominal ($z=1$) and equal to $\B{y}^-$ otherwise. Introducing the additional latent variables $\B{y}^+$ and $\B{y}^-$ is unnecessary in the IID setting, but becomes useful in the time series setting described next. In time series setting, where the the observations are time series $\B{x}_{1:T} = \B{x}_1, \ldots, \B{x}_T$ that exhibit temporal dependencies, and anomalies are time points or regions within these time series, we have one anomaly indicator variable $z_t$ corresponding to each time point $\B{x}_t$. Like before, the nominal data is drawn from a parametrized probabilistic model $p_\theta^+(\B{y}_{1:T})$, and the anomalies are generated from a fixed model $p^-(\B{y}_{1:T})$. For time series data, the mixture data model then amounts to drawing $\B{y}_{1:T}^+ \sim p^+(\cdot)$, $\B{y}^-_{1:T} \sim p^-(\cdot)$, and $z_{1:T} \sim p^z(z_{1:T})$, and setting $\B{x}_t = \mathbf{I}[z_t=0] \, \B{y}^+_t + \mathbf{I}[z_t=1] \, \B{y}^-_t$. \section{Method} Forecasting or reconstruction models are designed to learn a model of $p^+(\cdot)$ but are typically trained directly on the observed time series $\B{x}_{1:T}$. We propose to learn the model of $p^+(\cdot)$ only from $\B{y}_{1:T}^+$ by inferring $z_{1:T} \sim p^z(z_{1:T})$ on the training set. This way we can train the model only on the observed points that are normal, the ones that are equal to $\B{y}_{1:T}^+$. Depending on the model, the anomalous points can be treated as missing or the normal point can be inferred. \subsection{Models} Each of the three latent time series is modeled with a probabilistic model: a parametrized model $p^+_\theta$ of the nominal data $\B{y}_{1:T}^+$, a fixed model $p^-$ to model the anomalous data $\B{y}_{1:T}^-$, and a model $p^z$ of the indicator time series $z_{1:T}$. \paragraph{Nominal Data Model} Many existing deep anomaly detection methods aim to model the nominal data (e.g.\ \citep{shipmon2017time, zhao2020multivariate, omnianomaly, donut, lstmvae, Zhang2019mscred, ehrlich2021spliced}), and any of them can be used to model $\B{y}^+$, the latent nominal time series. Our method is agnostic to the type of model used, so that it can be combined with any probabilistic time series model, be it a deep or shallow probabilistic forecasting method, a reconstruction method, or any other type of model. We call the model of the latent normal time series $p^+_\theta$, which is parametrised by a set of parameters $\theta$. In our experiments we demonstrate the general setup by modeling $p^+(\B{y}^+_{1:T})$ with a simple deep probabilistic forecasting model. We decompose $p(\B{y}^+_{1:T})$ into the telescoping product $p(\B{y}^+_0) \prod_{t=0}^{T} p(\B{y}^+_{t+1} | \B{y}^+_{t:0})$ and, making an $l$-th order Markov assumption, approximate it with a network $p(\B{y}^+_{t+1} | \B{y}^+_{t:t-l} ) = \mathcal{N}(f_\theta(\bm{y}_{t:t-l}), g_\theta(\bm{y}_{t:t-l}) )$ taking as input the last $l$ time points. \paragraph{Anomalous Data Model} A simple model can be used to model $p^-$, it does not need to take into account the time component as there are typically few anomalous points. It can be modeled with a mixture of Gaussian distributions for example, with the risk of over-fitting to the few anomalies of the train set. We simply model $p^-$ with a uniform distribution over the domain of the training data, not assuming any prior on the kind of anomalies that we may expect. \paragraph{Anomaly Indicator Model} We model the latent anomaly indicator with a Hidden Markov Model (HMM) with two states, state ${z}_t = 0$ corresponds to the point being normal and state ${z}_t = 1$ corresponds to the point being anomalous. Any kind of time series model parameterizing a Bernoulli distribution can be used to model the latent anomaly indicators, we pick an HMM as it encodes basic time dependencies while staying a simple model. If it is available, prior knowledge about the dataset can be used to initialise the transition matrix. The expected length of anomalous windows can be used to initialise the transition probability $p( z_{t+1} = 1 | z_t = 1 )$. The expected percentage of anomalous points in the dataset can be used to initialise the transition probability $p( z_{t+1} = 1 | z_t = 0 )$. \iffalse is the prior probability of a point being anomalous, we can either: \begin{enumerate} \item set it to 0.01 by default as we assume that anomalies are rare (the one thing that we can assume in anomaly detection) \item use a prior that we have for this specific dataset \item have a prior given by labels on the dataset : e.g. 0.9 for points that are labeled as anomalous and 0.001 for the other ones \end{enumerate} $p_{+}^*(\bm{y}_{t+1}) = \mathcal{N}(f_\theta(\bm{y}_{t:t-l}), g_\theta(\bm{y}_{t:t-l}) )$ We model with a forecasting model, as of now, a Gaussian parametrised by a NN : This model takes into account the time dependencies of the points, and so knowing which points are anomalous has two advantages: \begin{enumerate} \item we do not train the model to predict them (not including them in the loss) \item we can replace/mask the anomalous points in the context window and so not have the model train on anomalous input \end{enumerate} \fi \subsection{Training} Our training procedure follows Monte Carlo EM \citep{wei1990monte}. In the E-step we infer $ p^z(z_{1:T})$. In the M-step we sample from $p^z(z_{1:T})$, using these samples to update $p^+_\theta$ and the transition matrix of the HMM. Algorithm \ref{alg} sketches this procedure. \begin{algorithm}[htpb] \SetAlgoLined \KwIn{Observed time series $\B{x}_{1:T}$, model to be trained $p^+_\theta$ } \For{$e \in \{1, \dots, \text{numb\_epochs}\}$}{ \tcp{E-step:} $\rightarrow$ infer $p^z(z_{1:T})$ \tcp{M-step:} \For{$s \in \{1, \dots, \text{numb\_samples}\}$}{ $\rightarrow$ sample indicator time series $z_s$ from $p^z(z_{1:T})$ $\rightarrow$ perform one epoch of $p^+_\theta$ on $\B{x}_{\neg z_s}$ where the points at sampled anomalous indices are replaced } $\rightarrow$ update the transition matrix of the HMM } \caption{Monte Carlo EM for Latent Anomaly Indicator} \label{alg} \end{algorithm} \subsubsection{E-step} We infer $p^z(z_{1:T})$ by using the standard forward-backward algorithm for HMMs, using the following distributions: \begin{align} p(\B{x}_t | z_t = 0) = p^+_\theta(\B{x}_t) \\ p(\B{x}_t | z_t = 1) = p^-(\B{x}_t) \end{align} and $p(z_{t+1} | z_t)$ is given by the HMM transition matrix. \iffalse (we abuse a bit the notation here: $p(p_- | \bm{y}_t)$ is the posterior probability that the point t comes from the anomalous data distribution) For each point, we want to infer the probability of this point coming from the anomalous model: $$p(p_- | \bm{y}_t) = \frac{p(\bm{y}_t | p_-) p(p_-)}{p(\bm{y}_t)} = \frac{p(\bm{y}_t | p_-) p(p_-)}{p(\bm{y}_t | p_-) + p(\bm{y}_t | p_+) } $$ First, simply using Bayes rule, then using the fact that we have: $p(\bm{y}) = p_{+}(\bm{y}) + p_{-}(\bm{y})$ are obtained with our trained model for the normal data and the model for the anomalous data \fi \subsubsection{M-step} We want to train $p^+(\cdot)$ only from $\B{y}_{1:T}^+$. As most models may not allow for an analytical update using $\bm{x}_{1:T}$ and $z_{1:T}$, we propose to a Monte Carlo approximation of the expectation under $p^z(z_{1:T})$. We draw multiple samples from $p^z(z_{1:T})$ giving us possible normal points on which $p^+_\theta$ can be trained. Each path sampled gives us a set of observed points that can be considered as coming from the normal data distribution $p^+$. We maximise the probability of these points under $p^+_\theta$, treating the points coming from $p^-$ points as missing. Depending on the choice of model for $p^+_\theta$, one may not be able to simply ignore anomalous points and they would have to be imputed. For deep forecasting or reconstruction models for example the model has to be given an input for each time point. In these cases, we propose to impute the point with the forecast or reconstruction obtained from $p^+_\theta$ at the last M-step. This way, we use $p^+_\theta$ to infer the time points of $ \B{y}_{1:T}^+$ that were not observed. With this method we can recover the full $\B{y}_{1:T}^+$ time series and train $p^+_\theta$ on it. Depending on the choice of model for $p^-$, one can update it using the points that are sampled as coming from $ \B{y}_{1:T}^-$. We can update the transition matrix of the HMM with the classical M-step. The average number of transitions from one state to the next in the samples from $p^z(z_{1:T})$ become the new transition probabilities. \iffalse We train the forecasting model by masking the inferred anomalous points from the input vector. We sample independently for each time point if it comes from or not. If we sample it, we replace it by the predicted mean $ f_\theta(\bm{y}_{t:t-l})$ obtained at the last epoch. In addition we ignore the loss for the points that we sample as coming from the anomalous distribution. This procedure allows to use mini batch training very easily: \begin{enumerate} \item we sample the points to ignore for the whole training set \item we replace them in the input time series \item we can do minibatches using this modified input time series \end{enumerate} For each training epoch, we sample 20 time from the distribution. \fi \subsection{Inference} At inference time, we propose to use the HMM to perform filtering on $z$ and infer if incoming points are more likely to be drawn from $p^+$ or $p^-$. If an incoming point $\B{x}_t$ is more likely to be coming from $p^-$ it can be treated as missing or replaced with a sample from $p^+_{\theta t}$ or by its mode. This way we ensure that the trained model is only used on points coming from $\B{y}_{1:T}^+$. \section{Experiments} \iffalse \fi We make our code available with an illustration notebook. \footnote{ \url{https://github.com/Francois-Aubet/gluon-ts/blob/monte_carlo_em_masking_ notebook/src/gluonts/nursery/anomaly_detection/Monte-Carlo-EM- for-Time-Series-Anomaly-Detection-demo-notebook.ipynb}} \paragraph{Model} We evaluate our approach with a simple forecasting model on both anomaly detection and forecasting tasks. We show the performance of the model when trained in a standard way and when trained with our procedure, which we call our procedure Latent Anomaly Indicator (LAI). We use a simple Multi-Layer Perceptron (MLP) model to parametrise the mean and the variance of a predictive Gaussian distribution. It takes as input the last 25 points. \paragraph{Datasets} For the anomaly detection evaluation, we use the \textbf{Yahoo} dataset, published by Yahoo labs.\footnote{\url{https://webscope.sandbox.yahoo.com/catalog.php?datatype=s&did=70}} It consists of 367 real and synthetic time series, divided into four subsets (A1-A4) with varying level of difficulty. The length of the series vary from 700 to 1700 observations. Labels are available for all the series. We use the last 50\% of the time points of each of the time series as test set, like \citep{ren2019time} did, and split the rest in 40\% training and 10\% validation set. We evaluate the performance of the model using the adjusted F1 score proposed by \citet{donut} and subsequently used in other work. In addition, we evaluate the method on forecasting tasks using the commonly used \textbf{electricity} dataset \cite{electricity}, composed of 370 time series of 133k points each. Given the length of the dataset, we sub-sample it by a factor 10. We select the last 50\% of the points of each time series for testing. We scale each time series using the median and inter-quartile range on the train~set. \subsection{Visualization on synthetic data} Figure \ref{fig:synthetic_ts} visualizes the advantage of the method on a simple sinusoidal time series with the simple MLP for $p^+_\theta$. We generate a synthetic time series and inject outliers in it. We observe that our approach allows to train the model $p^+_\theta$ while ignoring the outliers in the data, whereas the outliers heavily influence the model trained conventionally. We observe from figure \ref{fig:masking_pi} that the model is able to infer accurately which of the training points are likely to be anomalous. \begin{figure}[t] \begin{subfigure}{.5\textwidth} \includegraphics[width=.99\textwidth]{figures/normal_model_fit} \caption{The fit of a simple MLP without LAI.} \label{fig:normal_model_fit} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.99\textwidth]{figures/masking_model_fit} \caption{The fit of a simple MLP with LAI.} \label{fig:masking_model_fit} \end{subfigure} \begin{subfigure}{.5\textwidth} \includegraphics[width=.99\textwidth]{figures/masking_pi} \caption{The time series of latent anomaly indicator $p(z_t = 1)$.} \label{fig:masking_pi} \end{subfigure} \caption{ We fit a MLP on this simple synthetic time series with anomalies. (a) shows the fit of the model trained in a conventional way, (b) shows the fit of the model trained as we propose to, (c) show the inferred $p(z_{1:T})$ distribution at the end of the training. } \label{fig:synthetic_ts} \end{figure} \subsection{Time series anomaly detection} Table \ref{table:test_set} shows the F1 score of the model with and without LAI on the different subsets of the Yahoo dataset. We train one MLP on each of the time series and average the F1 scores obtained on the different time series of the subset. We observe that using our approach greatly improves the performance of the model. \begin{table}[h] \caption{F1 score on the different subsets of the Yahoo dataset.} \label{table:test_set} \centering \begin{tabular}{l|cccccccccccc} \toprule Model & A1 & A2 & A3 & A4 \\ \midrule MLP & 33.64 & 53.28 & 63.25 & 47.30 \\ MLP + LAI & 41.84 & 87.26 & 87.91 & 61.62 \\ \bottomrule \end{tabular} \end{table} \iffalse ARIMA: Yahoo A1: Normal average: 0.3363546742021299 LAI average: 0.4183863827943147 Yahoo A2: Normal average: 0.5328321386575404 LAI average: 0.8726312951525773 Yahoo A3: Normal average: 0.6324923474686052 LAI average: 0.8790611366231169 Yahoo A4: Normal average: 0.4730399846547243 LAI average: 0.6161590733402865 LSTM: \fi In addition to the improved F1 score, we compare the inferred anomalous points on the training set with the actual labeled anomalous points. Table \ref{table:train_set} shows the F1 score on the training set when using the anomaly indicator as anomaly score. We observe that our method allows to find accurately the anomalies present in the training set. While the training and test sets are different, we propose that the higher F1 on the train set is due to the fact that the model can use the whole training set to infer if a point is anomalous, and not only the past points. \begin{table}[H] \caption{F1 score on the training set the different subsets of the Yahoo dataset using the inferred $p(z_{t}=1)$ as anomaly score.} \label{table:train_set} \centering \begin{tabular}{l|cccccccccccc} \toprule Model & A1 & A2 & A3 & A4 \\ \midrule MLP + LAI & 59.48 & 94.02 & 81.89 & 73.77 \\ \bottomrule \end{tabular} \end{table} \subsection{Forecasting using a corrupted train set} Our method can be used more generally to train a forecasting model on a forecasting dataset containing anomalies. We take the electricity forecasting dataset and inject point outliers in the training set so that about 0.4\% of the training point have an added or subtracted spike. Table \ref{table:forecasting} shows the mean absolute error (MAE) on the test set in the setting where the original train set is used and in the setting where the noisy train set is used. We see that using our method allows to reduce significantly the increase in error from the outliers in the training set, only 0.0146 increase in the mean absolute error versus 0.0542 when training the model normally. \begin{table}[H] \caption{MAE on electricity with and without injecting point outliers in the train set} \label{table:forecasting} \centering \begin{tabular}{l|cccccccccccc} \toprule Model & electricity & electricity + outliers \\ \midrule MLP & 0.1551 & 0.2092 \\ MLP + LAI & 0.1558 & 0.1704 \\ \bottomrule \end{tabular} \end{table} \section{Conclusion} We present LAI, a method that can be used to wrap any probabilistic time series model to perform anomaly detection without being impacted by unlabeled anomalies in the training set. We present the details of the approach and propose preliminary empirical results on commonly used public benchmark datasets. The approach seems to greatly help both for anomaly detection tasks and for training a forecasting model on a contaminated training set. One can extend this work by wrapping other bigger models such as OmniAnomaly \citep{omnianomaly} or state-of-the-art forecasting models \citep{benidis2020neural}. Finally, with our current method at inference time, one has to decide at each incoming point if it is to be replaced or not, one could use particles which would mimic the Monte Carlo approach of the training time. \newpage \ \newpage
{'timestamp': '2021-12-30T02:22:21', 'yymm': '2112', 'arxiv_id': '2112.14436', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14436'}
arxiv
\section{} \section{Introduction} During the COVID-19 pandemic, we have seen a revolution of the contact tracing technology, which helped track and contain the epidemic \cite{braithwaite2020automated,kretzschmar2020impact}. Some contact tracing programs were conducted by governmental/health agencies \cite{park2020contact}, while others relied on decentralized approaches \cite{troncoso2020decentralized}. Most contact tracing approaches work by notifying people who could have received the infection from known infectious patients, i.e., they trace ``forward'' in time. However, some advocate that a ``bidirectional'' tracing, where the past history of the infection is also tracked, can be more effective \cite{bradshaw2021bidirectional,endo2020implication,kojaku2021effectiveness}. In this paper we focus on the ``backward'' direction of the problem; the task of identifying the first patient who carried the disease, also called patient zero, or the source of the epidemic. The identification of patient zero can either be limited to a smaller population cluster, in which case it can be a first step towards ``bidirectional'' tracing, or it can be more ambitious; finding the first patient who developed the mutation of a certain disease can help understanding how the mutation occurred, which can help us prevent, or better prepare for future epidemics. Surprisingly, given the importance of the problem and the relatively large literature on the topic, we are not aware of any instance where source detection algorithms have been applied in real situations, including during the COVID-19 pandemic. Our goal in this paper is to examine the applicability of the source detection models in the literature (which we call frameworks from now on), and then propose a new framework, which improves them in several aspects. Originally, source detection was introduced in the context of rumor spreading instead of epidemics by Zaman and Shah in their pioneering Sigmetrics paper~\cite{shah2010rumors,shah2011rumors}. Translating to the language of epidemics for clarity, in the framework of \cite{shah2011rumors}, an epidemic spreads over a network of agents that is completely known to us, and we observe a \textit{snapshot} of the network, which means that every agent reveals if they are infected or not at some given time (not too early, because then the problem is trivial, nor too late, because then the problem is impossible). Shortly after \cite{shah2011rumors}, Pinto et al. proposed a different framework, in which agents (also called \textit{sensors}) reveal, in addition to their state, the time when they became infected, but where only a few of them do so and act as sensors \cite{PintoTV12}; indeed, the problem is trivial if all agents are sensors. This framework is better tailored to epidemics, as it is reasonable that obtaining any information from all the agents is much harder than asking one more question about the starting time of the symptoms of the disease to only some of them. Pinto et al. found that in their framework, if the sensors are already selected, the maximum likelihood estimator of the source has a closed form solution when the underlying network is a tree, and the time it takes for an agent to infect one of its susceptible contacts follows a Gaussian distribution. For general graphs, it is difficult to find an algorithm with any theoretical guarantees, although we note that many heuristics have been developed \cite{hu2018localization,li2019locating,paluch2018fast,paluch2020locating,shen2016locating,tang2018estimating,xu2019identifying,zhu2016locating}. The only exception is on very simple contact networks \cite{lecomte2020noisy}, or when the epidemic spreads deterministically between the agents \cite{zejnilovic2013network}, which is not a realistic assumption for epidemics, but at least the estimation algorithm is trivial, and more emphasis can be put on the question of how the sensors should be selected for good performance \cite{spinelli2017effect,spinelli2018many}, which again is studied by heuristics in the general case \cite{paluch2020optimizing}. For a recent review of source detection algorithms, see \cite{shelke2019source}. One of the main criticisms of original framework of Pinto et al. is that, even though the contact network is fully known, it is very difficult to find the source exactly unless a large fraction (20-50\%) of the population act as sensors, which is unrealistic in the case of an epidemics, when the source is searched in a large population. An alternative recently proposed is to compute confidence sets for the source instead of finding it \cite{dawkins2021diffusion}. But if our goal is to locate the source exactly, a promising approach is to allow the sensors to be selected adaptively to previous observations \cite{zejnilovic2015sequential,zejnilovic2017sequential}, which we call \textit{adaptive sensor placement}. When the contact network is known, adaptive strategies have been studied by simulations \cite{spinelli2017general,spinelli2017back} and by theoretical analysis \cite{lecomte2020noisy}, and they show a large reduction in the number of required sensors in real networks. In this paper, we will also allow the sensors to be placed adaptively. We believe that the most problematic assumption that is still present in source detection papers, is the full knowledge of the contact network of agents, which is unrealistic (let alone because of privacy concerns). Due to this lack of data-availability, algorithms in the source detection literature have not been tested on realistic epidemic data. Moreover, while governmental/health agencies might have access to private datasets, such as cellular location data, from which a contact network may be estimated, these networks may be very noisy, and are potentially unfit for the source detection task. We only know of a few papers that study the effect of imperfections in the network data on the source detection task \cite{mashkaria2020robustness,zejnilovic2016extending}, but these papers study epidemics that spread deterministically between the agents. Inspired by adaptive sensor placement, and by the recent implementations of contact tracing algorithms, we propose a new framework for source detection, which we call Source Detection via Contact Tracing Framework (SDCTF). In SDCTF, algorithms can have two types of queries: contact queries, which can be used to explore the network, and sensor (test) queries, after which agents reveal their symptom onset time as before. The goal of the algorithm is to find the source as accurately as possible, while minimizing the number of contact and sensor queries. The SDCTF is a way to formalize the source detection task; it determines the goal of the algorithm and how information can be gained about the epidemic, but it does not specify the underlying epidemic and mobility data models (simulated or real). In this paper, we analyse different algorithms in the SDCTF with various epidemic and mobility models. Besides specifying the possible queries that algorithms can make, the SDCTF also determines the way the outbreak is detected, which marks the starting time of the source detection task. In sensor-based source detection, the source detection task often starts long after the outbreak, when essentially all agents in the network are infected \cite{PintoTV12}, which can be seen as a limitation of source detection frameworks. The SDCTF is also closely related to contact tracing frameworks, where it is standard to assign a probability that each node spontaneously self-reports after developing symptoms, which triggers the activation of contact tracing algorithms \cite{kretzschmar2020impact,bradshaw2021bidirectional}. In the SDCTF, we adopt the idea of self-reporting with a slight modification. We believe that the most interesting time to perform the source detection task is when a new disease (or a new mutation of the disease) appears, and therefore we tie these self-reporting events to hospitalizations, where infections are properly diagnosed by healthcare professionals. In particular, this means that the SDCTF can only be applied to epidemic data (and models) where hospitalizations are well-defined. In this paper, we use the datasets generated by the Data-driven COVID Simulator (DCS) introduced in \cite{lorch2020quantifying}, which is one of the most realistic toolboxes that generate datasets modelling COVID-19, which we are aware of (notably, hospitalizations are part of the model). We also propose synthetic approximations for the epidemic and mobility models in the DCS; the Deterministically Developing Epidemic model and the Household Network Model, which improve the interpretability of our results since they have fewer parameters. We propose a simple algorithm called LocalSearch (LS), which adaptively traces back the transmission path from the first hospitalized patient to the source. The LS algorithm is quite efficient at finding the source; the number of contact and sensor queries that it uses does not depend on the size of the network, but only on the local neighborhood of the source. Moreover, the LS algorithm provably finds the source with 100\% accuracy, because of our assumption that every contact and sensor query is answered without noise. However, it is well-known that data-availability is a major issue in contact tracing \cite{beidasrinad2020optimizing}, either because the agents do not comply with contact tracing efforts, or possibly (and in particular in the current COVID-19 epidemic) because they do not develop symptoms, and are unaware that they have the disease. In this paper, we model the effect of asymptomatic agents. When queried and tested, these agents do not reveal their time of infection, only whether they have or had the disease at some point. We show that the accuracy of the LS algorithm drops in the presence of asymptomatic agents, because the algorithm can get stuck while tracing back the transmission path from the first hospitalized patient to the source. Therefore, we propose an improved version of LS called LS+, which accounts for the presence of asymptomatic agents by placing more sensors. We are not aware of any previous work in the source detection literature that models the effect of asymptomatic patients, but the resulting model can be seen as a mix between the snapshot and the sensor-based models. We mention that non-complying agents or agents who provide noisy observations have been studied by \cite{altarelli2014patient,hernando2008fault,louni2015identification}. Non-complying agents could also be included in our framework by treating them as asymptomatic agents (even though in this case we have no information about whether the agent had the disease or not), without jeopardizing the correctness of our algorithms. We benchmark the LS and LS+ algorithms in both our data-driven and our synthetic epidemic and mobility models, and we compare them to state-of-the-art adaptive \cite{spinelli2017back} and non-adaptive \cite{jiang2016rumor,lokhov2014inferring} algorithms tailored to the SDCTF, whenever possible. We find that both LS and LS+ outperform these baseline algorithms in accuracy (probability of finding the correct source). While the LS/LS+ are designed to be simple algorithms, their theoretical analysis is quite challenging. Nevertheless, we are able to provide rigorous results about the success probability of both algorithms after a series of simplifications to the epidemic and mobility models, by extending some recent results on the theory of exponential random trees \cite{feng2018profile,mahmoud2021profile}, which have previously not been connected to the source detection literature. We present these theoretical results in Section~\ref{sec:theory}, after formally introducing the SDCTF, our models and the LS/LS+ algorithms in Section~\ref{sec:models}. By simulations, we show that our analytic results approximate the accuracy of the algorithms well, even in the most realistic setting in Section~\ref{sec:simulation}. Our analytic results provide additional insight into how the parameters of the epidemic and mobility models affect the performance of the algorithms. We discuss these insights along with some non-rigorous computations that mirror our main proof ideas in Section~\ref{sec:boe_sec}. Reading Section~\ref{sec:boe_sec} before Sections~\ref{sec:models}-\ref{sec:simulation} is useful to build intuition, but is not necessary to understand the paper. \section{Warmup Results} \label{sec:boe_sec} \subsection{A Simple Network and Epidemic Model and a Simple Algorithm} \label{sec:boe_model} \begin{figure} \begin{center} \includegraphics[width=\textwidth]{images/boe_fig.pdf} \caption{(a)-(c) shows the spread of the infection in the model considered in Section~\ref{sec:boe_model}, which is equivalent to the growth of the RERT, with $d=2$. Dark blue edges show the contacts on day~$t$, and light blue edges show contacts present on previous days (and thus subfigures). Orange (resp., red; black) nodes mark symptomatic non-hospitalized (resp, asymptomatic; symptomatic hospitalized) nodes. (d)-(f) shows the LS source detection algorithm introduced in Section~\ref{sec:boe}, which succeeds in this example because there are no asymptomatic nodes on the transmission path between the first hospitalized node and the source. Black edges show the queried edges, and black stroke marks nodes already discovered by the algorithm. A node with black X marks a negative test result, and red stroked node marks the node currently maintained as source candidate by the LS algorithm.} \label{fig:boe} \end{center} \end{figure} Let us consider a time-dependent network model, where each agent meets $d$ new agents each day in such a way that the contact network is an infinite tree (ignoring the label of the edges giving the propagation time along the edge). This network models homogeneous mixing in a very large population; we consider more realistic network models in Section~\ref{sec:models}. On this network, we consider an epidemic model that starts at $t=0$ with one infected agent, and then progresses as infected agents infect their $d$ susceptible contacts each independently with probability $p_i$ each day. Since our goal is to study the epidemic process, it is sufficient to track only the agents who are already infectious (also called \emph{internal nodes}), and the agents who are in contact with infectious agents at time~$t$ (also called \emph{external nodes}), as shown in Figure \ref{fig:boe} (a)-(c). For $d=1$, the spread of the infection is then equivalent to the growth a random tree $\mathcal{T}_t$ rooted at the source of the infection, known under the name of Random Exponential Recursive Tree (RERT) and recently introduced in \cite{mahmoud2021profile}. Because of the similarities of the models, we refer to the model with general $d$ as RERT in the remaining of this section. We point out that the standard literature on elementary branching processes such as Galton-Watson trees or random recursive trees \cite{drmota2009random} is not applicable in our scenario, because these branching processes have no notion of global time (i.e., a node in such processes becomes infectious immediately after receiving the infection), whereas nodes in diseases commonly go through an exposed, non-infectious period before becoming infectious, which is well captured by the RERT model. We mention that there is literature on more advanced branching processes that do have a notion of global time, e.g. Crump-Mode-Jagers trees \cite{jagers1984growth}, however we opt for the RERT because of its simple definition. After a node (patient) becomes infected, the disease can take three courses (which for now do not affect $\mathcal{T}_t$): with probability $p_a$ the patient is asymptomatic, with probability $(1-p_a)p_h$ the patient is hospitalized, and with probability $(1-p_a)(1-p_h)$ the patient recovers without hospitalization. The governmental/health agency learns about the outbreak when the first hospitalization occurs (see Figure~\ref{fig:boe} (c)) and starts the source detection process right away. It can inquire about the contacts of each agent and it can test the agents. From patients that were symptomatic (at any point in time in the past), the agency learns about their symptom onset time (which, in this simple model, is always one day after the infection time), but from asymptomatic patients it only learns that they had (or have) the disease at some point when they are tested. The framework introduced in this paragraph (including both the detection of the outbreak through the first hospitalization, and the possible actions the agency can take) is a simplified version of the SDCTF (Source Detection via Contact Tracing Framework), introduced in Section~\ref{sec:SDCTF}. The network and epidemic models introduced in this section have four parameters: $d, p_i, p_a, p_h$, and it is important to understand how each of them affects the difficulty of source detection in the SDCTF. We distinguish two important factors. First, if the outbreak is not detected rapidly enough, the length of the transmission path to the first hospitalized agent is long, and source detection becomes then difficult, because a lot of information needs to be recovered. Therefore, a low $p_i$, a low $p_h$ and/or a high $p_a$ parameter can hinder source detection (recall that the probability of hospitalization was $p_h(1-p_a)$). The second factor is related to the difficulty of recovering information about the transmission path. If $p_a$ is high, then there are a lot of nodes who are asymptotic and therefore do not reveal their symptom onset time, making source detection very difficult. Since $p_a$ affects both the length of the transmission path and the amount of collected information, it is safe to expect that, of all parameters, $p_a$ has the largest effect on the difficulty of source detection. The parameter $d$ is interesting, because a large $d$ can reduce the length of the transmission path, but it also makes the information about the transmission path less accessible as more agents need to be tested. Since in this paper we do not set a hard constraint on the total number of available tests, the advantage of a shorter path takes over the drawback of additional tests and a large $d$ increases the success probability. To say anything quantitative about source detection in the SDCTF, we must discuss specific algorithms that solve the source detection task. In this paper we propose a simple algorithm called LocalSearch (LS), shown in Figure~\ref{fig:boe}~(d)-(f). The LS algorithm maintains one candidate node $s_c$ at each iteration (initially, the first hospitalized node), which is always symptomatic, and it updates it in a greedy way: at the time of the infection of $s_c$, all its $d$ incident edges are queried, and all its $d$ neighbors are tested. Then the agent with the lowest reported infection time will be the new candidate $s_c$. The algorithm stops when $s_c$ does not change anymore between two consecutive iterations. For simplicity, we assume that the infection does not spread any further during these iterations, however, this assumption does not affect the ability of the algorithm to find the source or not. Indeed, it is not difficult to see that on tree networks, LS succeeds if and only if there are no asymptomatic nodes on the transmission path from the source to the first hospitalized agent. This observation leads us to enhance the LS algorithm by also searching within the neighbors of asymptomatic nodes; we explore this idea in the LS+ algorithm introduced in Section~\ref{sec:localsearch}. We are not aware of this simple greedy algorithm being studied in the context of source detection, although similar ideas were implemented for non-adaptive source detection to lower the runtime of the algorithms \cite{paluch2018fast}. \subsection{Back of the Envelope Calculation} \label{sec:boe} Now, we have all the tools to estimate the probability of success of the LS algorithm. First we condition on the course of the disease in the source. With probability $p_a$, the source is asymptomatic and LS can never succeed. With probability $(1-p_a)p_h$, the source itself becomes hospitalized, and LS always succeeds. Finally, with probability $(1-p_a)(1-p_h)$ the source is symptomatic but not hospitalized, which we call event $\mathcal{A}$. If event $\mathcal{A}$ happens, then LS may or may not succeed depending on whether there are any asymptomatic nodes on the transmission path. More precisely, conditioned on event $\mathcal{A}$ and on the transmission path having length $l$, the probability of success is $(1-p_a)^{l-1}$ (since there are $l-1$ nodes on the path which can be asymptomatic), which implies \begin{equation} \label{eq:boe_ps1} \P(\mathrm{success}) = (1-p_a)p_h+ (1-p_a)(1-p_h) \left(\sum_{l=1}^t \P\left(\text{transmission path has length $l$} \mid \mathcal{A} \right) (1-p_a)^{l-1} \right). \end{equation} The difficult part is to compute the distribution of the transmission path conditioned on event $\mathcal{A}$; indeed we already saw that all four parameters $d, p_i, p_a, p_h$ affect this distribution in a non-trivial way. Let us perform a back of the envelope computation to get more insight into the effect of these parameters. The exact structure of the infection tree will not matter for this computation, only its \textit{profile} does. It is denoted by $\mathcal{T}_t(l)$ and defined as the number of (internal) nodes at level $l$ (i.e., at distance $l$ from the source of the infection). Remember that by definition the RERT has $d \cdot \mathcal{T}_{t-1}(l-1)$ external nodes on level $l$, and that at time~$t$ each external node is promoted to be internal with probability $p_i$ to form $\mathcal{T}_t$. Consequently, the level of a node~$h$ added at time $t>0$ has the same distribution (conditioned on the tree $\mathcal{T}_{t-1}$ at the previous step) as the size (number of internal nodes) of the profile $\mathcal{T}_{t-1}(l-1)$, that is, \begin{equation} \label{eq:back_of_envelope_def} \P(\mathrm{level}(h)=l \mid \mathcal{T}_{t-1}=T_{t-1}) = \frac{T_{t-1}(l-1)}{|T_{t-1}|}. \end{equation} Working on the RERT directly can be a daunting task, therefore we propose to approximate the numerator and the denominator of equation \eqref{eq:back_of_envelope_def} by $\mathbf{E}[\mathcal{T}_{t-1}(l-1)]$ and $\mathbf{E}|[\mathcal{T}_{t-1}|]$, respectively. It can be shown by a simple inductive argument, or by generating functions as in \cite{mahmoud2021profile}, that for RERTs we have $\mathbf{E}[\mathcal{T}_{t}(l)]=\binom{t}{l} (dp_i)^l$ and $\mathbf{E}[|\mathcal{T}_{t}|]=(1+dp_i)^t$, which suggests a binomial distribution for the level of $h$. And indeed, we can approximate the distribution of the level of a node $h$ added at time $t$ as \begin{align*} \P(\mathrm{level}(h)=l) &\approx \frac{\mathbf{E}[\mathcal{T}_{t-1}(l-1)]}{\mathbf{E}[|\mathcal{T}_{t-1}|]} \\ &=\frac{\binom{t-1}{l-1} (dp_i)^{l-1}}{(1+dp_i)^{t-1}}\\ &=\binom{t-1}{l-1}\left(\frac{ dp_i}{1+dp_i}\right)^{l-1} \left(1-\frac{ dp_i}{1+dp_i}\right)^{t-l} \\ &= \P(\mathrm{Bin}(t-1,q) = l-1), \end{align*} with $q=dp_i/(1+dp_i)$. One of the main challenges of this calculation is that we do not know the day of the first hospitalization $t$ conditioned on event $\mathcal{A}$, we only know that each node is hospitalized with probability $(1-p_a)p_h$, which means that the index of the first hospitalized node follows a geometric distribution with mean $1/((1-p_a)p_h)$. We approximate $t-1$ by the first time that the expected size of the infection tree (excluding the source since we condition on event $\mathcal{A}$) exceeds the expected index of the first hospitalized node. Therefore we solve $$\mathbf{E}[|\mathcal{T}_{t-1}|-1]=(1+dp_i)^{t-1}-1 = \frac{1}{(1-p_a)p_h}=\mathbf{E}[\text{index of the first hospitalized node}]$$ for $t$ (relaxing the constraint that $t$ is an integer), which gives $$t-1= \frac{\log \left(1+\frac{1}{(1-p_a)p_h} \right)}{\log(1+dp_i)}.$$ Consequently, we approximate $\P\left(\text{transmission path has length $l$} \mid \mathcal{A} \right)$ by $\P(\mathrm{Bin}(t-1,q) = l-1)$. Continuing equation \eqref{eq:boe_ps1}, and using the well-known expression of the probability generating function of the binomial distribution, we get \begin{align} \label{eq:two} \P(\mathrm{success}) &\approx (1-p_a)p_h+ (1-p_a)(1-p_h) \left(\sum_{l=1}^t \P\left(\mathrm{Bin} \left(t-1, q \right)=l-1 \right) (1-p_a)^{l-1} \right) \nonumber \\ &= (1-p_a)\left(p_h + (1-p_h) \left((1-p_a)\frac{dp_i}{1+dp_i}+1-\frac{dp_i}{1+dp_i}\right) ^{\frac{\log\left(1+\frac{1}{(1-p_a)p_h}\right)}{\log(1+dp_i)}} \right). \end{align} One can check that this expression agrees with our qualitative intuition. However, it is not at all clear whether it is valid because of the strong approximations made in some steps of the above computation. In Section \ref{sec:theory}, we prove a rigorous upper bound on the success probability, and we also provide much more careful approximations by proving exact theorems about the simplified models that we use. Then, in Section \ref{sec:simulation} we compare our results with simulation results on synthetic data, as well as with data generated by the DCS model. \section{Models, Methods, Algorithms} \label{sec:models} \subsection{Epidemic Models} \label{sec:epidemic_models} \subsubsection{The DCS Model} \label{subsub:DCS} We call DCS the model implemented by \cite{lorch2020quantifying}. The DCS model is fairly complex, and we only give a brief overview. Each agent in the agent set $V$ can be in one of 8 states: susceptible, exposed, asymptomatic infectious, pre-symptomatic infectious, symptomatic infectious, hospitalized, recovered or dead. Transitions between different states are characterized by counting processes described by stochastic differential equations with jumps. The most important, and also most complicated of these counting processes is the exposure counting process $N_i(t)$, which is modeled by a Hawkes process for each agent~$i$. Hawkes processes are point processes with a time-dependent, self-exciting conditional intensity function $\lambda^*_i(t)$. \begin{equation} \label{eq:Hawkes} \hspace*{-5pt} \lambda^*_i(t) = \beta \sum_{j \in V \backslash \{i\}} \int_{t - \delta}^{t} K_{i,j}(\tau) ~ \gamma e^{-\gamma(t-\tau)} \, d\tau \end{equation} where the kernel $K_{i,j}(\tau)$ indicates whether $j$ has been at time $\tau$ at the same site where $i$ is at time $t$, and whether $j$ is in the infectious state. Parameters $\gamma$ and $\delta$ are the decay of infectiousness at sites and the non-contact contamination window, respectively, and they account for the fact that $j$ can infect $i$ even if they are never at the same site, as $j$ can leave some pathogens behind (airborne for instance). Parameter $\beta$ is the transmission rate for symptomatic and asymptomatic individuals, and it comes in two versions: $\beta_c$ accounts for infections outside the household and $\beta_h$ accounts for infection in the household. Parameters $\beta_c$ and $\beta_h$ are fitted to the COVID-19 infection data of Tubingen from 12/03/2020 to 03/05/2020 using Bayesian Optimization. The model also has a parameter for the relative asymptomatic transmission rate built into the function $K_{i,j}(\tau)$, which scales down the infectiousness of asymptomatic agents (to 55\% of the infectiousness of symptomatic agents by default). Once a susceptible agent becomes infected, the disease can take three possible courses (see Figure~\ref{fig:mobility_models}~(a)). With probability $p_a$, the agent becomes asymptomatic infectious after time $T_E$, and then recovers after time $T_I$. With probability $1-p_a$, the agent becomes pre-symptomatic infectious after time $T_E$, next symptomatic infectious after time $T_P$, and then recovers with probability $1-p_h$ after time $T_I-T_P$, or becomes hospitalized with probability $p_h$ after time $T_H$. Agents in the DCS are also assigned age values based on demographic data, and the hospitalization probability $p_h$ of each agent is determined based on its age (following COVID-19 infection data). The times $T_E, T_P, T_I$ and $T_H$ are drawn from an appropriately parametrized (using values from the COVID-19 literature) lognormal distribution as shown in Table \ref{tab:Tvalues}. \subsubsection{The DDE Model} \label{subsub:DDE} We start by taking the DCS model \cite{lorch2020quantifying}, which we simplify to enable its theoretical analysis. In the Deterministically Developing Epidemic (DDE) model, continuous time (used in DCS) is replaced by discrete time-steps: we refer to one time-step in the DDE as one day. Instead of modelling the infection propagation as a Hawkes process, an infectious agent (symptomatic or asymptomatic) can infect its susceptible neighbor with probability $p_i$ each day. Thereafter, the disease progresses the same way as in the DCS, except that in the DDE model the transition times are deterministic (the infection events and the severity of the disease (i.e., the (a)symptomatic and hospitalized states) are still determined randomly), and we have a single parameter $p_h$ for the hospitalization probability (agents in this model do not have an age parameter). We discuss how we set the parameters of the DDE model in Section \ref{sec:parameters}. \begin{figure} \begin{center} \includegraphics[width=\textwidth]{images/mobility_models.pdf} \caption{(a) The flow diagram of the DCS and DDE epidemic models. (b) A possible epidemic outbreak in the Tubingen mobility model, and (c) the Household network model. The large grey circles mark households, and the purple nodes mark places, otherwise we use the same coloring as in (a). In both cases (b) and (c), the transmission paths are $(v_2, v_4, v_5, v_8)$. } \label{fig:mobility_models} \end{center} \end{figure} \subsection{Simulating Mobility} \label{sec:mobility} \subsubsection{Tubingen Mobility Model} \label{sec:TU} We briefly review the mobility model introduced in \cite{lorch2020quantifying}, and illustrated in Figure~\ref{fig:mobility_models}~(b). The population is partitioned into households of possibly varying size (usually between 1 and 5). The households are assigned a location, and we also place some external sites (shops, offices, schools, transport stations, recreating sites) on the map, which the agents may visit. The location of the households and the number of agents in them is sampled randomly based on demographic datasets. Initially, each agent is assigned a few favorite sites (randomly based on distance), and will only visit these throughout the simulation. Each agent decides to leave home after some exponentially distributed time, visits one of its (randomly chosen) favorite sites, and comes back home after another (usually much shorter) exponentially distributed time. If two agents visit the same site at the same time, or within some time $\delta$, we record them as a contact, which gives an opportunity for the infection to propagate. We denote the Tubingen mobility model as TU, and the DCS epidemic model that runs on the TU mobility model as DCS+TU. \subsubsection{Household Network Model} \label{sec:HNM} The Household network model (HNM) was inspired by \cite{lorch2020quantifying}, however we note that similar models have been studied in the theoretical community by~\cite{ball2009threshold}. As in the Tubingen mobility model, in HNM $N$ nodes are assigned into households, but of constant size $d_h+1$. Every pair of nodes in the same household are connected by an edge, forming therefore cliques of size $d_h+1$. Additionally, each node is assigned $d_c$ half edges, which are paired uniformly at random with other half-edges in the beginning. Some half-edge pairings can result in self-loops or multi-edges, which are discarded. This construction defines a random graph generated by a configuration model, which shares a lot of similarities with Random Regular Graphs (RRG) \cite{wormald1999models}. In fact, if we join nodes in the same household into a single node in the HNM (which we refer to as the \textit{network of households} of the HNM), then the resulting graph is equivalent to the \textit{pairing model} of RRGs with degree $d_c(d_h+1)$. It is well-known that in the pairing model of RGGs of degree $d$, the local neighborhood (of constant radius, as the number of nodes tends to infinity) of a uniformly randomly chosen vertex is a $d$-regular tree (with probability tending to 1), which implies that locally there are asymptotically almost surely no self-loops, multi-edges or any cycles in the graph. This result has various names; in random graph theory the result is usually proved by subgraph counting \cite{wormald1999models}, in probability theory it is the basis of branching process approximations \cite{ball2009threshold}, and in graph limit theory it is called the local convergence to the infinite $d$-regular tree~\cite{benjamini2011recurrence}. In our theoretical analysis, this result motivates the approximation of the neighborhood of the source in the network of households of the HNM by an infinite $d_c(d_h+1)$-regular tree. The HNM itself is then approximated by replacing each (household) node of the infinite $d_c(d_h+1)$-regular tree of households by a $(d_h+1)$-clique, and by setting the edges so that each (individual) node has degree exactly $d_c+d_h$, while keeping the connection between cliques unchanged (see Figure~\ref{fig:mobility_models}~(c) for a visualization). Since the HNM is a time-independent graph, we adopt the standard notations from graph theory. Formally, the HNM is given by the set of nodes and edges $G=(V,E)$. Let us denote by $H(v)$ the set of nodes that are in the same household as node $v$. The distance between two nodes $u,v \in V$ (denoted by $d(u,v)$) is defined as a number of edges of the shortest path between $u$ and $v$. We denote the DDE epidemic model that runs on the HNM network as DDE+HNM. \subsection{The Source Detection via Contact Tracing Framework} \label{sec:SDCTF} We present the Source Detection via Contact Tracing Framework (SDCTF), which can be applied to both epidemic and mobility models presented so far. The framework determines how the government/health agency, which conducts the source detection task, learns about the outbreak, and how it can gather further information to locate the source. In the SDCTF, as in Section \ref{sec:boe_model}, the agency learns about the outbreak when the first hospitalization occurs, and it also learns the identity of nodes when they become hospitalized (including the identity of the first hospitalized node). After the outbreak is detected, the agency can make three types of queries. The first type of query, the household query with parameter $v$, reveals the agents that live in the same household as $v$. The household query works the same way in both the TU and the HNM models, and we do not limit the number of times it can be called (these queries are considered as cheap in the SDCTF). The second type of query, the contact query, works differently in the TU and the HNM models. For the TU model, a contact query has two parameters: an agent $v$ and a time window $[t_1,t_2]$. As a result, all agents that have been in contact with $v$ (and therefore could have infected $v$ or could have been infected by $v$) at an external site between $t_1$ and $t_2$ are revealed. In the HNM, no time window is needed for the contact query (which we also call edge query), and all neighbors of $v$ in graph $G$ are revealed. Contact (and edge) queries are considered expensive in the SDCTF. While in this paper we do not limit the number of available queries, we track the number of contacts and edges that are revealed as the algorithm runs. Note that in the TU model if two agents $v_1$ and $v_2$ have been in contact during the time window $[t_1, t_2]$ and also during a different time window $[t_3,t_4]$, then those are counted as separate contacts, whereas in the HNM an edge between $v_1$ and $v_2$ is only counted once. Although contact queries are considered expensive, both household and contact queries are answered instantly in the SDCTF. The third kind of query is the test query with parameter $v$, which reveals information about the course of the disease in the queried agent (see Figure \ref{fig:mobility_models}~(a)). Symptomatic patients reveal the time of their symptom onset (which exactly determines their time of infection in the DDE due to the deterministic transition times) if they are past the pre-symptomatic state (i.e., if they are either infectious or recovered). Asymptomatic and pre-symptomatic patients do not reveal any information about their infection time; they just reveal that they have the disease or had the disease at some point and have recovered. For all algorithms we assume that asymptomatic patients do not reveal whether they have the infection at the time they are queried. Finally, agents who have not been exposed, or are still in their exposed state, give a negative test result. Test queries are again considered expensive in the SDCTF, we even limit the population that can be tested on any given day to at most 1\% of the total population, due to the capacity of testing facilities. However, since in this paper we do not limit the number of days that the algorithm can use to locate the source, the limit on the number of tests does not play an important role. As opposed to household and contact queries (and the model in Section \ref{sec:boe_model}), tests results are only answered the next day in the SDCTF, which means that the algorithms must operate in ``real-time'', while the epidemic keeps propagating. \subsection{Parameters} \label{sec:parameters} \begin{figure}[h] \begin{center} \includegraphics[width=\textwidth]{images/table1.png} \caption{Default values for the infection parameters in the DCS+TU and the DDE+HNM models.} \label{tab:Tvalues} \end{center} \end{figure} The DCS+TU model has many parameters, most of which are fitted to COVID-19 datasets of Tubingen from 12/03/2020 to 03/05/2020 by \cite{lorch2020quantifying} (we show the most relevant parameters in Table \ref{tab:Tvalues}). We determined the parameters of the DDE+HNM model so that they fit the parameters of the DCS+TU as closely as possible (see the precise values in Table \ref{tab:Tvalues}). We determine the values of $T_E, T_P, T_I$ in the DDE+HNM by rounding the expected value of the corresponding distribution in the DCS+TU to the nearest integer. Since $p_a$ is simply a constant in both models, we keep the same numerical value in the DDE+HNM. The parameter $p_h$ is more complicated, because in the DCS+TU model there is a different hospitalization probability for each age group. We take the average hospitalization probability across the population to be $p_h$. The most complicated parameter to fit is $p_i$, because in the DCS+TU model, infections are modelled by a Hawkes process, which depends on many parameters, including whether the infectious agent is symptomatic or asymptomatic, the length of the visit, the site where the infection happens, etc (see equation \eqref{eq:Hawkes}). We empirically observe the probability of infection in every contact in several simulations, and we find that an agent has on average 15 contacts outside the household each day, and that the average probability of infection during such a contact is around 0.02. However, since we use smaller networks for the DDE+HNM ($N=400$ or $1000$, because running the baselines on larger networks is not feasible) than the DCS ($N=9054$), setting $d_c$ to be as high as 15 would violate the assumption that the network of households of the HNM can be locally approximated by a tree (see Section~\ref{sec:HNM}). Therefore we chose $d_c=3$ for the HNM and we scale $p_i$ so that $d_cp_i$ (the expected number of external infections caused by a single agent each day) is the same in the DCS+TU and the DDE+HNM models. Finally, we choose $d_h$ in the DDE+HNM by rounding the average household connections in the DCS+TU. Note that the average number of household connections is not the same as the average number of household members, because the number of connections grows quadratically in the size of the households, and thus fitting to the number of connections results in a higher $d_c$ (due to the Quadratic Mean-Arithmetic Mean inequality). Finding the default values for the parameters is useful to create a realistic model. However, we also interested in the effect of each of the parameters on the performance of our algorithms. Therefore, in the DDE+HNM, we vary the parameters $p_a,p_h,p_i,d_h$ and $d_c$, while keeping the other ones unchanged. For the DCS+TU model, we also keep the mobility model fixed and we focus on varying the parameters $p_a,p_h$ and $p_i$. As noted above, there is no single parameter $p_h$ or $p_i$ in the DCS+TU model, therefore we change all hospitalization probabilities and all intensities of the Hawkes processes so that the hospitalization probability averaged across the population and the infection probability averaged across contacts equal the desired values. \subsection{The LocalSearch Algorithms LS and LS+} \label{sec:localsearch} The LS algorithm finds patient zero by local greedy search. It keeps track of a candidate node, which is always the node with the earliest reported symptom onset time. We denote the candidate of the algorithm at iteration $i>0$ by $s_{c,i}$. We think of $s_c$ as a list, which is updated in each iteration of the algorithm, and we use the notation $s_{c,-1}$ for the last element of the list (i.e., the current candidate). In each iteration of the algorithm, we compute a new candidate denoted by $s_c'$, and we append it at the end of the list $s_c$ at the beginning of the next iteration, unless $s_c'=s_{c,-1}$, in which case the algorithm terminates. \begin{figure}[h] \begin{center} \includegraphics[width=\textwidth]{images/Alg_1.pdf} \caption{Pseudocode and graphical explanation for the LS and LS+ algorithms. We use the same coloring as in Figure \ref{fig:mobility_models}~(a). Black edges show the queried edges, a node with black X marks a negative test result, and red stroked node marks the node currently maintained as source candidate by the LS algorithm. We denote by $t_v$ the symptom onset time of symptomatic node $v$ and by $H(v)$ the household of a node $v$ similarly to the main text. } \label{fig:Alg1_figure} \end{center} \end{figure} Since we consider the SDCTF, the outbreak is detected when the first hospitalized case is reported. At that time, $s_c'$ is initialized to be the hospitalized patient, the test queue is initialized to be empty, and the algorithm is started. In the beginning of an iteration, if the test queue is empty, the household members and the ``backward'' contacts of the current candidate $s_{c,-1}$ are queried and are added to the test queue (see Figure~\ref{fig:Alg1_figure}~(a)). We define ``backward'' contacts as the set of nodes that have been in contact with $s_{c,-1}$ in the interval $[t_{s_{c,-1}} - (T_E+T_P) - (\sigma_E +\sigma_P),t_{s_{c,-1}} - (T_E+T_P) + (\sigma_E +\sigma_P)]$, where $t_{s_{c,-1}}$ is the symptom onset time of current candidate $s_{c,-1}$. The terms $\sigma_E$ and $\sigma_P$ model the standard deviation of the transition times, and they are set to zero for the DDE and to $\sigma_E=2$ and $\sigma_P=1$ for the DCS based on Table \ref{tab:Tvalues}. We note that the notion of ``backward'' contacts is only meaningful in the case of time-dependent network models; for the HNM, all neighbors are counted as backward contacts. After the test queue is initialized, the agents inside the queue are tested (see Figure \ref{fig:Alg1_figure}~(b)). Not all nodes can be tested on the same day because of the limitation on the number of tests available per day in the SDCTF, however, this has little effect because we do not proceed to the next iteration until the test queue becomes empty. Once the test results come back to the agency, if any of the (symptomatic) nodes $v$ reports an earlier symptom onset time than the current candidate $s_{c,-1}$, then we update our next candidate $s_c'$ to be $v$ (see Figure \ref{fig:Alg1_figure}~(c)). We note that the iteration does not stop immediately after $s_c'$ is first updated; the iteration runs until the test queue becomes empty, and until then, $s_c'$ can be updated multiple times. This is important in the theoretical results to prevent the algorithm from getting sidetracked (see Figure~\ref{fig:LSp_cases}). We also experimented with a version of the LS and LS+ algorithms where the iteration stops immediately once $s_c'$ is updated; we call these algorithms LSv2 and LS+v2. The main drawback of the LS algorithm is that is gets stuck very easily if there is even one asymptomatic node on the transmission path. For this reason, we introduce the LS+ algorithm, in which we enter the backward contacts of the asymptomatic household members of $s_{c,-1}$, and the household members of any asymptomatic node into the testing queue (see Figure \ref{fig:Alg1_figure}~(d)-(f)). Since the symptom onset times of asymptomatic nodes $v$ are not revealed, we define backward contact in this case as any contact in the time window $[t_{s_{c,-1}} -(T_P+2T_E+T_I), t_{s_{c,-1}} - (T_P+2T_E)]$, where $t_{s_{c,-1}}$ is still the symptom onset time of the current candidate $s_{c,-1}$. Indeed, in the DDE model, since $s_{c,-1}$ was infected at $t_{s_{c,-1}} -(T_P+T_E)$, if $v$ infected $s_{c,-1}$, agent $v$ must have been infectious at that time, which implies that $v$ could not have been infected later than $t_{s_{c,-1}} -(T_P+2T_E)$ or earlier than $t_{s_{c,-1}} -(T_P+2T_E+T_I)$. In the DCS model, the terms $\sigma_E$ and $\sigma_P$ can be subtracted and added to the two ends of the queried time window to account for the randomness in the transition times. Both algorithms stop if the testing queue becomes empty before a node with an earlier symptom onset time than $s_{c,-1}$ is discovered, and both algorithm return $s_{c,-1}$ as their inferred source. The high level pseudocode and an illustration of the LS and LS+ algorithms are given in Figure~\ref{fig:Alg1_figure}. \section{Theoretical Results} \label{sec:theory} In this section we present theoretical results for the LS and LS+ algorithms described in Section~\ref{sec:localsearch}. We follow a similar approach as in the non-rigorous computation in Section~\ref{sec:boe}, which useful but not necessary for understanding this section. All the statements are rigorously established, and whenever we reach a point where the computations would become intractable, we propose a simpler approximate model to study. One of the main contributions of this paper is to identify which computations can be done on more general models, and which computations need more simplified ones (see Figure~\ref{fig:overview} for an overview of the different models used for the computations in this section). We compute the success probability of the LS and LS+ algorithms in two steps. We first assume the length of the transmission path known in Section~\ref{sec:lsp_succes} . This computation is then made possible by a tree approximation of the HNM, called the Red-Blue (RB) tree (defined in Section~\ref{subsub:RBtree}), and a slightly modified version of the DDE model called $\mathrm{DDE}_{\mathrm{NR}}$ (defined in Section~\ref{subsub:DDENR}). The RB tree preserves some of the household structure in the HNM, and therefore allows us gain insight into the difference between the LS and LS+ algorithms, which would be difficult to obtain if we had worked on trees without taking the household structure in account. For the second step, we would need to compute the distribution of the transmission path on the RB tree. However, finding a closed form expression is intractable. Instead, we combine the network and epidemic models into a growing random tree model, and we consider a $d$-ary Random Exponential Tree (RET). The $d$-ary RET model has only been studied for $d=2$ \cite{feng2018profile}; we extend the results on their expected profile for general $d$ in Section~\ref{subsub:RET}. Nevertheless, working on $d$-ary RETs still remains difficult, and therefore, in our last modeling step, we introduce a Deterministic Exponential Tree (DET) model, whose profile is close to the expected profile of the RET, and we compute the distribution of the transmission path on this model in Section~\ref{subsub:DET}. \begin{figure} \begin{center} \begin{subfigure}[b]{\textwidth} \caption{} \includegraphics[width=\textwidth]{images/Figure1_a.pdf} \label{fig:y equals x} \end{subfigure} \hfill \begin{subfigure}[b]{\textwidth} \caption{} \centering \includegraphics[width=\textwidth]{images/Figure1_b.pdf} \label{fig:three sin x} \end{subfigure} \caption{The different approximation methods (a) and the distribution of the length of transmission path in the different models (b) proposed in Section~\ref{sec:theory}. Panel (b) also shows the length of the transmission path in the DCS model on the TU dynamics, to highlight the fit of our model.} \label{fig:overview} \end{center} \end{figure} To summarize all models considered in this paper, we have a data-driven and a synthetic model for simulations (DCS+TU and HNM+DDE), an analytically tractable model (RB-tree+$\mathrm{DDE}_{\mathrm{NR}}$) where we can compute the success probability if the length of the transmission path is known. In a second stage, we compute the distribution of a transmission path on a deterministic tree (DET), which has a similar profile as a random tree (RET) that approximates our analytically tractable model. We visualize these five different models in Figure~\ref{fig:overview}~(a), and we show by simulations in Figure~\ref{fig:overview}~(b) that the distribution of the transmission path is similar in all of the considered models with appropriately scaled parameters. We compare our analytic results on the success probabilities of the LS and LS+ algorithms with our simulation results in Section \ref{sec:comp_theory} in Figure~\ref{fig:theory_plots}. \subsection{Success Probability of LS and LS+ Algorithms on the RB Tree} \label{sec:lsp_succes} In this section we introduce the Red-Blue (RB) tree model (which is a tree approximation to the HNM), and we calculate the exact probability that the LS and LS+ algorithms succeed, if the length of the transmission path is known. \subsubsection{Red-Blue tree models} \label{subsub:RBtree} In short, a RB tree is a two-type branching process with a deterministic offspring distribution that depends on $d_h$ and $d_c$. The lack of randomness in this distribution makes us adopt the formalism of deterministic rooted trees. \begin{definition} \label{def:RBtree} Let a rooted tree, denoted by $G(s)$, be a tree graph with a distinguished node root node $s$. Let $u$ and $v$ be two nodes connected by an edge in $G(s)$. If $d(u,s) < d(v,s)$, we say that $u$ is a parent of $v$, otherwise $u$ is a child of $v$. Moreover, if $d(s,v) = l$ we say that $v$ is on level $l$. An RB tree with parameters $(d_c, d_h)$ is an infinite rooted tree, such that the nodes also have an additional color property. The root is always colored red and the rest of the nodes are colored red or blue. The root has $d_c$ red and $d_h$ blue children. Every other red node has $d_c-1$ red and $d_h$ blue children, and every blue node has $d_c$ red children and no blue children. Red nodes and their $d_h$ blue children partition the nodes of the RB tree $G(s)$ into subsets of size $d_h+1$, which we call households. \end{definition} \begin{remark} \label{rem:RBdef} In the RB tree, each blue node has degree $d_c+1$, and each red node has degree $d_c+d_h$, including the root of the tree $s$ (which is the source of the epidemic, when the RB tree is combined with an epidemic model). \end{remark} The RB tree can be seen as a local tree approximation of the HNM. Let $G=(V,E)$ be an HNM with parameters $(d_c,d_h)$, and let $s \in V$ be the distinguished source node. In Section \ref{sec:HNM} we noted that the HNM can be approximated locally around the source node by replacing each node of an infinite $d_c(d_h+1)$-regular tree by a $(d_h+1)$-clique, and setting the edges so that each node has degree exactly $d_c+d_h$, while keeping the connection between cliques unchanged. Let us call this infinite graph $G^*$. Although $G^*$ is not a tree, all cycles in $G^*$ must be contained entirely inside the households, which implies that in each household there exists exactly one node that has the minimal distance to the source. We will refer to these nodes with minimal distance to the source as the red nodes, and we color the rest of the nodes blue. In other words, the red nodes will be the first ones in their households to be infected. Let us now delete the edges between the blue nodes in $G^*$ to obtain graph $G'$. We claim that $G'$ is isomorphic to the RB tree $G(s)$ rooted at the source~$s$. Indeed, since the edges between blue nodes have been deleted in $G^*$ to form $G'$, each blue node has $d_c+1$ red neighbors and no blue neighbor, and since the edges incident to red nodes have been unchanged, each red node has $d_c$ red and $d_h$ blue neighbors, exactly as in the definition of RB tree above. Note that a household in $G^*$ is completely characterized by only specifying the colors of the nodes: a household always consists of one red node and of its $d_h$ blue children. We use this characterization as a definition for households in the RB tree $G'$, because it does not depend on the edges from $G$ that are deleted in $G^*$, whereas this deletion makes the original definition of a household as a clique in $G$ unusable. Next, we make some important observations the behaviour of the LS and the LS+ algorithms on RB trees, which we prove in Appendix \ref{sec:LS,LSp,trees_app}. We start by formalizing the notion of transmission path. \begin{definition} \label{def:inf_path} Let $h$ be the first hospitalized node and $s$ be the source. We call the path $(s = v_0, v_1, ... v_l = h)$, where $v_{i}$ is the infector of $v_{i+1}$ for $0 \leq i < l$, the \emph{transmission path}. Also we call the path $(v_l, v_{l-1}, ... v_1)$ the \emph{reverse transmission path}. \end{definition} \begin{remark} \label{rem:RBtree} Note that in an RB tree, each household traversed by a transmission path shares one (the red node in the household) or two (the red node of the household and one of its $d_h$ children in the household) nodes with this path. Moreover, the red node of a household traversed by a transmission path is followed by another red node on the path (in another household) if it is the only node of that household on the transmission path, whereas it is followed by a blue node (in the same household) if two nodes of that household are on the transmission path. \end{remark} \begin{lemma} \label{lem:LS,LSp,trees} In the RB tree network, the LS algorithm succeeds if and only if all nodes on the transmission path are symptomatic, and the LS+ algorithm succeeds if among the nodes of the transmission path, there exists a symptomatic node in each household, and the source is symptomatic. \end{lemma} \begin{remark} We note that the statement for LS+ in Lemma \ref{lem:LS,LSp,trees} cannot be reversed, i.e., it is possible that LS+ succeeds even if among the nodes of the transmission path, there is a household with no symptomatic node (see Figure \ref{fig:LSp_cases}~(a)). Also, the proof of Lemma \ref{lem:LS,LSp,trees} does not hold if the LS+ algorithm proceeds to the next iteration at the first time $s_c'$ is updated (see Figure \ref{fig:LSp_cases}~(b)). Finally, in the proof of Lemma \ref{lem:LS,LSp,trees}, we do not make any assumptions about asymptomatic patients having had the disease previously or not, which implies that we could treat non-complying agents as asymptomatic patients without jeopardizing the correctness of the algorithms. \end{remark} \subsubsection{The $\mathrm{DDE}_{\mathrm{NR}}$ Model} \label{subsub:DDENR} Focusing on tree networks is an important step towards making our models tractable for theoretical analysis, but it will not be enough; we will make two minor simplifications to the DDE model as well: we eliminate (i) the pre-symptomatic state and (ii) the recovered state, and we call the new model $\mathrm{DDE}_{\mathrm{NR}}$ (where NR stands for No Recovery). (i) The first assumption can be made without loss of generality, because the pre-symptomatic state does not have any effect on the disease propagation, nor on the success of the source detection algorithm. Indeed, according to Lemma \ref{lem:LS,LSp,trees}, the success of the LS and LS+ algorithms depends only on the information gained about the transmission path, and by the time of the first hospitalization, every node on the transmission path must have left the pre-symptomatic state (since we always have $T_P<T_E+T_H$), even if we include it in the model. (ii) The second assumption on the absence of recovery states amounts to take $T_I \rightarrow \infty$, which does have a small effect on the disease propagation, however, this effect is minimal because $T_I=14$ is already quite large, and because only the very early phase of the infection is interesting for computing the success probabilities of the algorithms. Finally, this last assumption has no effect on the information gained by the algorithm since we assumed that recovered patients (who were symptomatic) can remember and reveal their symptom onset time in the same way as symptomatic infectious patients. \subsubsection{Success Probability of LS} Assuming that the distribution of length of the transmission path is provided for us (we give an approximation in Section \ref{sec:depth_dist}), the success probability of LS can be computed succinctly. We need a short definition before stating our result. \begin{definition} \label{def:p} Let $p$ be the probability that a node is asymptomatic conditioned on the event that it is not hospitalized. \end{definition} A simple computation shows that \begin{equation} \label{C5} p=\P ( v \text{ is asy} \mid v \text{ is not hosp})=\frac{p_a}{p_a +(1-p_a)(1-p_h)}. \end{equation} \begin{lemma} \label{lem:LSsucc} For the $\mathrm{DDE}_{\mathrm{NR}}$ epidemic model with parameters $(p_i, p_a, p_h)$ on the RB tree with parameters $(d_c, d_h)$, and with $p$ computed in equation \eqref{C5}, we have \begin{equation} \label{eq:LS_success_RB_tree} \P(LS \textrm{ succeeds}) = \sum_{n=0}^{\infty} \left(1-p\right)^n \P(d(s,h) = n). \end{equation} \end{lemma} \begin{proof} Let us reveal the randomness that generates the epidemic in a slightly modified way than in the definition (Sections \ref{subsub:DDE} and \ref{subsub:DDENR}). As before, at the beginning only the source is infectious, and depending on course of the disease, the source can be symptomatic and hospitalized, symptomatic but not hospitalized, or asymptomatic with probabilities $(1-p_a)p_h, (1-p_a)(1-p_h), p_a$, respectively. In each moment, each infectious node infects each of its susceptible neighbors with probability $p_i$. If a node is infected, we reveal the information whether it will become hospitalized (which happens with the probability $(1-p_a)p_h$), but if it does not become hospitalized, we do not reveal whether the node is asymptomatic or symptomatic yet. Indeed, this information is not necessary for continuing the simulation of the epidemic since we assumed that there is no difference between the infection probabilities of symptomatic and asymptomatic nodes. Thereafter, when the first hospitalized case occurs, we reveal for each infected node $v$ on the transmission path (except the last node, which we know is hospitalised; see Definition \ref{def:inf_path}) whether it is asymptomatic or not. The only information we have about these nodes is that they are not hospitalized, which implies that the probability that a node is revealed to be asymptomatic on the transmission path is exactly the probability $p$ from Definition \ref{def:p} computed in \eqref{C5}. By Lemma \ref{lem:LS,LSp,trees}, LS succeeds if and only if each node on the transmission path is symptomatic. Conditioning on the length of the transmission path, we can compute the probability of each node being symptomatic by equation \eqref{C5} as \begin{equation} \P(LS\textrm{ suceeds} | d(s,h) = n)=\left(1- \P(v \textrm{ is asy}| v\textrm{ is not hosp}) \right)^n=\left(1-p\right)^n, \end{equation} from which \eqref{eq:LS_success_RB_tree} follows immediately. \end{proof} \subsubsection{Success Probability of LS+} Computing the success probability of the LS+ algorithm is far more challenging compared to the LS algorithm, even if the distribution of the length of the transmission path is provided to us. Indeed, since the LS+ algorithm does further testing on the contacts and household members of asymptomatic nodes, it is essential to have additional information about the number of households on the transmission path. We give our main result on the LS+ in the next theorem, which we prove in Appendix \ref{sec:thrm:LSp_suc}. \begin{theorem} \label{thrm:LSp_suc} Let $p$ be as in \eqref{C5} and let $\mathcal{S}(n,\alpha,\beta)$ be the set of $k$ integer values such that $k$ and $n$ have different parity and $n+1 - 2(\alpha + \beta) \geq k \geq 2-(\alpha+\beta)$. Then, for the $\mathrm{DDE}_{\mathrm{NR}}$ epidemic model with parameters $(p_i, p_a, p_h)$ on the RB tree with parameters $(d_c, d_h)$, we have \begin{align} &\P(LS+ \textrm{ succeeds}) \ge \P(d(s,h) = 0) + (1-p)\P(d(s,h)=1)+ \nonumber \\ & \sum_{n = 2}^{\infty} \sum_{\substack{\alpha,\beta \in \{0,1\} \\ k \in \mathcal{S}(n,\alpha,\beta)}} \binom{\frac{n+k-3}{2}}{k-2+\alpha+\beta} \frac{(d_h(1-p))^{\frac{n+k-1}{2}}(d_c(1+p))^{\frac{n-k+1}{2}-\alpha-\beta}d_c(d_c-1)^{k+\alpha + \beta-2}}{\lambda_1\left( \frac{d_c-1+D}{2}\right)^n + \lambda_2\left( \frac{d_c-1-D}{2}\right)^n} \P(d(s,h)=n), \end{align} where \begin{align} D &= \sqrt{(d_c-1)^2 +4d_cd_h} \\ \lambda_1 &= \frac{(d_c+1+D)(2d_h+d_c-1+D)}{2D(d_c-1+D)} \\ \lambda_2 &= \frac{(D-d_c-1)(2d_h+d_c-1-D)}{2D(d_c-1-D)}. \end{align} \end{theorem} \subsection{Approximating the Depth of the Path to the First Hospitalized Node} \label{sec:depth_dist} Section \ref{sec:lsp_succes} was dedicated to the success probability of the LS and LS+ algorithms, however, in these results, we are still missing the distribution of the transmission path length. In this subsection we address this problem by introducing simpler approximate models. \subsubsection{$(d_r, d)$-ary Random Exponential Tree} \label{subsub:RET} When we introduced the $\mathrm{DDE}_{\mathrm{NR}}$ model in Section \ref{subsub:DDENR}, we removed both parameters $T_P$ and $T_I$ from the DDE model (by removing the presymptomatic and the recovered states, respectively), but we kept the parameter $T_E$. In this step we will rescale the time parameter to make $T_E'=1$ by changing $p_i'$ to be $1-(1-p_i)^{T_E}$. Since we had $T_E=3$ by default, using $T_E'$ and $p_i'$ instead of $T_E$ and $p_i$ means that we choose 3 days to be our time unit, and the probability of infection is scaled to be the probability that the infection is passed in at least one of three days (since the RB tree is time-independent, if two nodes are connected, the infection can spread on it every day). We drop the prime from $p_i'$ and $T_E'$ for ease of notation. As a second approximation, instead of keeping track of two types of nodes (red and blue) as it is done in the RB tree, we propose to change our network model to an infinite $d$-regular tree, where $d$ is set to be the average degree of an RB tree. By making these two changes (tracking time at a coarser scale and simplifying the network topology to a $d$-regular tree), the growth of the epidemic becomes equivalent to a known model, the $d$-ary Random Exponential Tree ($d$-RET). Binary RETs have been introduced in \cite{feng2018profile} . We give the definition below for completeness. \begin{definition} \label{def:dRET} A $d$-ary Random Exponential Tree ($d$-RET) with parameters $d,p_i$ at time day $t$, denoted by $G_t(s)$, is a random tree rooted at node $s$. At day $0$, the tree $G_t(s)$ only has its root node~$s$. Let $\bar{G}_t(s)$ be the closure of $G_t(s)$, which is obtained by attaching external nodes to $G_t(s)$ until every internal node (a node that was already present in $G_t(s)$) has degree exactly $d$ in the graph $\bar{G}_t(s)$. Then, $G_{t+1}(s)$ is obtained from $\bar{G}_{t}(s)$ by retaining each external node with probability $p_i$, and dropping the remaining external nodes. \end{definition} Indeed, each node of a $d$-RET infects a new node with probability $p_i$ each day, and after a sufficiently long time, the $d$-RET becomes close to a large $d$-ary tree. Of course, we do not want to let the $d$-RET grow for a very long time, we only want it to grow until the first hospitalization occurs. So far we have not talked about the course of the disease of the nodes in the $d$-RET model because we could define the spread of the infection without it. Since we still need to do one final simplification to compute the distribution of the transmission path, we defer the discussion about hospitalizations, and how the parameters $p_a$ and $p_h$ are part of the model, to Section~\ref{subsub:DET}. Note that by considering the $d$-RET, we deviate from the idea of separating the epidemic and the network models; we only have a randomly growing tree, which is stopped at some time, when the tree is still almost surely finite. So far we only did simplifications to the model, which resulted in further and further deviations from the original version. Now we will make a small modification that brings our model back closer to the RB tree, without complicating the computations too much. We still make almost all maximum degrees of the RET uniform $d$, but we make an exception with the root, which will have maximum degree $d_r=d_c+d_h$. This makes the maximum degree of the root the same as the degree of the root of the RB tree. We call the resulting model a $(d_r,d)$-RET with parameter $p_i$. Since the close neighborhood of the source has a high impact on the success probability, we found that this solution gives the best results while keeping the computations tractable. In our computations, only the profile the infection tree will be important, which motivates the next definition. \begin{definition} \label{def:total} In the $(d_r,d)$-RET model with parameter $p_i$, let $A_{t,l}$ be the number of nodes during day~$t$ at level~$l$, and let $a_{t,l} = \mathbb{E}[A_{t,l}]$. Moreover, we define the random variable \begin{align} &A_{t} = \sum_{t = 0}^{+\infty} A_{t,l} \label{eq:def_total \end{align} with $A_{-1, l} = 0$ for all $l$, and its expectation $a_{t} = \mathbb{E}[A_{t}]$. \end{definition} As noted earlier, the $d$-RET model has only been analysed for $d=2$ to this date. We provide the expected number $a_{t,l}$ of nodes at level~$l$ in day~$t$ for the general case in the next theorem and corollary, which we prove in Appendices ~\ref{sec:theorem:a} and \ref{sec:corollary:at}. \begin{theorem} \label{theorem:a} In the $(d_r, d)$-RET with parameter $p_i$, let $a_{t,l}$ be as in Definition \ref{def:total}. Then \begin{align} a_{t,0} &= 1 \\ a_{t,l} &= d_rp_i\sum_{m = l-1}^{t-1} \binom{m}{l-1}(1-p_i)^{m-l+1}d^{l-1}p_i^{l-1} \textrm{, for } t \geq l \geq 1 \\ a_{t,l} &= 0 \textrm{, for l > t}. \end{align} \end{theorem} \begin{corollary} \label{corollary:at} In the RET$(p_i, d_r, d)$, let $a_{t}$ be the expectation of \eqref{eq:def_total}, as in Definition~\ref{def:total}. For $t\geq0$, \begin{equation} a_{t} = 1 + d_r\frac{(1-p_i+dp_i)^t - 1}{d-1}. \label{lemma:total} \end{equation} \end{corollary} \subsubsection{Deterministic Exponential Tree with Parameters $p_a, p_h$ and $(c_{t,l})_{t,l \in \mathbb{N}}$} \label{subsub:DET} In the $(d_r,d)$-RET model it is still complicated to calculate the distribution of the depth of the first hospitalized node. For this reason, we approximate the RET model by a deterministic time-dependent tree with a prescribed profile. \begin{definition} Let $(c_{t,l})_{t \in \mathbb{N} \bigcup \{-1\},l \in \mathbb{N}}$ be a two-dimensional array with $c_{t,l}=0$ for $t\in\{-1,0\}$ and $l\in \mathbb{N}$, except for $c_{0,0} = 1$, and with $c_{t,l} \geq c_{t,l-1}$ for any $t$ and any $l \geq 1$. Additionally, if we define $c_t = \sum_l c_{t,l}$, then the array $(c_{t,l})$ must satisfy $c_t> c_{t-1}$ for $t\ge0$. Then, we define the Deterministic Exponential Tree (DET) with parameter $(c_{t,l})_{t \in \mathbb{N} \bigcup \{-1\},l \in \mathbb{N}}$, as a time-dependent rooted tree, that has exactly $c_{t,l}$ nodes on level $l$ at time $t$. The edges between the adjacent levels are drawn arbitrarily so that the tree structure is preserved. \end{definition} The formal assumptions on the array $(c_{t,l})$ are simply made to ensure that the DET starts with a single node at $t=0$, that it never shrinks on any level ($c_{t,l} \geq c_{t,l-1}$), and that it grows by at least one node in each time step ($c_t> c_{t-1}$). We have defined the DET at any given time $t$, however, to determine the length of the transmission path, we are not interested in the DET at any given time, but only when the first hospitalization occurs. To compute the distribution of the first hospitalized node, we would like to have an absolute order on the times when the nodes are added, which we do by randomization. We say that on day $t$, nodes are added one by one to the DET, their order given by a uniformly random permutation, and each node is hospitalized with probability $(1-p_a)p_h$ (as in the original DDE model). When the first hospitalization occurs, we stop growing the tree, and we call the resulting (now random) model a stopped DET with parameters $(c_{t,l}), p_a, p_h$. We find the transmission path length distribution on the stopped DET in the next lemma, which we prove in Appendix~\ref{sec:lem:DET}. \begin{lemma} \label{lem:DET} Let us consider the stopped DET model with parameters $(c_{t,l}), p_a, p_h$, and let $h$ denote the first hospitalized node. Then \begin{align} \label{eq:DET_lemma} \P(d(s,h) = l) = \sum_{t=0}^{+\infty} \frac{c_{t,l}-c_{t-1,l}}{c_t-c_{t-1}} (1-(1-p_a)p_h)^{c_{t-1}}\left(1-(1-(1-p_a)p_h)^{c_t-c_{t-1}}\right). \end{align} \end{lemma} We would like to set $c_{t,l}$ so that the DET is close to the RET described in Section~\ref{subsub:RET}. For equation~\eqref{eq:DET_lemma} to make sense, we should substitute integer values for $c_{t,l}$, however, for an approximation the equation can also be evaluated for fractional values as well. \begin{remark} \label{rem:subs} If we substitute $c_{t,l}=a_{t,l}$ and $c_t=a_t$ in equation \eqref{eq:DET_lemma}, where $a_{t,l}$ is given in Theorem \ref{theorem:a} and $a_{t}$ is computed in Corollary~\ref{corollary:at}, then we get the expression \begin{align} \label{eq:rem_approx} d_rp_i^{l-1}d^{l-1} \sum_{t=l}^{+\infty} \frac{\binom{t-1}{l-1}(1-p_i)^{t-l}}{(1-p_i+dp_i)^{t-1}}(1-(1-p_a)p_h)^{1 + d_r \frac{(1-p_i+dp_i)^{t-1} - 1}{d-1}} \left(1-(1-(1-p_a)p_h)^{d_r(1-p_i+dp_i)^{t-1})}\right), \end{align} which approximates the distribution of the transmission path length in the $(d_r, d)$-ary RET stopped at the first hospitalization. \end{remark} \section{Simulation Results} \label{sec:simulation} \subsection{Baseline Algorithms} \subsubsection{Non-adaptive Baseline: Dynamic Message Passing} There are few sensor-based source detection algorithms that are compatible with time-varying networks in the literature \cite{huang2017source,jiang2016rumor,fan2020identifying}. The most promising one among these algorithms \cite{jiang2016rumor} has a close resemblance to the a previous work of \cite{lokhov2014inferring} on Dynamic Message Passing (DMP) algorithms. Given the initial conditions on the identity of the source node and its time of infection, the DMP algorithm approximates the marginal distribution of the outcome of an epidemic at some later time $t$. The algorithm is exact on tree networks, and it computes a good approximation when there are not too many short cycles in the network. Therefore, the DMP algorithm can be used to approximate the likelihood of the observed symptom onset times for any (source,time) pair. Due to its flexibility, we were able to adapt the DMP algorithm to the SDCTF (see Appendix \ref{sec:DMP_all} for more details). Originally, the DMP was applied to the source detection problem by computing the likelihood values for all possible (source,time) pairs, and then choosing the source node from the most likely pair as the estimate \cite{lokhov2014inferring}. However, testing all (source,time) pairs increases the time complexity of the algorithms potentially by a factor of $N^2$, which makes the algorithm intractable in many applications. Jiang et. al. \cite{jiang2016rumor} proposed a very similar algorithm to the DMP equations (which is unfortunately not exact even on trees), and solved the issue of intractability by a heuristic preprocessing step to the DMP algorithm. This preprocessing step, identifies a few candidate (source,time) pairs, by spreading the disease backward from the observations in a deterministic way (called reverse dissemination). Since we already approximate our data-driven model (DCS) by an epidemic model with deterministic transition times (DDE), it is natural for us to also implement the deterministic preprocessing step proposed by \cite{jiang2016rumor}. We produce 5 (source,time) pairs which are feasible for the 5 earliest symptom onset time observations (see Appendix~\ref{sec:DMP_feasible} for more details). It would have been ideal to run the algorithms for more than 5 pairs, but this was made impossible by the runtimes becoming very high. We run therefore our implementation of the DMP algorithm with the previously computed feasible (source,time) pairs as initial conditions to find the most likely source candidate. The source estimation algorithms developed using the DMP algorithm do not specify how the sensors should be selected, and therefore place these non-adaptive sensors randomly. We refer to the resulting algorithm as random+DMP. The number of sensors is set so that it always exceeds the number that LS/LS+ would use. The simulation results are shown in Figure \ref{fig:baseline_plots} for the DDE+HNM model. Importantly, the deterministic preprocessing step of \cite{jiang2016rumor} is compatible with time-varying networks, which allows us to run the algorithm for the DCS+TU model as well (see Figure \ref{fig:DCSplots}). \subsubsection{Adaptive Baseline: Size-Gain} The Size-Gain (SG) algorithm was developed for epidemics which spread deterministically \cite{zejnilovic2015sequential}, and has been later extended to stochastic epidemics \cite{spinelli2017back}. It works by narrowing a candidate set based on a deterministic constraint. If $v_1, v_2$ are symptomatic observations, then $s_c$ is in the candidate set of SG if and only if \begin{equation} \label{eq:SG} |(t_{v_2}-t_{v_1})- (d(v_2,s_c) - d(v_1,s_c))| < \sigma(d(v_2,s_c)+d(v_1,s_c)), \end{equation} where $\sigma$ is the standard deviation of the infection time of a susceptible contact. If one of the observations, say $v_2$, is negative, then SG uses a condition almost identical to equation \eqref{eq:SG}, except that the absolute value is dropped, since a negative observation at time $t_{v_2}$ is only a lower bound on the true symptom onset time of $v_2$. These deterministic conditions are checked for every symptomatic-symptomatic or symptomatic-negative pair $(v_1, v_2)$ to determine if $s_c$ can be part of the candidate set. Next, SG places the next sensor adaptively at the node which reduces the candidate set by the largest amount in expectation (assuming a uniform prior on the source and its infection time), and it terminates when the candidate set shrinks to a single node. Note that the SG algorithm can fail if at least one of the deterministic conditions in equation~\eqref{eq:SG} is violated for some $(v_1, v_2)$ because of the randomness of the epidemic. We use the existing implementation of the SG algorithm by \cite{spinelli2017back}, and adapt it to the SDCTF. We incorporate asymptomatic-symptomatic and asymptomatic-negative observations $(v_1,v_2)$ the same way as symptomatic-negative are incorporated; we drop the absolute value sign in equation \eqref{eq:SG}, because an asymptomatic observation at time $t_{v_1}$ is only an upper bound on the true symptom onset time of $v_1$. We impose the same daily limit to the number of sensors that can be placed by the SG algorithm in a single day as for the LS/LS+ algorithm, and if the candidate set size does not shrink to one on the day when both LS and LS+ have already provided their estimates, then the SG algorithm must make a uniformly random choice from the current candidate set as its source estimate. The simulation results are shown in Figure \ref{fig:baseline_plots} for the DDE+HNM model. We do not implement the SG algorithm for the DCS+TU model, because its runtime is too high, and because it is not clear how it should be implemented for time-varying networks. \subsection{Comparison with Baselines} \label{sec:comp_baseline} \begin{figure}[h] \begin{center} \includegraphics[width=\textwidth]{images/Figure3.pdf} \caption{The performance of the algorithms LS, LS+, R and SG if the metric is the probability of finding the source (solid curves) or the first symptomatic patient (dashed curves). The simulations were computed on a population of $n=400$ individuals in the DDE model on the HNM, and each datapoint is the average of $4800$ independent realizations except for the SG algorithm, which was run with $192$ independent realizations. The confidence intervals for the success probabilities are computed using the Wilson score interval method, and for the tests and the queries using the Student's t-distribution.} \label{fig:baseline_plots} \end{center} \end{figure} We show our simulation results comparing the random+DMP, SG, LS and LS+ algorithms in Figure~\ref{fig:baseline_plots}. In the first row of Figure \ref{fig:baseline_plots}, we show the accuracy of the algorithms with solid curves. Since the LS/LS+ algorithms cannot detect an asymptomatic source, we also show what the accuracy would look like if the goal of the SDCTF was to detect the first symptomatic agent with dashed lines. It is clear that in both metrics and across a wide range of parameters, the LS+ algorithm performs best, followed by LS, next random+DMP, and finally SG. The only exception is for high values of $p_i$, where SG performs best. The good performance of SG for these parameters is expected, because SG was originally developed for deterministically spreading epidemics (i.e., $p_i=1$). In the second row of Figure \ref{fig:baseline_plots}, we show the number of test/sensor queries used by the algorithms. LS uses the fewest tests, followed by LS+. The random+DMP and SG algorithms always use more tests than LS/LS+, except for large values of $p_i$. Finally, in the last row of Figure \ref{fig:baseline_plots} we show the number of contact (or in this case edge) queries used by the algorithms. Again, LS uses fewer queries than LS+, while both the random+DMP and SG algorithms query essentially the entire network. Figure \ref{fig:baseline_plots} shows that the LS/LS+ algorithms are fairly robust to changes in the parameters of the model, except for the parameter $p_a$. Indeed, if there are many asymptomatic nodes in the network, then source detection becomes very challenging. It may be surprising that as $p_a$ grows, the number of tests that LS uses decreases, contrary to LS+. This is because as $p_a$ grows, the LS algorithm gets stuck more rapidly, while the LS+ algorithm compensates for the presence of asymptomatic nodes by using more test/sensor queries. \subsection{Comparison of Simulations and Theoretical Results} \label{sec:comp_theory} \begin{figure}[h] \begin{center} \includegraphics[width=\textwidth]{images/Figure2.pdf} \caption{The probability of success of the LS and LS+ algorithms (solid curves) and their theoretical estimate (dash-dotted curves) with the success probabilities computed in Lemma \ref{lem:LSsucc} and Theorem \ref{thrm:LSp_suc}, while the transmission path distribution computed in equation \eqref{eq:rem_approx}. The simulation results were generated using the DDE model on HNM networks of size $n=1000$ with $4800$ independent samples. The $95\%$ confidence intervals are computed using the Wilson score interval method.} \label{fig:theory_plots} \end{center} \end{figure} The analytic results from Section~\ref{sec:theory} are in good agreement with the simulation results in Figure \ref{fig:theory_plots}. We also experiment with changing the parameters $d_h$, $d_c$ while keeping all the parameters fixed, and with changing $d_c$ while keeping the product $d_cp_i$ fixed. We observe that LS is not affected by the parameter $d_h$, whereas LS+ performs better with a higher $d_c$, which is expected because LS+ leverages the household structure of the network to improve over LS. Somewhat surprisingly, we also observe that a higher $d_c$ also improves the performance of both algorithms. This can be explained by the fact that a larger $d_c$ implies that there are more nodes in the close neighborhood of the source, which results in shorter transmission paths, making source detection less challenging. Finally, if we increase $d_c$ but keep $d_cp_i$ fixed, the performance of the algorithms does not change as much, which confirms the intuition that it is the number of infections caused by an infectious node in a single day that matters the most (as we discussed in Section~\ref{sec:boe_sec}). \subsection{Simulations on the DCS Model} \label{sec:simDCS} \begin{figure}[h] \begin{center} \includegraphics[width=\textwidth]{images/Figure4.pdf} \caption{The performance of the algorithms LS, LS+ and random+DMP on the DCS model with the Tubingen dynamics if the metric is the probability of finding the source (solid curves) or the first symptomatic patient (dashed curves), together with the theoretical results (dash-dotted lines), as shown in Figure \ref{fig:theory_plots}. The simulations were computed on a population of $n=9054$ individuals, and each datapoint is the average of $2400$ independent realizations for the LS/LS+/LSv2/LS+v2 algorithms, and $48$ independent realizations for the random+DMP algorithm. The default population and infection parameters were selected to match the population and COVID-19 infection datasets of Tubingen. The confidence intervals for the success probabilities are computed using the Wilson score interval method, and for the tests and the queries using the Student's t-distribution.} \label{fig:DCSplots} \end{center} \end{figure} We show our simulation results on our most realistic DCS+TU model in Figure \ref{fig:DCSplots}. We make very similar observations on this model as the ones that we have made on the DDE+HNM model in Sections~\ref{sec:comp_baseline} and \ref{sec:comp_theory}, which shows that the LS/LS+ algorithms and our analysis of their performance is robust to changes in the epidemic and network models. In the DCS+TU model, we used a fixed limit on the number of sensors that the random+DMP model selects, instead of setting the limit based on the LS+ algorithm. As a result, for a few parameters the LS+ algorithm used more tests than the random+DMP model. However, we note that by updating the candidate node immediately after an earlier symptom onset time is revealed (see Section \ref{sec:localsearch}), we can essentially cut the number of required tests for the LS+ algorithm by half (LSv2 and LS+v2), without sacrificing the performance of the algorithms. \section{Discussion} \label{sec:discussion} We have introduced the LS and LS+ algorithms in the SDCTF, and we have used a sequence of models on which we can compute their accuracy (probability of finding the correct source) rigorously. We find that both LS and LS+ outperform baseline algorithms, even though the baselines essentially query all contacts on a transmission path between agents, while LS and LS+ query only a small neighborhood of the source. One could argue that LS and LS+ beat the baseline algorithms only because we benchmark them in our own framework, which is different from the framework for which the baseline algorithms were developed. However, we argue that the LS/LS+ algorithms are robust to changes in the framework due to their simplicity, and we support our argument by simulation results. The runtimes of the LS/LS+ algorithms are also much lower than the baselines and do not depend on the network size since they are local algorithms - as opposed to the baselines, which have quadratic or even larger dependence on the network size. The ``low-tech'' approach in the design of the LS/LS+ algorithms increases their potential to be implemented in real-world scenarios, possibly even in a decentralized way, similarly to contact tracing smart phone applications \cite{troncoso2020decentralized}, which is an interesting direction for future work. \bibliographystyle{ACM-Reference-Format} \section{Additional Proofs} \begin{figure}[h] \begin{center} \includegraphics[width=\textwidth]{images/LSp_cases.pdf} \caption{Illustration for Lemma \ref{lem:LS,LSp,trees} using the same coloring as Figure \ref{fig:mobility_models}~(a). (a) An example for an epidemic where among the nodes of the transmission path $(v_1, v_2, v_3, v_5)$, the middle household contains no symptomatic node (only the asymptomatic node $v_3$), but the LS+ algorithm still succeeds. Indeed, at iteration 0 we set $s_{c,0}=v_5$, after which we find that $v_3$ is asymptomatic, and next that $v_2$ is asymptomatic and $v_4$ is symptomatic, with a lower symptom onset time then $v_5$. Hence, in iteration 1 we set $s_{c,1}=v_4$, and we find that $v_3, v_2$ are asymptomatic and $v_1$ is is symptomatic, with a lower symptom onset time then $v_4$. Finally, in iteration 2 we set $s_{c,2}=v_1$, and we find $s_c'=v_1=s_{c,2}$, which implies that the algorithm stops, and returns the correct source $v_1$. (b) An example for an epidemic where the LS+ algorithm would fail if we would update the candidate before the test queue becomes empty. Similarly to subfigure (a), in iteration 0 of the algorithm first learns about asymptomatic node $v_3$ and next about asymptomatic node $v_2$ and symptomatic node $v_4$. If the algorithm updates the candidate to $v_4$ and continues further, instead of scheduling the tests of the household members of $v_2$, then it is not hard to check that $v_4$ will be the final estimate and the algorithm fails. However, if the algorithm waits until the test queue becomes empty and tests the household members of $v_2$, then $v_1$ becomes the next candidate and the algorithm succeeds.} \label{fig:LSp_cases} \end{center} \end{figure} \subsection{Proof of Lemma \ref{lem:LS,LSp,trees}} \label{sec:LS,LSp,trees_app} We start by restating the lemma here for convenience. \begin{lemma} \label{lem:LS,LSp,trees_app} In the RB tree network, the LS algorithm succeeds if and only if all nodes on the transmission path are symptomatic, and the LS+ algorithm succeeds if among the nodes of the transmission path, there exists a symptomatic node in each household, and the source is symptomatic. \end{lemma} \begin{proof} Throughout the proof we assume that there is no limitation on the number available tests. We can make this assumption because in the SDCTF there is only a daily limit on the number tests, there is no limitation on the number of days, and neither the LS nor the LS+ algorithms proceed in an iteration until the test queue becomes empty, which implies that all nodes that enter the test queue get eventually tested. Suppose that the LS algorithm succeeds. Then the list of candidate nodes $s_c$ at different iterations forms a path that consists entirely of symptomatic nodes between the source and the first hospitalized node. In tree networks, the transmission path is the only path between the source and the first hospitalized node, which yields the "only if" part of the statement on the LS algorithm. Next, suppose that all nodes on the transmission path are symptomatic. Then, we claim that the candidate node $s_{c,i}$ computed in the $i^{th}$ iteration of the LS algorithm is $v_{l-i}$, the $i^{th}$ node of the reverse transmission path. Our claim is definitely true for $i=0$, because $s_{c,0}$ is initialized to be the first hospitalized node $v_l$. Then, the proof proceeds by induction. By the induction hypothesis, in the $i^{th}$ step, $s_{c,i}=v_{l-i}$, and since we are on a tree, the symptom onset time of $v_{l-(i+1)}$ (which is revealed because all nodes on the transmission path are symptomatic by assumption) is the only symptom onset time among the neighbors of $s_{c,i}$ that have a lower symptom onset time than $s_{c,i}$ itself. Therefore $s_c'=v_{l-(i+1)}$, and $s_{c,i+1}$ is updated to be $v_{l-(i+1)}$ in the beginning of the next iteration, which proves that the induction hypothesis holds until the source is reached. Finally, suppose that among the nodes of the transmission path, there exists a symptomatic node in each household, and the source is symptomatic. Let us denote by $w_i$ the $i^{th}$ symptomatic node of the \emph{reverse} transmission path. Then, we claim that the candidate list $s_{c,i}$ computed in the $i^{th}$ iteration of the LS+ algorithm equals $w_i$. Similarly to the case of the LS algorithm, the $i=0$ case holds by definition, and we proceed by induction. Suppose that $s_{c,i}=w_i$. It will also be useful to define the index of $w_i$ on the \emph{forward} transmission path (without skipping asymptomatic nodes). Let $j$ be this index, for which therefore $w_i=v_j$. Now we distinguish 3 cases: (i) $v_{j-1}=w_{i+1}$ is symptomatic, (ii) $v_{j-1}$ is asymptomatic and $v_{j-2}=w_{i+1}$ is symptomatic, and (iii) $v_{j-1}$ and $v_{j-2}$ are asymptomatic and $v_{j-3}=w_{i+1}$ is symptomatic. We claim that there are no more cases, and that in all three cases $w_{i+1}$ is tested in the $i^{th}$ iteration of the LS+ algorithm. Case (i) is immediate because all neighbors of $s_{c,i}$ are tested. Case (ii) is only possible if either $v_{j-1} \in H(s_{c,i})$ or $v_{j-2} \in H(v_{j-1})$, otherwise $v_{j-1}$ would be a lone asymptomatic node in a household, which contradicts the assumption that there is a symptomatic node in each household. Since all the contacts of asymptomatic nodes in $H(s_{c,i})$ (see Figure \ref{fig:Alg1_figure}~(d)) and all nodes in the household of asymptomatic nodes are tested in the LS+ algorithm (see Figure \ref{fig:Alg1_figure}~(e)), $v_{j-2}$ must be tested too. Finally, case (iii) is possible only if $v_{j-1} \in H(s_{c,i})$ and $v_{j-3} \in H(v_{j-2})$ both hold, otherwise $v_{j-1}$ or $v_{j-2}$ would be a lone asymptomatic node in a household. Similarly to the previous case, $v_{j-3}$ must be tested (see Figure \ref{fig:Alg1_figure}~(f)). There are no more cases because, by Remark \ref{rem:RBtree}, on the RB tree a transmission path can only have two nodes in each household, and we assumed that there exists a symptomatic node in each household among the nodes of the transmission path. After we proved that $w_{i+1}$ is tested in the $i^{th}$ iteration of the LS+ algorithm, we must still show that it will be the next candidate $s_{c,i+1}$ for the induction hypothesis to hold. This is true because once the symptom onset time of $w_{i+1}$ is revealed, none of its neighbors are scheduled for testing, and therefore all tested nodes have $w_{i+1}$ on their path to the source, which means that $w_{i+1}$ must have the lowest revealed symptom onset time, and therefore that it will be the next candidate~$s_{c,i+1}$. \end{proof} \subsection{Proof of Theorem \ref{thrm:LSp_suc}} \label{sec:thrm:LSp_suc} We are going to need prove a few intermediate results before proving Theorem \ref{thrm:LSp_suc}. A first step is to count all the possible paths from the source with a given length. \begin{definition} Let $G(s)$ be the RB tree with parameters $(d_c, d_h)$, and let $s$ be the source. A Red-Blue (RB) path of length $n$ is any path of nodes in $(s=v_0, v_1, ...v_n)$ such that $(v_i, v_{i+1}) \in E'$ for $0\leq i < n$. Let $\mathcal{C}_n$ be the set of RB paths of length $n$. \end{definition} \begin{lemma} \label{lem:Cn} In the RB tree with parameters $(d_c, d_h)$, $|C_0| = 1$, while for $n \geq 1$, \begin{equation} |\mathcal{C}_n| = \lambda_1\left( \frac{d_c-1+D}{2}\right)^n + \lambda_2\left( \frac{d_c-1-D}{2}\right)^n \end{equation} where \begin{align} D &= \sqrt{(d_c-1)^2 +4d_cd_h} \\ \lambda_1 &= \frac{(d_c+1+D)(2d_h+d_c-1+D)}{2D(d_c-1+D)} \\ \lambda_2 &= \frac{(D-d_c-1)(2d_h+d_c-1-D)}{2D(d_c-1-D)}. \end{align} \end{lemma} \begin{proof} Let us keep track of the number of RB paths of length $n$ depending on the color of the last node in the path. Let $r_n$ and $b_n$ be the numbers of RB paths of length $n$ such that the last node is red and blue, respectively. A RB path of length 0 consists only of the source, which implies that $r_0 = 1$ and $b_0=0$. The source has $d_c$ red and $d_h$ blue neighbours, which implies that $r_1 = d_c$ and $b_1 = d_h$. Suppose that $P$ is an RB path of length $n \geq 2$. If the last node of $P$ is red, then the node before the last node can be both blue or red. Red nodes other than the source have $d_c-1$ red children, while blue nodes have $d_c$ red children, yielding \begin{align} \label{eq:rn} r_n = (d_c-1)r_{n-1}+d_cb_{n-1}, \textrm{ for }n\geq 2. \end{align} If the last node of $P$ is blue, then the node before has to be red. Since every red node, including the source, has $d_h$ blue children, we have \begin{align} \label{eq:bn} b_n = d_hr_{n-1}, \textrm{ for }n\geq 1 . \end{align} By substituting equation \eqref{eq:bn} into equation \eqref{eq:rn}, we obtain the recurrence \begin{align} r_n = (d_c-1)r_{n-1}+d_cd_hr_{n-2}, \textrm{ for }n\geq 2. \end{align} We solve this recurrence equation by calculating the characteristic equation \begin{equation} t^2 - (d_c-1)t - d_cd_h = 0, \end{equation} whose roots are \begin{align} t_1 &= \frac{d_c-1+\sqrt{(d_c-1)^2 +4d_cd_h}}{2} = \frac{d_c-1+D}{2} \\ t_2 &= \frac{d_c-1-\sqrt{(d_c-1)^2 +4d_cd_h}}{2} = \frac{d_c-1-D}{2} \end{align} yielding the the general solution \begin{equation} r_n = c_1t_1^n + c_2t_2^n, \end{equation} where $c_1, c_2$ are given by the initial conditions for $n=0,1$ \begin{align} &c_1 + c_2 = r_0 = 1 \\ &c_1 t_1 + c_2t_2 = r_1 = d_c, \end{align} which are \begin{align} c_1 &= \frac{1}{2} + \frac{d_c+1}{2\sqrt{(d_c-1)^2+4d_cd_h}} = \frac{1}{2} + \frac{d_c+1}{2D} \\ c_2 &= \frac{1}{2} - \frac{d_c+1}{2\sqrt{(d_c-1)^2+4d_cd_h}} =\frac{1}{2} - \frac{d_c+1}{2D}. \end{align} From equations \eqref{eq:rn} and \eqref{eq:bn} we conclude that for $n\geq 1$, \begin{equation} b_n = d_h(c_1t_1^{n-1} + c_2t_2^{n-1}) \end{equation} and therefore \begin{align} |C_n| = r_n + b_n = \lambda_1t_1^n + \lambda_2t_2^n, \end{align} where \begin{align} \lambda_1 &= c_1\left(1+\frac{d_h}{t_1}\right) \\ \lambda_2 &= c_2\left(1+\frac{d_h}{t_2}\right) . \end{align} Inserting the values for $t_1, t_2, c_1, c_2$ we obtain the desired result. \end{proof} Since LS+ improves on LS by making use of the household structure of the network, we need further information about the household structure of the transmission paths. Recall that by Remark~\ref{rem:RBtree}, households on transmission paths on an RB tree were characterized either by a single red node (that is followed by a red node), or a pair of consecutive red and blue nodes. The following definition and lemma refine our previous result on counting the number of RB paths by taking the household structure into account. \begin{definition} Let $P=\{ s=v_0,v_1,\ldots, v_n=h \}$ be a RB path of length $n$. We say that a node $v$ on the path $P$ is in a $P$-single-household if no other node from $P$ is in the same household as $v$. Otherwise, we say $v$ is in a $P$-multi-household. Given a path $P$, let $M_s: \mathcal{C}_n \rightarrow \{0,1\}$ be the indicator function that the source is in a $P$-multi-household. Similarly, let $M_l: \mathcal{C}_n \rightarrow \{0,1\}$ be the indicator function that the last node of path $P$ is in a $P$-multi-household. Finally, for $0 \leq k \leq n+1$ and $\alpha, \beta \in \{0,1\}$, let \begin{equation} C_{n,k,\alpha, \beta} = \{P \in \mathcal{C}_n : (\textrm{there are exactly }k \textrm{ nodes in } P-\textrm{single-households})\wedge (M_s(P)=\alpha) \wedge (M_l(P) = \beta)\}. \end{equation} \end{definition} The set $C_{n,k,\alpha, \beta}$ depends on 4 parameters, but only some combinations of these parameters make it non-empty. The following definition will be useful in this regard. \begin{condition} \label{cond:path} Let $\alpha, \beta \in \{0,1\}$ and $n \geq 2$. We say $k \in \mathbb{N}$ satisfies Condition~\ref{cond:path} if and only if $k$ and $n$ have different parity and $n+1 - 2(\alpha + \beta) \geq k \geq 2-(\alpha+\beta)$. \end{condition} \begin{lemma} \label{lem:Cnkab} It holds that $|C_{0,1,0,0}| = 1$, $|C_{1,0,1,1}| = d_h$ and $|C_{1,2,0,0}| = d_c$. Let $\alpha, \beta \in \{0,1\}$, let $n \geq 2$ and let $k\in \mathbb{N}$ satisfy Condition \ref{cond:path}. Then \begin{equation} \label{eq:Cnkab} |\mathcal{C}_{n,k,\alpha, \beta}| = \binom{\frac{n+k-3}{2}}{k-2+\alpha+\beta}d_h^{\frac{n-k+1}{2}}d_c^{\frac{n-k+3}{2}-\beta-\alpha}(d_c-1)^{k+\alpha + \beta-2}. \end{equation} In all other cases $|C_{n,k,\alpha, \beta}| = 0$. \end{lemma} \begin{proof} Since there are $n+1$ nodes on path $P$, with $k$ in $P$-single households and thus $n+1-k$ of them in $P$-multi-households, we must have $$k + \frac{n+1-k}{2}=\frac{n+k+1}{2}$$ households along path~$P$ in total. Clearly, the numbers $n$ and $k$ cannot be of the same parity for any RB path $P$, which is thus assumed for the rest of the proof (this assumption is also part of Condition~\ref{cond:path}). If $n=0$, then the source is also the first hospitalized node, and it is in a $P$-single-household, which implies that $|C_{0,1,0,0}| = 1$. If $n=1$, then there are two cases: either the source is in the same $P$-multi-household with the first hospitalized node, or both of them are in $P$-single-households. The former case is possible via $d_h$ edges from the source, which gives $|C_{1,0,1,1}| = d_h$, while the latter case is possible via $d_c$ edges, and gives $|C_{1,0,1,1}| = d_c$. Since these are the only possible RB paths of length $n\le 1$, we must have $|C_{0,k,\alpha,\beta}|=|C_{1,k,\alpha,\beta}| = 0$ for any other choice of parameters $k,\alpha$ and $\beta$. Let us assume that $n\geq 2$. Then, the source and the first hospitalized node are not in the same household. Let us denote the household of the source by $H_s$ and the household of the first hospitalized node by $H_h$. Note that $(1-\alpha)$ and $(1-\beta)$ are the indicators of $H_s$ and $H_h$ being $P$-single-households, and therefore $k \geq (1-\alpha) + (1-\beta)$. If this inequality (which is also part of Condition \ref{cond:path}) does not hold, then clearly $|\mathcal{C}_{n,k,\alpha, \beta}|=0$. Similarly, the number of $P$-multi-households is $\frac{n-k+1}{2}$ and we must have $\frac{n-k+1}{2} \geq \alpha + \beta$ for $|\mathcal{C}_{n,k,\alpha, \beta}|>0$, which implies the inequality $n+1 - 2\alpha - 2\beta \geq k$. Therefore $\mathcal{C}_{n,k,\alpha, \beta}$ is empty if Condition \ref{cond:path} does not hold. For the rest of the proof we assume that Condition \ref{cond:path} does hold. There are $\frac{n+k-3}{2}$ households along path~$P$, excluding $H_s$ and $H_h$. Among them, there are $k-(1-\alpha)-(1-\beta)$ $P$-single-households, which can be chosen in $\binom{\frac{n+k-3}{2}}{k-2+\alpha+\beta}$ ways. Once we know the color of each node along the path, the number of RB paths can be computed by multiplying the numbers of children with the appropriate color of each node. $P$-single-households have no blue nodes, and $P$-multi-households have exactly one, which implies that there are $\frac{n-k+1}{2}$ blue nodes. Since blue nodes are preceded by red nodes that have $d_h$ blue children, they give the multiplicative factor $d_h^{\frac{n-k+1}{2}}$. Blue nodes, except from the first hospitalized node (if it is blue), have $d_c$ red children. So far we have accounted for all of the nodes in $P$-multi-households and none of the nodes in $P$-single-households. If the source is in a $P$-single-household, then we must count its red children, whose number is $d_c$. This implies that there exist $\frac{n-k+1}{2}-\beta+(1-\alpha)$ nodes with $d_c$ red children. Finally, each $P$-single-household, except $H_s$ and/or $H_h$ in case they are $P$-single households, has $d_c-1$ red children. There are $k-(1-\alpha)-(1-\beta)$ such $P$-single-households, which gives the final term in equation \eqref{eq:Cnkab}. \end{proof} The sets $\mathcal{C}_{n,k,\alpha, \beta}$ define equivalence classes on the transmission paths based on their household structure. In the next lemma we show that once we know which equivalence class we are in, it is possible compute the success probability of the LS+ algorithm. \begin{lemma} \label{lem:LSp|Cnkab} Let $P$ be the transmission path in the $\mathrm{DDE}_{\mathrm{NR}}$ epidemic model with parameters $(p_i, p_a, p_h)$ on the RB tree with parameters $(d_c, d_h)$, and let $p$ be as computed in \eqref{C5}. Then, it holds that $$\P(LS+ \textrm{ succeeds} | P \in \mathcal{C}_{0,1,0,0}) = 1$$ and $$\P(LS+ \textrm{ succeeds} | P \in \mathcal{C}_{1,0,1,1}) = \P(LS+ \textrm{ succeeds} | \mathcal{C}_{1,2,0,0}) = 1-p.$$ Let $\alpha, \beta \in \{0,1\}$, let $n \geq 2$ and let $k\in \mathbb{N}$ satisfy Condition \ref{cond:path}. Then, it holds that \begin{equation} \P(LS+ \textrm{ succeeds} | P \in \mathcal{C}_{n,k,\alpha, \beta}) \ge (1-p)^{\frac{n+k-1}{2}}(1+p)^{\frac{n-k+1}{2}-\alpha-\beta}. \end{equation} In all other cases $\P(LS+ \textrm{ succeeds} | P \in \mathcal{C}_{n,k,\alpha, \beta})$ is not defined. \end{lemma} \begin{proof} If $n = 0$, then $k = 1$ and $\alpha = \beta = 0$. In that case, the source is the first hospitalized node and LS+ always succeeds. If $n =1$, then the first hospitalized node is in the neighbourhood of the source, and LS+ succeeds if and only if the source is symptomatic, which happens with probability $1-p$. Let us assume that $n \geq 2$ and that $k$ satisfies Condition \ref{cond:path} (otherwise $|\mathcal{C}_{n,k,\alpha, \beta}|=0$ and $\P(LS+ \textrm{ succeeds}| P \in \mathcal{C}_{n,k,\alpha, \beta})$ is not defined). By Lemma \ref{lem:LS,LSp,trees} the LS+ algorithm succeeds in the $\mathrm{DDE}_{\mathrm{NR}}$ model on the RB tree if, among the nodes of the transmission path, there exists a symptomatic node in each household, and the source is symptomatic, which means that we can prove a lower bound on the success probability of LS+. Let us assume that the source is indeed symptomatic. Since the first hospitalized node is symptomatic by definition, the households of the source and of the first hospitalized node cannot make the LS+ algorithm fail. Let us denote these two households by $H_s$ and $H_h$, respectively. Also, let $M$ and $S$ be the sets of all $P$-multi- and $P$-single-households, respectively, excluding $H_s$ and $H_h$. Then, LS+ succeeds if all nodes in the households of $S$ are symptomatic, and if at least one node in the households of $M$ is symptomatic, which has probability $1-p$ and $1-p^2$ for each type of household, respectively, by equation \eqref{C5}. These observations yield that \begin{align} \P(LS+ \textrm{ succeeds} | P \in \mathcal{C}_{n,k, \alpha, \beta}) &\ge \P(\textrm{source is sym}) (1-p)^{|S|} (1-p^2)^{|M|} \nonumber \\ &= (1-p)(1-p)^{k-2+\alpha+\beta}(1-p^2)^{\frac{n-k+1}{2}-\alpha-\beta} \nonumber \\ &= (1-p)^{k-1+\alpha+\beta}(1-p^2)^{\frac{n-k+1}{2}-\alpha-\beta}. \end{align} \end{proof} Finally, we are ready to state and prove Theorem \ref{thrm:LSp_suc} on the success probability of LS+, which we restate here for convenience. \begin{theorem} \label{thrm:LSp_suc_app} Let $p$ be as in \eqref{C5} and let $\mathcal{S}(n,\alpha,\beta)$ be the set of $k$ values that satisfy Condition \ref{cond:path}. Then, for the $\mathrm{DDE}_{\mathrm{NR}}$ epidemic model with parameters $(p_i, p_a, p_h)$ on the RB tree with parameters $(d_c, d_h)$ we have \begin{align} &\P(LS+ \textrm{ succeeds}) \ge \P(d(s,h) = 0) + (1-p)\P(d(s,h)=1)+ \nonumber \\ & \sum_{n = 2}^{\infty} \sum_{ \substack{\alpha,\beta \in \{0,1\} \\ k \in \mathcal{S}(n,\alpha,\beta)}} \binom{\frac{n+k-3}{2}}{k-2+\alpha+\beta} \frac{(d_h(1-p))^{\frac{n+k-1}{2}}(d_c(1+p))^{\frac{n-k+1}{2}-\alpha-\beta}d_c(d_c-1)^{k+\alpha + \beta-2}}{\lambda_1\left( \frac{d_c-1+D}{2}\right)^n + \lambda_2\left( \frac{d_c-1-D}{2}\right)^n} \P(d(s,h)=n), \end{align} where $D,\lambda_1$ and $\lambda_2$ are terms depending on parameters $d_c$ and $d_h$ and are computed explicitly in Lemma \ref{lem:Cn}. \end{theorem} \begin{proof} Let us extend the domain of $\P(LS+ \textrm{ succeeds} | P \in C_{n,k, \alpha, \beta})$ by function $g$ defined as $g: \mathbb{N} \times \mathbb{N} \times \{0,1\} \times \{0,1\} \rightarrow [0,1] $ such that \begin{equation} g(n,k,\alpha, \beta) = \begin{cases} \P(LS+ \textrm{ succeeds} | P \in C_{n,k, \alpha, \beta})& \text{ if } k \in \mathcal{S}(n,\alpha,\beta) \\ 0& \text{ if } k \not\in \mathcal{S}(n,\alpha,\beta). \end{cases} \end{equation} Unlike $\P(LS+ \textrm{ succeeds} | P \in C_{n,k, \alpha, \beta})$, $g$ is defined for every 4-tuple of parameters $(n,k, \alpha, \beta) \in \mathbb{N} \times \mathbb{N} \times \{0,1\} \times \{0,1\}$. By the law of total probability we expand the success probability by conditioning on the path $P$ being of length~$n$ as \begin{align} \label{eq:LS+expand} \P(LS+ \textrm{ succeeds}) =& \sum_{n = 0}^{\infty} \sum_{k = 0}^{\infty} \sum_{\alpha,\beta \in \{0,1\}} g(n,k, \alpha, \beta) \P(P \in C_{n,k, \alpha, \beta}) \nonumber \\ =& \sum_{n = 0}^{\infty} \sum_{k = 0}^{\infty} \sum_{\alpha,\beta \in \{0,1\}} g(n,k,\alpha, \beta) \P(P \in C_{n,k, \alpha, \beta} | P \in C_{n}) \P(d(s,h)=n). \end{align} Next, we exchange the sums over $\alpha, \beta$ and $k$. This allows us to sum over only those $k$ values that satisfy Condition \ref{cond:path}, which implies that $\P(LS+ \textrm{ succeeds} | P \in C_{n,k, \alpha, \beta})$ is well-defined. As in Lemma \ref{lem:Cnkab}, we need to treat the $n=0$ and $n=1$ cases separately. Continuing equation \eqref{eq:LS+expand}, we arrive to \begin{align} \label{eq:LS+switch} \P(LS+ \textrm{ succeeds}) =& \P(d(s,h) = 0) + (1-p)\P(d(s,h)=1)+ \nonumber \\ &\sum_{n = 2}^{\infty} \sum_{\alpha,\beta \in \{0,1\}} \sum_{ k \in \mathcal{S}(n,\alpha,\beta) } \P(LS+ \textrm{ succeeds} | P \in C_{n,k, \alpha, \beta}) \frac{ |C_{n,k, \alpha, \beta}|}{ |C_{n}|} \P(d(s,h)=n \end{align} Substituting in the results from Lemmas \ref{lem:Cn}, \ref{lem:Cnkab} and \ref{lem:LSp|Cnkab} into equation \eqref{eq:LS+switch} gives the desired result. \end{proof} \subsection{Proof of Theorem \ref{theorem:a}} \label{sec:theorem:a} We start by restating Theorem \ref{theorem:a} for convenience. \begin{theorem} \label{theorem:a_app} In the $(d_r, d)$-RET with parameters $p_i,p_a, p_h$, let $a_{t,l}$ be as in Definition \ref{def:total}. Then \begin{align} a_{t,0} &= 1 \\ a_{t,l} &= d_rp_i\sum_{m = l-1}^{t-1} \binom{m}{l-1}(1-p_i)^{m-l+1}d^{l-1}p_i^{l-1} \textrm{, for } t \geq l \geq 1 \\ a_{t,l} &= 0 \textrm{, for l > t}. \end{align} \end{theorem} \begin{proof} Similarly to \cite{feng2018profile,mahmoud2021profile}, the proof relies on generating functions. We start by addressing the boundary cases. For all $t \geq 0$, it holds that $A_{t,0} = 1$, and therefore $a_{t,0} = 1$. Similarly, for all $l,t$ such that $l > t$, it holds that $A_{t,l} = 0$, and therefore $a_{t,l} = 0$. Suppose that $t\geq l = 1$. During day~$t-1$, on the first level, there are $A_{t-1,1}$ infected (internal) nodes and $d_r-A_{t-1,1}$ (external) nodes that may be infected with probability $p_i$ during day~$t$. Thus, \begin{align} \label{eq:At1} A_{t,1} &= A_{t-1,1}+\mathrm{Bin}(d_r - A_{t-1, 1};p_i) . \end{align} Taking the expectation of both sides in equation \eqref{eq:At1} yields \begin{align} a_{t,1} = a_{t-1,1}(1-p_i) + d_rp_i, \textrm{ for }t\geq 1. \end{align} By subtracting the appropriate recurrence equations for $a_{t,1}$ and $a_{t-1,1}$ for $t\geq 2$ we obtain the homogeneous recurrence equation \begin{align} a_{t,1} - a_{t-1,1}(2-p_i) + (1-p_i)a_{t-2,1} = 0, \textrm{ for } t\geq 2 \end{align} and boundary conditions $a_{0,1} = 0$ and $a_{1,1} = d_rp_i$. We solve for $a_{t,1}$ using the same methods as in the proof of Lemma~\ref{lem:Cn} and obtain \begin{align} \label{eq:a_t,1} a_{t,1} = d_r\left(1-(1-p_i)^t\right), \textrm{ for }t\geq 0. \end{align} Next, let us consider the general case $t \geq l > 1$. On day $t-1$, there are $A_{t-1, l-1}$ nodes on level $l-1$. Since, each node on level $l-1$ has $d$ children, there are $dA_{t-1,l-1}$ nodes on level $l$ that have an infectious parent on level $l-1$. However, $A_{t-1,l}$ of them are already infected. Therefore $dA_{t-1,l-1}-A_{t-1,l}$ nodes of level $l$ may be infected on day~$t$, each with probability $p_i$, which implies \begin{align} \label{eq:Arec} A_{t,l} &= A_{t-1,l}+\mathrm{Bin}(dA_{t-1, l-1} - A_{t-1; l},p_i), \textrm{ for }t \geq l \geq 2 . \end{align} Taking the expectation of both sides in equation \eqref{eq:Arec} yields \begin{align} \label{eq:atl_rec} a_{t,l} &= a_{t-1,l} + (da_{t-1, l-1}-a_{t-1, l})p_i \nonumber \\ &= a_{t-1,l}(1-p_i) + dp_ia_{t-1, l-1}, \textrm{ for } t\geq l \geq 2. \end{align} For convenience, let us introduce $\lambda = 1-p_i$ and $\mu = dp_i$, and also let \begin{align} \label{eq:f(x,y)} f(x,y) = \sum_{t = 1}^{\infty} \sum_{l = 1}^{\infty} a_{t,l}x^ty^l =\sum_{t = 1}^{\infty} \sum_{l = 1}^{t} a_{t,l}x^ty^l \end{align} be the generating function for $a_{t,l}$ with $t,l \geq 1$. By multiplying \eqref{eq:atl_rec} by $x^ty^l$ and summing it over $t,l \geq 2$ we obtain \begin{align} \label{eq:a1} \sum_{t = 2}^{\infty} \sum_{l = 2}^{t} a_{t,l}x^ty^l &= \lambda \sum_{t = 2}^{\infty} \sum_{l = 2}^{t} a_{t-1,l}x^ty^l +\mu \sum_{t = 2}^{\infty} \sum_{l = 2}^{t} a_{t-1,l-1}x^ty^l \nonumber \\ &= \lambda x\sum_{t = 1}^{\infty} \sum_{l = 2}^{t} a_{t,l}x^ty^l +\mu xy \sum_{t = 1}^{\infty} \sum_{l = 1}^{t} a_{t,l}x^ty^l. \end{align} Since $a_{1,l} = 0$ for $l \geq 2$, \begin{align} \label{eq:a2} \sum_{t = 1}^{\infty} \sum_{l = 2}^{t} a_{t,l}x^ty^l = \sum_{t = 2}^{\infty} \sum_{l = 2}^{t} a_{t,l}x^ty^l, \end{align} and by inserting \eqref{eq:a2} into \eqref{eq:a1}, we obtain \begin{align} \label{eq:atl} (1-\lambda x)\sum_{t = 1}^{\infty} \sum_{l = 2}^{t} a_{t,l}x^ty^l &= \mu xy \sum_{t = 1}^{\infty} \sum_{l = 1}^{t} a_{t,l}x^ty^l \stackrel{\eqref{eq:f(x,y)}}{=} \mu xy f(x,y) . \end{align} Now, we can also decompose the sum (\ref{eq:a2}) using geometric series as \begin{align} \label{eq:atl2} \sum_{t = 1}^{\infty} \sum_{l = 2}^{t} a_{t,l}x^ty^l &= \sum_{t = 1}^{\infty} \sum_{l = 1}^{t} a_{t,l}x^ty^l - \sum_{t = 1}^{\infty} a_{t,1}x^ty \nonumber \\ &\stackrel{\eqref{eq:a_t,1}}{=} f(x,y) - d_r y \sum_{t=1}^{\infty} (1-\lambda^t)x^t \nonumber \\ &= f(x,y) - d_r xy \left( \frac{1}{1-x} - \frac{\lambda}{1-\lambda x}\right). \end{align} By plugging \eqref{eq:atl2} into \eqref{eq:atl}, we obtain the expression \begin{align} \label{eq:f_x_y_final_expression} f(x,y) &= d_r (1-\lambda) xy\frac{1}{1-x}\frac{1}{1-\lambda x - \mu xy}. \end{align} Then, we expand the fractions in (\ref{eq:f_x_y_final_expression}) into a power series and we next apply the binomial theorem, we arrive to \begin{align} \label{eq:fnmj} f(x,y) &= d_r(1-\lambda)xy \sum_{n=0}^{\infty}x^n \sum_{m=0}^{\infty}x^m(\lambda+\mu y)^m \nonumber \\ &= d_r(1-\lambda)xy \sum_{n=0}^{\infty}x^n \sum_{m=0}^{\infty}x^m\sum_{j = 0}^m \binom{m}{j}\lambda^{m-j} (\mu y)^{j} \nonumber \\ &= d_r(1-\lambda)\sum_{n=0}^{\infty} \sum_{m=0}^{\infty}\sum_{j = 0}^m \binom{m}{j}\lambda^{m-j} \mu ^{j} x^{1+n+m}y^{j+1}. \end{align} Let $t = 1+n+m$ and $l= j+1$. In order to obtain an expression for $a_{t,l}$, we must change the variables in the sums of equation \eqref{eq:fnmj} from $(n,m,k)$ to $(t,m,l)$. Changing the inner sum from variable $j$ to $l$ is simple. Changing the variables in the two outer sums is more challenging because $t,n$ and $m$ depend on each other in a nontrivial way. More precisely, since $m,n\ge 0$ we have $t\ge 1$ and also $m\le t-1$, which means that we have to set the lower limit of $t$ and the upper limit of $m$ accordingly. As for the remaining limits, variable $t$ can be arbitrary large, and $m$ can take any integer value starting from $0$ independently of $t$, which yields the expression \begin{align} \label{eq:ftml} f(x,y) &= d_r(1-\lambda)\sum_{t=1}^{\infty} \sum_{m=0}^{t-1}\sum_{l = 1}^{m+1} \binom{m}{l-1}\lambda^{m-l+1} \mu ^{l-1} x^{t}y^{l} . \end{align} For the values of $l$ with $l \geq m+1$, the binomial coefficient $\binom{m}{l-1}$ is $0$, which implies that we can increase the upper limit of the inner sum from $m+1$ to $t$ in equation \eqref{eq:ftml}. Then, \begin{align} \label{eq:ftml2} f(x,y) &= d_r(1-\lambda)\sum_{t=1}^{\infty} \sum_{m=0}^{t-1}\sum_{l = 1}^{t} \binom{m}{l-1}\lambda^{m-l+1} \mu ^{l-1} x^{t}y^{l} \nonumber \\ &= \sum_{t=1}^{\infty} \sum_{l = 1}^{t} d_r(1-\lambda) \sum_{m=0}^{t-1} \binom{m}{l-1}\lambda^{m-l+1} \mu ^{l-1} x^{t}y^{l}. \end{align} Finally we can read off the value of $a_{t,l}$ from equation \eqref{eq:ftml2} as \begin{align} a_{t,l} = d_r(1-\lambda) \sum_{m=0}^{t-1} \binom{m}{l-1} \mu^{l-1} \lambda^{m-l+1} = d_rp_i \sum_{m=0}^{t-1} \binom{m}{l-1} (dp_i)^{l-1} (1-p_i)^{m-l+1}. \end{align} \end{proof} \subsection{Proof of Corollary \ref{corollary:at}} \label{sec:corollary:at} We start by restating Corollary \ref{corollary:at} for convenience. \begin{corollary} \label{corollary:at_app} In the RET$(p_i, d_r, d)$, let $a_{t}$ be the expectation of \eqref{eq:def_total}, as in Definition~\ref{def:total}. For $t\geq0$, \begin{equation} a_{t} = 1 + d_r\frac{(1-p_i+dp_i)^t - 1}{d-1}. \label{lemma:total_app} \end{equation} \end{corollary} \begin{proof} By using linearity of expectation, equation \eqref{eq:def_total} and Theorem \ref{theorem:a} we obtain: \begin{align} \label{eq3:1} a_{t} &= \sum_{l = 0}^{+\infty} a_{t,l} \nonumber \\ &= 1 + \sum_{l = 1}^{+\infty} a_{t,l} \nonumber \\ &= 1 + d_rp_i\sum_{l = 1}^{t} \sum_{m = l-1}^{t-1} \binom{m}{l-1}(1-p_i)^{m-l+1}d^{l-1}p_i^{l-1} \end{align} Before we use binomial theorem, we need to swap the sums. Boundaries from \eqref{eq3:1} are equivalent to $t-1 \geq m \geq l-1 \geq 0$, so we can rewrite this as 2 conditions: $m+1 \geq l \geq 1$ and $t \geq m \geq 0$. \begin{align} a_{t,l} &= 1 + d_rp_i\sum_{m = 0}^{t-1}\sum_{l = 1}^{m+1} \binom{m}{l-1}(1-p_i)^{m-l+1}d^{l-1}p_i^{l-1} \nonumber \\ &= 1 + d_rp_i\sum_{m = 0}^{t-1}\sum_{l = 0}^{m} \binom{m}{l}(1-p_i)^{m-l}d^{l}p_i^{l} \end{align} Finally, by applying the binomial theorem and summing the geometric series, we obtain the desired equation: \begin{align} a_{t,l} &= 1 + d_rp_i\sum_{m = 0}^{t-1} (1-p_i+dp_i)^m \nonumber \\ &= 1 + d_r\frac{(1-p_i+dp_i)^t - 1}{d-1}. \end{align} \end{proof} \subsection{Proof or Lemma \ref{lem:DET}} \label{sec:lem:DET} We restate Lemma \ref{lem:DET} here for convenience. \begin{lemma} \label{lem:DET_app} Let us consider the stopped DET model with parameters $(c_{t,l}), p_a, p_h$, and let $h$ denote the first hospitalized node. Then \begin{align} \label{eq:DET_lemma_app} \P(d(s,h) = l) = \sum_{t=0}^{+\infty} \frac{c_{t,l}-c_{t-1,l}}{c_t-c_{t-1}} (1-(1-p_a)p_h)^{c_{t-1}}\left(1-(1-(1-p_a)p_h)^{c_t-c_{t-1}}\right). \end{align} \end{lemma} \begin{proof} Recall that a node added at day $t$ is uniformly distributed among the $c_{t}-c_{t-1}>0$ nodes added that day, and that the number of nodes added to level $l$ is $c_{t,l}-c_{t-1,l}$ on day $t$. If we condition on the time of the first hospitalized case, denoted by $TI_h$, then \begin{align} \P(d(s,h) = l) &= \sum_{t=0}^{+\infty} \P(d(s,h)=l | TI_h = t) \P(TI_h = t) \nonumber \\ & = \sum_{t=0}^{+\infty} \frac{c_{t,l}-c_{t-1,l}}{c_t-c_{t-1}} \P(\textrm{node is not hosp})^{c_{t-1}} (1-\P(\textrm{node is not hosp })^{c_t-c_{t-1}}) \nonumber \\ & = \sum_{t=0}^{+\infty} \frac{c_{t,l}-c_{t-1,l}}{c_t-c_{t-1}} (1-(1-p_a)p_h)^{c_{t-1}}\left(1-(1-(1-p_a)p_h)^{c_t-c_{t-1}}\right). \label{eq:DET_ctl} \end{align} \end{proof} \section{Dynamic Message Passing for the DDE model} \label{sec:DMP_all} In this section, we explain how we derived and implemented the DMP equations for the DDE+HNM model. We start by reviewing the previous work on the DMP equations for the SIR model in Appendix \ref{sec:DMP_SIR}, and then we proceed to our derivations in Appendix \ref{sec:DMP_DDE}. In Appendix \ref{sec:DMP_feasible}, we explain how we find candidate (node,time) pairs for the DMP equations, and in Appendix \ref{sec:DMP_final} we conclude by combining Appendices \ref{sec:DMP_DDE} and \ref{sec:DMP_feasible} into a source-detection algorithm. \subsection{DMP Equations for the SIR Model} \label{sec:DMP_SIR} The DMP equations were first derived by \cite{lokhov2014inferring} for the SIR model in the context of source detection. Their goal is to compute the marginal probabilities that node $i$ is in a given state at time $t$ (denoted by $P_S^{i}(t), P_I^{i}(t)$ and $P_R^{i}(t)$ for the susceptible, infected and recovered states, respectively), given initial conditions $P_S^{i}(t_0), P_I^{i}(t_0)$ and $P_R^{i}(t_0)$ at some initial time $t_0$. To solve this problem in tree networks, we may consider a dynamic programming approach, where we delete a node $i$, we compute the marginal probabilities of $P_S^{j}(t-1)$ for all neighbors $j$ of $i$ in the remaining subtrees, and use this information to compute $P_S^{i}(t)$ (as the marginals are independent in each of the subtrees conditioned on the state of $i$). The DMP equations make the dynamic programming intuition explicit. Originally, the DMP equations were developed for static networks, but since the generalization to time-varying networks is straightforward, and has already been foreshadowed in a similar heuristic algorithm \cite{jiang2016rumor}, we include it in this preliminary section. For time-varying networks, we define $N_i(t)$ as the set of neighbors of node $i$ in the time-window $[t,t+1)$. To formalize the dynamic programming approach, \cite{lokhov2014inferring} introduces some new notation. Let $\lambda$ be the probability that an infectious node infects a susceptible neighbor, and let $\mu$ be the probability that an infectious node recovers. Let $D_{i}$ be the auxiliary dynamics, where node $i$ receives infection signals, but ignores them, and thus remains in the $S$ state at all times. Let $P_{S}^{j \rightarrow i}(t)$ be the probability that node $j$ is in the state $S$ at time $t$ in the dynamics $D_{i}$, and let $\theta^{k \rightarrow i}(t)$ be the probability that the infection signal has not been passed from node $k$ to node $i$ up to time $t$ in the dynamics $D_{i}$. Finally, let $\phi^{k \rightarrow i}(t)$ be the probability that the infection signal has not been passed from node $k$ to node $i$ up to time $t$, and that node $k$ is in the state $I$ at time $t$, in the dynamics $D_{i}$. With these definitions, the dynamic programming approach is formalized by the following equations for $t\ge t_0$: \begin{align} P_S^{i \rightarrow j}(t+1)&=P_S^{i}(t_0)\prod_{k\in N_i(t) \backslash j}\theta^{k \rightarrow i}(t+1), \label{eq:SIRequations:Ps} \\ \theta^{k \rightarrow i}(t+1)-\theta^{k \rightarrow i}(t) &= -\lambda\phi^{k \rightarrow i}(t), \label{eq:SIRequations:theta} \\ \phi^{k \rightarrow i}(t)&=(1-\lambda)(1-\mu)\phi^{k \rightarrow i}(t-1) + \left(P_S^{k \rightarrow i}(t-1)-P_S^{k \rightarrow i}(t)\right). \label{eq:SIRequations:phi} \end{align} The marginal probabilities that node $i$ is in a given state at time $t$ are then given by \begin{align} & P_S^{i }(t+1)=P_S^{i}(t_0)\prod_{k\in N_i(t)}\theta^{k \rightarrow i}(t+1)\, ,\label{eq:SIRequations:S} \\ & P_R^{i}(t+1)=P_R^{i}(t)+\mu P_{I}^{i}(t)\, ,\label{eq:SIRequations:R} \\ & P_I^{i}(t+1)=1-P_S^{i}(t+1)-P_R^{i}(t+1)\, .\label{eq:SIRequations:I} \end{align} These equations are only exact on trees, but they can also be applied to networks with cycles as a heuristic approach. The heuristic gives good approximations to the true marginals if the network is at least locally tree-like \cite{karrer2010message}. \subsection{DMP Equations for the DDE+HNM Model} \label{sec:DMP_DDE} There are several differences between the SIR model on locally tree-like networks and the DDE+HNM model (see Figure \ref{fig:mobility_models} (a)). First, the DDE model has additional compartments (exposed nodes, asymptomatic nodes), which motivates the introduction of several new variables. Let $\lambda_{(a)}$ (resp., $\lambda_{(s)}$) be the probability that an asymptomatic (resp., symptomatic) node infects a susceptible node. Let $\phi^{k \rightarrow i}(t)^{(a)}$ (resp., $\phi^{k \rightarrow i}(t)^{(s)}$) be the probability that the infection signal has not been passed from node $k$ to node $i$ up to time $t$, and that node $k$ is asymptomatic (resp., symptomatic) infectious at time $t$, in the dynamics $D_{i}$. The second important difference is that in the DDE model, the transition times between different compartments are deterministic instead of following a geometric distribution as in the standard SIR model. While deterministic transition times sound simpler at first, it turns out that they make the DMP equations more complex, because the Markovian property that each marginal probability depends only on the previous timestep is lost if the transition times are larger than $1$. Recall that the times for the transitions $E \rightarrow I$ and $I \rightarrow R$ (with their default values) are $T_E=3$ and $T_I=14$. Let us incorporate these two differences into equations \eqref{eq:SIRequations:Ps}--\eqref{eq:SIRequations:phi} to derive the DMP equations for the DDE model. Equation \eqref{eq:DDEequations:Ps} is essentially a copy of \eqref{eq:SIRequations:Ps}. Equation \eqref{eq:DDEequations:theta} follows equation \eqref{eq:SIRequations:theta}, but we incorporate the two different variants of infected (asymptomatic and symptomatic) patients with their respective infection probabilities $\lambda_{(a)}$ and $\lambda_{(s)}$. Equation \eqref{eq:DDEequations:Pr} is a new equation, which is necessary because recovery times are no longer geometric random variables; instead we need to check the probabilities of infection $T_E+T_I$ timesteps earlier than the current time $t$. Finally, equation \eqref{eq:DDEequations:phi_a} (resp., \eqref{eq:DDEequations:phi_s}) is the asymptomatic (resp., symptomatic) version of equation \eqref{eq:SIRequations:phi}, while also incorporating the deterministic time for the transition $E \rightarrow I$. For $t\ge t_0$, this yields equations \begin{align} P_S^{i \rightarrow j}(t+1)&=P_S^{i}(t_0)\prod_{k\in N_i(t) \backslash j}\theta^{k \rightarrow i}(t+1)=P_S^{i}(t_0)\frac{P_S^{i}(t+1)}{\theta^{j \rightarrow i}(t+1)}, \label{eq:DDEequations:Ps} \\ \theta^{k \rightarrow i}(t+1)-\theta^{k \rightarrow i}(t) &= -\lambda_{(a)} \phi^{k \rightarrow i}_{(a)}(t)-\lambda_{(s)}\phi^{k \rightarrow i}_{(s)}(t), \label{eq:DDEequations:theta} \\ P_R^{k \rightarrow i}(t) &=P_S^{k \rightarrow i}(t-T_E-T_I-1)-P_S^{k \rightarrow i}(t-T_E-T_I) \label{eq:DDEequations:Pr} \\ \phi^{k \rightarrow i}_{(a)}(t)&=(1-\lambda_{(a)})(1-P_R^{k \rightarrow i}(t)) \phi^{k \rightarrow i}_{(a)}(t-1) \nonumber\\ & \qquad \qquad + p_a[P_S^{k \rightarrow i}(t-T_E-1)-P_S^{k \rightarrow i}(t-T_E)]. \label{eq:DDEequations:phi_a} \\ \phi^{k \rightarrow i}_{(s)}(t)&=(1-\lambda_{(s)})(1-P_R^{k \rightarrow i}(t)) \phi^{k \rightarrow i}_{(s)}(t-1) \nonumber\\ & \qquad \qquad + (1-p_a)[P_S^{k \rightarrow i}(t-T_E-1)-P_S^{k \rightarrow i}(t-T_E)]. \label{eq:DDEequations:phi_s} \end{align} We note that for early values of $t$, equations \eqref{eq:DDEequations:Pr}--\eqref{eq:DDEequations:phi_s} depend on $P_S^{k \rightarrow i}$ before $t_0$, which we initialize to be 1 (all nodes are susceptible before the first node develops the infection). The marginal probability that node $i$ is susceptible at time $t$ is still computed by equation \eqref{eq:SIRequations:S} as before. Equations \eqref{eq:SIRequations:R}--\eqref{eq:SIRequations:I} do not apply anymore; we explain it in Appendix \ref{sec:DMP_final} how to take into account observations for nodes in the infectious compartments. The third difference between the the SIR model on locally tree-like networks and the DDE+HNM model is that the HNM model contains many short cycles inside the households. Short cycles can cause unwanted feedback loops in the DMP equations where, loosely speaking, nodes are treated as if they could reinfect themselves. We solve this issue by modifying the underlying graph to be locally tree-like (only for the computation of the DMP equations). Specifically, we introduce a new central household-node for each household, and we replace the cliques inside the households by a star graph centered at this new household-node node. Introducing such a central household-node does of course alter epidemic process, in particular it makes household infections less independent and slower (all household infections need to pass through an extra node). To mitigate this issue, we assume that central household-nodes have $T_E=1$ and that they are infected with probability 1 by any node in the same household. We tested the validity of the resulting DMP equations against simulations of the epidemic progressions and we found the results to be quite accurate, in particular, more accurate than the version without the introduction of these central household-nodes. Note that we derived the DMP equations for the DDE+HNM model, however, since (i) the compartments are the same, (ii) the equations support temporal networks, and (iii) we have separate infection probabilities $\lambda_{(a)}$ and $\lambda_{(s)}$ for asymptomatic and symptomatic nodes, our equations can also be applied to the DCS+TU model after a discretizing (rounding) the time observations. Finally, we touch upon the computational complexity of computing the DMP equations. In principle, we need to update $O(dN)$ equations (for each edge) over $t_{\mathrm{max}}$ timesteps, where $t_{\mathrm{max}}$ is the maximum time during which the marginals can still change, which can be as large as $O(N)$. However, since we are only interested in computing the likelihood of the 5 earliest observations, $t_{\mathrm{max}}$ is typically quite low. Moreover, since we assume to be in an early stage of the epidemic, most of the equations remain unchanged. For better computational scalability, we only compute $P_S^{i}(t)$ and $\theta^{k \rightarrow i}(t)$ for nodes $k,i$ that have $P_I^{k \rightarrow i}(t)>0.01$, i.e., we only update nodes that are at least somewhat likely to have received the infection. Otherwise, we set $P_I^{k \rightarrow i}(t)=P_I^{k \rightarrow i}(t-1)$, $\theta^{k \rightarrow i}(t)=\theta^{k \rightarrow i}(t-1)$, and in the implementation we can perform these assignments implicitly using appropriate data structures. With these adjustments, the time-complexity of the algorithm becomes independent of $N$, but remains dependent on the network parameters, the epidemic parameters and the number of sensors in a non-trivial way. \subsection{Feasible Source-time Pairs for Source Detection} \label{sec:DMP_feasible} In this section we explain how we implemented the feasible source identification algorithm, which was suggested as a preprocessing step for a method very similar to the DMP equations by \cite{jiang2016rumor}. Let us define the directed graph $G_2$ on (node,infecton\_time) pairs (we use ``nodes'' for the nodes of the original graph $G$ and ``pairs'' for the nodes of $G_2$), and draw an edge between two pairs $(v_1, t_1) \rightarrow (v_2, t_2)$ if $v_1$ and $v_2$ are in contact at $t_2$, and $t_2$ is in the interval $[t_1+T_E, t_1+T_E+T_I]$. Observe that in the DDE model there is an edge $(v_1, t_1) \rightarrow (v_2, t_2)$ if and only if $v_1$ becoming infected at time $t_1$ can infect $v_2$ at time $t_2$. The definition of $G_2$ is applicable to the DCS model as well after discretization (rounding), however, since the infection times are not deterministic anymore, not all possible infections $(v_1, t_1) \rightarrow (v_2, t_2)$ have a corresponding edge in~$G_2$. Then, we perform a breadth-first search backwards on the directed edges of $G_2$, starting from each pair $(v_i, t_i-T_E-T_P)$, where $v_i$ is a symptomatic sensor node, and $t_i$ is the symptom onset time of $v_i$ (for the DCS model, we start from integer times in the $t_i-T_E-T_P \pm (\sigma_E+\sigma_P)$ interval to account for the randomness of the transition times). To limit the time complexity of the algorithm, we only consider the $k_1$ earliest observations, which means that we start $k_1$ breadth-first searches. With this construction, each pair $(v,t)$ discovered by a breadth-first search started from $(v_i, t_i-T_E-T_P)$ could have caused the infection in $v_i$; we say that $(v,t)$ is an explanation for observation $i$. We perform the breath-first searches until we find $k_2$ pairs that explain all of the $k_1$ earliest observations. See the pseudocode in Algorithm \ref{alg:feasible}. \begin{claim} In the DDE model, Algorithm \ref{alg:feasible} with $\sigma_E=\sigma_P=0$ finds the $k_2$ feasible explanations with the latest starting time of the $k_1$ earliest symptomatic nodes. \end{claim} \begin{proof} By construction, a source node $v$ that becomes infectious at time $t$ can cause an observation $(v_i, t_i)$ if and only if there is a directed path from $(v,t)$ to $(v_i, t_i-T_E-T_P)$. Therefore, the breadth-first search algorithm finds all of the closest feasible sources in time. \end{proof} \begin{algorithm}[h] \SetKwFunction{isOddNumber}{isOddNumber} \KwIn{ \begin{itemize} \item The mean exposed time $T_E$ the mean pre-infectious time $T_P$, the mean infectious time $T_I$,\\ the std of the exposed time $\sigma_E$ and the std of the pre-infectious time $\sigma_P$ \item $F(v)_{min}$ and $F(v)_{max}$ returns the minimum and maximum times when $v$ could have been exposed based on all of its (possibly asymptomatic or negative) test results \item $S(v)$ returns the time of symptom onset for a node $v$ tested positive symtomatic. \item $N(v, [ t_{min}, t_{max} ])$ returns the set of neighbors of node $v$ in the interval $[t_{min}, t_{max}]$ \item A lower estimate of the time the source became infectious $t_{min}$ \item Integers $k_1,k_2$ \end{itemize}} \KwOut{A list of at most $k_2$ tuples of node and time pairs that can explain the first $k_1$ symptomatic nodes} $l \leftarrow \{\}$; \tcp*[f]{if the list $l[t]$ contains the tuple $(v,w)$, then the infection started at $w$ at time $t$ can explain $v$}\\ $D \leftarrow \{\}$; \tcp*[f]{if the list $D[w,t]$ contains the node $v$, then the infection started at $w$ at time $t$ can explain $v$}\\ $doneList \leftarrow []$\; \For{$v \in SortIncreasingByValues(S)[0:k_1]$} { $t'_{min} \leftarrow S(v)-(T_E+T_P)-(\sigma_E+\sigma_P)$\; $t'_{max} \leftarrow S(v)-(T_E+T_P)+(\sigma_E+\sigma_P)$\; \For{$t' \leftarrow t'_{min}$ to $t'_{max}$} { $Append((v,v), l[t'])$\; $Append(v, D[v,t'])$\; \uIf{$Length(D[v,t'])=k_1$} { $Append((v,t'),doneList)$ } } } $t \leftarrow SortIncreasingByValues(S)[k_1-1]$\; $stopCondition \leftarrow False$ \; \While{ not $stopCondition$ and $t>t_{min}$} { \For {$v,w \in l[t]$} { \For{$u \in N(w, [t,t-1])$} { $t'_{min} \leftarrow \max(F(u)_{min}, t-T_E-T_I)$\; $t'_{max} \leftarrow \min(F(u)_{max}, t-T_E)$\; \For{$t' \leftarrow t'_{max}$ to $t'_{min}$} { $Append((v,u), l[t'])$\; $ Append(v,D[(u,t')])$\; \uIf{$Length(D[u,t'])=k_1$} { $Append((u,t'),doneList)$ } } } } $doneList \leftarrow SortBySecondElement(doneList)$\; \uIf{$Length(doneList\ge k2$) and $t-T_E \le doneList[k2][1]$} { $stopCondition \leftarrow True$\; } \Else{ $t \leftarrow t-1$\; } } \KwRet{$doneList$} \caption{Feasible source identification (reverse dissemination \cite{jiang2016rumor})} \label{alg:feasible} \end{algorithm} \subsection{Source Detection via Feasible Source Identification and DMP} \label{sec:DMP_final} In this section we explain how to combine Algorithm~\ref{alg:feasible} with the DMP equations derived in Appendix~\ref{sec:DMP_DDE}. See the pseudocode in Algorithm~\ref{alg:Sdd}. We start by computing the DMP equations \eqref{eq:DDEequations:Ps}-\eqref{eq:DDEequations:phi_s} and \eqref{eq:SIRequations:Ps} for the $k_2$ tuples of node and time pairs that can explain the first $k_1$ symptomatic observations returned by Algorithm \ref{alg:feasible}. Next, our goal is to use these DMP equations to compute the likelihood of each of the $k_2$ tuples using the $k_1$ observations. Similarly to \cite{lokhov2014inferring}, we make the assumption that the first $k_1$ observations are independent, and we can compute the likelihood by multiplying their respective marginals together. For symptomatic observed nodes $v$, we know the time of symptom onset, which we denote by $S(v)$. Then, the marginal probability of $v$ developing symptoms exactly at time $t$ can be computed by taking the difference of $P_S^{v}(S(v)-T_P-T_E-1)$ and $P_S^{v}(S(v)-T_P-T_E)$ and multiplying the difference by $(1-p_a)$. In Algorithm \ref{alg:Sdd} we drop the multiplicative factor $(1-p_a)$ because it is present for all of the tuples, and it does not change the final order of their scores. For asymptomatic (resp., negative) observations, we only know that at the time of testing, denoted by $A(v)$ (resp., $NE(v)$), at least a time interval of length~$T_E$ has passed (resp., $T_E$ has not passed) since the time of infection. Therefore, dropping the $p_a$ factor similarly to the symptomatic case, we compute the marginal of asymptomatic observations as $1-P_S^{v}(A(v)-T_E)$, and we compute the marginal of negative observations as $P_S^{v}(NE(v)-T_E)$. Finally, the contributions of the observations are multiplied together for each of the $k_2$ tuples returned by Algorithm \ref{alg:feasible}, and the scores approximating the likelihoods are returned. \begin{algorithm} \SetKwFunction{isOddNumber}{isOddNumber} \KwIn{ \begin{itemize} \item The mean exposed time $T_E$, the mean pre-infectious time $T_P$, the mean infectious time $T_I \item $S(v)$ returns the time of symptom onset for a node $v$ tested positive symtomatic. \item $A(v)$ and $NE(v)$ return the time of asymptomatic and negative test results, respectively \end{itemize}} \KwOut{A dictionary $L$ of $k_2$ elements, which contains a score for each $(v,t)$ pair that explains the first $k_1$ observations. Higher scores signify higher confidence of being the source.} $L \leftarrow \{\}$\; $doneList \leftarrow \mathrm{Algorihtm \ \ref{alg:feasible}}(k_1,k_2)$\; \For{$v,t_0 \in doneList$} { $P_S \leftarrow$ eq. \eqref{eq:SIRequations:Ps} based on DMP eq. \eqref{eq:DDEequations:Ps}-\eqref{eq:DDEequations:phi_s} with $P_S^v(t_0)=0$, and $P_S^w(t_0)=1$ for all $w \ne v$\; $L[v,t_0] \leftarrow 1$\; \For{$w \in S$} { $L[v,t_0] \leftarrow L[v,t_0]\cdot (P_S^{v}(S(v)-T_P-T_E-1)-P_S^{v}(S(v)-T_P-T_E))$\; } \uIf{{$w \in A$} }{ $L[v,t_0] \leftarrow L[v,t_0]\cdot (1-P_S^{v}(A(v)-T_E))$\; } \For{$w\in NE$} { $L[v,t_0] \leftarrow L[v,t_0]\cdot P_S^{v}(NE(v)-T_E)$\; } } \KwRet{$L$} \caption{Source detection via DMP} \label{alg:Sdd} \end{algorithm}
{'timestamp': '2021-12-30T02:26:54', 'yymm': '2112', 'arxiv_id': '2112.14530', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14530'}
arxiv
\section{Introduction} \IEEEPARstart{I}{mage} fusion is an important task in image processing, which aims to integrate salient features of source images into a single image by using a fusion method\cite{1}. Fusion of infrared and visible images is a chalenging task in image fusion\cite{luo2016novel}\cite{li2020nestfuse}. Due to different imaging principles of infrared and visible images, they contain different information about the same scene. Therefore, solving the problem of fusing infrared and visible images is important in many applications\cite{zheng2006nearest}\cite{sun2019effective}\cite{wang2003initial}\cite{sun2011quantum}. Many methods have been proposed in the area of image fusion. Generally speaking, the multiscale transform (MST) method is the most common method in the field of image fusion. The main steps of MST-based methods include decomposition, fusion and reconstruction. However, the MST-based methods will loose the effective information of the source image in the process of inverse transform, thus affecting the final fusion results\cite{3}. In recent years, image fusion methods based on representation learning have been widely developed. In sparse representation (SR), Liu et al.\cite{4} obtained global and local saliency maps of the source images based on sparse coeffcients for fusion. Liu et al.\cite{5} proposed a general framework of image fusion by combining MST and SR to overcome the inherent defects of the MST- and SR- based fusion methods. In low-rank representation (LRR), Li et al.\cite{6} obtained a better performance in both global and local structure by combining LRR and dictionary learning simultaneously. With the development of deep learning, many image fusion methods based on deep learning were proposed. In 2017, Liu et al.\cite{7} presented a method that can generate the activity level measurement and fusion rule jointly under a convolutional neural network (CNN) model. In 2018, Li et al.\cite{2} used the pretrained VGG-19\cite{9} to extract the features. Then, they made full use of middle layer features to generate the fused image. In 2019, Li et al.\cite{10} proposed a novel deep learning architecture of image fusion, called DenseFuse. The fusion framework consists of encoding network, a fusion layer and decoding network. But they did not consider multi-scale features in their network. To solve this problem, Song et al.\cite{11} proposed a MSDNet for medical image fusion. They added a multi-scale layer at the end of the encoder of Li's\cite{10} to get multi-scale features and achieved a good fusion effect. Therefore, from the multi-scale perspective, in this paper we embed the idea of Res2Net\cite{12} into the encoder. Res2Net is a new multi-scale backbone architecture, which will be introduced in Section\ref{Res2Net}. The main contributions of the proposed fusion method are given below: (1) Res2Net is used for the fast time in image fusion. We applied Res2Net into our encoder, which extracts muti-scale image features at a more granular level. (2) An interesting aspect is that we found that by using only a single natural image we can learn an effective reconstruction model, and the performance of the reconstruction model is comparable with the reconstruction model trained by 80000 images. This has greatly reduced the training time of the proposed model. (3) A fusion strategy was developed to use the attention model to produce a weight map for the salient features of the source images. The structure of the rest of the paper is as follows. In Section\ref{relatedworks}, we briefly introduce Res2Net and DenseFuse, respectively. In Section\ref{Methodology}, we introduce the the proposed method in detail. In Section\ref{experiment}, experiment results will be shown, and Section\ref{conclusion} is the conclusion of our paper. \section{Related Works} \label{relatedworks} \subsection{Res2Net} \label{Res2Net} Multi-scale features play an important role in many image processing tasks. In PAMI 2020, Gao et al\cite{12} presented a novel building block for CNN, called Res2Net. The Res2Net module is shown in Fig.~\ref{Res2Net module} \begin{figure}[!ht] \centering \includegraphics[width=0.8\linewidth]{Res2Net_module} \caption{The graph of Res2Net module.} \label{Res2Net module} \end{figure} In Fig.~\ref{Res2Net module}, after the $1\times1$ convolution, the feature map subsets are obtained by splitting the feature maps evenly, denoted by $x_i$, where $i\in\{1,2, \ldots,n\}$ and $n$ represents the number of subsets. Except for $x_1$, the rest of subsets have a corresponding convolution denoted as $F_i()$. The output of $F_i()$ is marked with $y_i$. Thus, $y_i$ can be calculated by Eq.\ref{equ:$y_i$} \begin{eqnarray}\label{equ:$y_i$} y_i=\left\{\begin{array}{ll} x_i & \textrm{ $i=1$ } \\ F_i(x_i) & \textrm{ $i=2$ } \\ F_i(x_i+y_{i-1}) & \textrm{$2 <i\leq n$} \end{array}\right. \end{eqnarray} As shown in Eq.\ref{equ:$y_i$}, when $x_i$ goes through $3\times3$ convolutional layer, the output result ($y_i$) can have a larger receptive field than $x_i$. Finally, concatenating all splits and passing them through a $1\times1$ convolution. Therefore, the idea of Res2Net is constructing hierarchical residual-like connections within a residual block. Res2Net extracts multi-scale features at the granularity level and increases the receptive field range for each network layer. \subsection{DenseFuse} \label{DenseFuse} The DenseFuse architecture consists of an encoding network, fusion layer and decoding network. The training network consists of encoder and decoder, and its purpose is to reconstruct the input image. Therefore, training images are not necessarily of the same type as the test images. Hence, the training dataset is easy to get. After the training process, the trained encoder and decoder, respectively, have the ability to extract features and reconstruct the image. Both of them are used in the fusion network. The architecture of DenseFuse is described in Fig.\ref{densefuse}. \begin{figure}[!ht] \centering \includegraphics[width=0.8\linewidth]{densefuse} \caption{The DenseFuse framework.} \label{densefuse} \end{figure} In Fig.\ref{densefuse}, after encoding, two groups of features are fused in the fusion layer. Finally, the fused image is reconstructed by the decoder. \section{Methodology} \label{Methodology} In this section, we will introduce in detail the proposed fusion method for grayscale images. How to process color images will be introduced in Section\ref{RGBresults}. The three subsections are: the proposed method in \ref{proposedmethod}; training network (loss function and training strategy) in \ref{Training}; fusion layer(strategy) in \ref{fusionstrategy}. \begin{figure*}[!ht] \centering \includegraphics[width=0.75\linewidth]{framework} \caption{The architecture of the proposed method for gray scale images.} \label{framework} \end{figure*} \begin{figure*}[!ht] \centering \includegraphics[width=0.75\linewidth]{trainingnetwork} \caption{The reconstruction model.} \label{trainingnetwork} \end{figure*} \subsection{The Proposed Method} \label{proposedmethod} Inspired by the success of DenseFuse and Res2Net, we use the Res2Net module for the encoder because of its strong ability to extract multi-scale features. The input images are infrared and visible images, denoted as $I_1$ and $I_2$. We assume the input images are already registered. Our proposed architecture includes the encoder, the fusion layer and the decoder. The architecture of the proposed method is shown in Fig.~\ref{framework}. As shown in Fig.~\ref{framework}, in the fusion model, the encoder consists of two $3\times3$ filters and a block of Res2Net. For the Res2Net block, after a $1\times1$ convolution, all features are split evenly. The operation and the specific formula for the Res2Net block are described in Section\ref{Res2Net}. At the end of the Res2Net block, all splits are concatenated and pass them through a $1\times1$ convolution. The decoder is constructed by four $3\times3$ filters. The fusion strategy in the fusion layer will be introduced later. \subsection{Training} \label{Training} Regardless of color or gray scale images being used, the training network is the same. The training network has just two parts: the encoder and the decoder. The function of the training network is to reconstruct the input image. Therefore, the training network can also be called a reconstruction model. After the training process, we add the fusion layer between the encoder and the decoder. The architecture of the training network is shown in Fig.\ref{trainingnetwork}. The parameters of the training network are outlined in Table\ref{tab:outline}. \begin{table}[!ht] \centering \caption{\label{tab:outline}The outline of the training network. \textbf{Conv3} and \textbf{Conv1} denote the convolutional layer with $3\times3$ filter and $1\times1$ filter, respectively. \textbf{[Conv3]$\times2$} denotes two identical layers.} \resizebox{3.5in}{!}{ \begin{tabular}{|c|c|c|c|c|c|c|} \hline & Layer & Size & Stride & \makecell[cc]{Input\\Channel} & \makecell[cc]{Output\\Channel} & Activation \\ \hline \multirow{3}*{Encoder} & Conv3 & 3 & 1 & 1 & 32 & ReLU \\ \cline{2-7} ~ & Conv3 & 3 & 1 & 32 & 64 & ReLU\\ \cline{2-7} ~ & Res2Net Block & -- & -- & -- & -- & --\\ \cline{2-7} \hline \multirow{4}*{Decoder} & Conv3 & 3 & 1 & 64 & 64 & ReLU \\ \cline{2-7} ~ & Conv3 & 3 & 1 & 64 & 32 & ReLU \\ \cline{2-7} ~ & Conv3 & 3 & 1 & 32 & 16 & ReLU \\ \cline{2-7} ~ & Conv3 & 3 & 1 & 16 & 1 & --\\ \cline{2-7} \hline \multirow{6}*{\makecell[cc]{Res2Net Block}} & Conv1 & 1 & 1 & 64 & 64 & ReLU \\ \cline{2-7} ~ & -- & -- & -- & -- & 16 & -- \\ \cline{2-7} ~ & [Conv3]$\times2$ & 3 & 1 & 16 & 16 & ReLU\\ \cline{2-7} ~ & [Conv3]$\times2$ & 3 & 1 & 16 & 16 &ReLU\\ \cline{2-7} ~ & [Conv3]$\times2$ & 3 & 1 & 16 & 16 &ReLU\\ \cline{2-7} ~ & Conv1 & 1 & 1 & 64 & 64 & ReLU \\ \hline \end{tabular}} \end{table} \textbf{Reconstruction Loss}. In order to reconstruct the input image, we use the loss function\cite{10} as shown in Eq.\ref{equ:lossfunction}. \begin{eqnarray}\label{equ:lossfunction} L = L_{ssim} + L_{pixel} \end{eqnarray} The $L_{pixel}$ and the $L_{ssim}$ are respectively calculated as: \begin{eqnarray}\label{L_pixel} L_{pixel} = \frac{1}{BCHW}||O-I||^2_2 \end{eqnarray} \begin{eqnarray}\label{L_ssim} L_{ssim} = 1 - SSIM(O,I) \end{eqnarray} where $O$ and $I$ are output and input images respectively, $B$ represents the batch size, $C$ is the number of channels of $O$, $H$ and $W$ are height and width of $O$. In addition, SSIM($\cdot$) denotes the structural similarity\cite{14}. \textbf{Training Strategy}. In an ICCV 2019 paper\cite{15}, the authors proved that the internal statistics of patches within a natural image own enough information for learning a powerful generative model. Authors use a single natural image at multiple scales to train a generative model, rather than many samples from a database. Inspired by \cite{15}, at first, we tried a single natural image at different scales to train a reconstruction model. However, experiments showed that the model has the ability to reconstruct the input image, but the details of the output image are slightly blurry. Therefore, we just tried using a whole natural image to train the reconstruction model 2000 times. Finally, the results show that the reconstruction ability of the model is comparable with DenseFuse\cite{10} and MSDNet\cite{11}, which are trained by 80000 images. Moreover, the training time is greatly reduced. The assessment and the analysis of the training strategy will be dicussed in detail in the \ref{Reconstruction} subsection. Hence, we just randomly choose a natural image (grayscale) from MS-COCO\cite{16} as being our training sample to train the reconstruction model. \subsection{The Fusion Layer} \label{fusionstrategy} The fusion strategy plays an important role in image fusion, and this section will detail our fusion strategy. Input images have their own distinctive features, therefore, two groups of features will be obtained after encoding. Then, we need two weight maps to fuse them, but the average strategy is too rough. Therefore, as shown in Fig.\ref{framework}, we propose to apply a spatial attention model to the fusion layer. \textbf{1)Spatial Attention Based on $1_1$-norm. } Inspired by\cite{10}, we use an $l_1$-norm to process the features extracted by the encoder. Then, we obtain two weight maps, $w_1$ and $w_2$, which are computed by Eq.\ref{equ:weightmap1} \begin{eqnarray}\label{equ:weightmap1} w_i(x,y) = \frac{\sum_{j=1}^m||\phi_i^j(x,y)||_1}{\sum_{i=1}^k\sum_{j=1}^m||\phi_i^j(x,y)||_1} \end{eqnarray} where $\phi_i^{1:m}$ are the feature maps extracted by the encoder, $m$ and $k$, respectively, denote the number of feature maps and input images. In this paper, $k=2$. Finally, the enhanced(fused) features denoted as $f^{1:m}$ are calculated by Eq.\ref{equ:fusedmaps1}. \begin{eqnarray}\label{equ:fusedmaps1} f^{1:m}=\sum_{i=1}^kw_i\times\phi_i^{1:m} \end{eqnarray} \textbf{2)Spatial Attention Based on Mean Operation.} Firstly, we use mean operation to process the features extracted by the encoder $\phi_i^{1:m}$. Then, we apply the soft-max operation to get the weight maps $w_1$ and $w_2$, as shown in Eq.\ref{equ:weightmap2}. \begin{eqnarray}\label{equ:weightmap2} w_i(x,y) = \frac{M(\phi_i^{1:m}(x,y))}{\sum_{i=1}^kM(\phi_i^{1:m}(x,y))} \end{eqnarray} where $M(\cdot)$ is the mean operation to process the pixel at position $(x,y)$ of each feature map. Then, the fused features $f^{1:m}$ are calculated by Eq.\ref{equ:fusedmaps2}. \begin{eqnarray}\label{equ:fusedmaps2} f^{1:m}=\sum_{i=1}^kw_i\times\phi_i^{1:m} \end{eqnarray} After the fusion layer, the final fused features $f^{1:m}$ are fed into the decoder and the fused image is reconstructed accordingly. \section{Experimental Results} \label{experiment} This section firstly introduces the experimental settings and environment. Then, a detailed discussion on the performance of our training network that can be obtained using a single training image is done. The results of the experiments will also be presented, and, finally, we will explain how to process RGB images. \subsection{Experimental Settings and Environment} \label{settings} In our experiment, there are 20 pairs of test images (infrared and visible images)\cite{10}. Several samples of test images are shown in Fig.\ref{testimages} \begin{figure}[!ht] \centering \includegraphics[width=\linewidth]{testimages} \caption{Four pairs of source images. The first row is infrared images and the second row is visible images.} \label{testimages} \end{figure} Comparison methods include the discrete cosine harmonic wavelet transform method(DCHWT)\cite{19}, the joint sparse representation-based method(JSR)\cite{20}, the fusion method based on saliency detection in sparse domain(JSRSD)\cite{4}, DenseFuse\cite{10}, FusionGAN\cite{22}, and MSDNet\cite{11}. In order to evaluate the fusion results in an objective assessment, we choose eight indices as follows: entropy(EN)\cite{23} that indicates how much information the fusion result contains; mutual information(MI)\cite{24} that measures the amount of information of the source images that the fused image contains; $Q_{abf}$\cite{25} reflects the quality of visual information; the sum of the correlations of differences(SCD)\cite{28} that indicates the amount of transferred information from each of the input images into the fused image; a new no-reference quality assessment for image fusion(MS\_SSIM)\cite{29}; $FMI_{dct}$ and $FMI_w$\cite{26}, which calculate the feature mutual information, such as discrete cosine and wavelet features; $SSIM_a$ which is calculated by Eq.\ref{ssim}. \begin{eqnarray}\label{ssim} &SSIM_a(f) = (SSIM(f,I_1)+SSIM(f,I_2))\times 0.5 \end{eqnarray} where $f$ means the fused image, SSIM($\cdot$) denotes the structural similarity operation\cite{14}. The values of $SSIM_a$ measure the structural information of the source images. In the training phase, the number of iterations is 2000 and the batch size is 1. In addition, the number of training images (grayscale) is 1 and the size of training image is $256\times256$. Our method was implemented with NVIDIA GTX 1050Ti GPU, and Pytorch was utilized as the backend for the network framework. \subsection{Detailed Discussion of the Training Strategy} \label{Reconstruction} Natural images have strong internal data repetiton\cite{shocher2018zero}. The analysis of the internal predictive-power was shown to be strong for almost any natural image\cite{glasner2009super}. Motivated by these observations, we combined the predictive power of internal information and the generalization capabilities of deep-Learning to train our reconstruction model by a single natural image. Therefore, the training strategy consists in that we utilize a natural image to train the reconstruction model 2000 times. Firstly, we will show the loss graph of our training strategy in Fig.\ref{loss}. As we can see, after 200 iterations, the training model begins to become stable. Then, we display the comparison results to prove the effectiveness of the trained model from the perspective of reconstruction and fusion. \begin{figure}[!ht] \centering \includegraphics[width=\linewidth]{loss} \caption{The graphs of loss. (a)$L_{pixel}$; (b)$L_{ssim}$; (c)Total loss}. \label{loss} \end{figure} \begin{table*}[!ht] \centering \caption{\label{tab:fusionl1mean}The average values of quality metrics for 20 fused images. \textbf{\emph{$l_1$-norm}} and \textbf{\emph{mean}} means fusion strategy.} \resizebox{\textwidth}{!}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{2}{|c|}{Methods} & $SSIM_a$ & EN & MI & $Q_{abf}$ & $FMI_{dct}$ & $FMI_w$ & SCD & MS\_SSIM \\ \hline \multicolumn{2}{|c|}{DenseFuse} & 0.72829 & 6.66296 & 13.32592 & 0.43454 & {\color{red}{\textbf{0.41456}}} & {\color{green}{\textbf{0.42525}}} & {\color{blue}{\textbf{1.83379}}} & {\color{red}{\textbf{0.92860}}}\\ \hline \multirow{2}*{MSDNet}& $l_1$-norm & {\color{blue}{\textbf{0.76365}}} & 6.40040 & 12.80079 & 0.44416 & 0.37547 & 0.41741 & 1.61825 & 0.83311 \\ \cline{2-10} ~& Mean & {\color{red}{\textbf{0.77453}}} & 6.28483 & 12.56966 & 0.39214 & 0.39046 & 0.41116 & 1.67953 & 0.87041 \\ \cline{2-10} \hline \multirow{2}*{Res2NetFuse\_80000}& $l_1$-norm & 0.70881 & {\color{red}{\textbf{6.83607}}} & {\color{red}{\textbf{13.67214}}} & {\color{blue}{\textbf{0.47354}}} & 0.37620 & {\color{red}{\textbf{0.43160}}} & 1.67887 & 0.84166\\ \cline{2-10} ~& Mean & 0.72993 & {\color{green}{\textbf{6.77470}}} & {\color{green}{\textbf{13.54940}}} & 0.45175 & {\color{blue}{\textbf{0.40685}}} & 0.42417 & {\color{green}{\textbf{1.82024}}} & {\color{green}{\textbf{0.91695}}}\\ \hline \multirow{2}*{Res2NetFuse\_1}& $l_1$-norm & 0.72520 & {\color{blue}{\textbf{6.81785}}} & {\color{blue}{\textbf{13.63569}}} & {\color{red}{\textbf{0.48364}}} & 0.37552 & {\color{blue}{\textbf{0.42924}}} & 1.69888 & 0.85384 \\ \cline{2-10} ~& Mean & {\color{green}{\textbf{0.74206}}} & 6.76675 & 13.53350 & {\color{green}{\textbf{0.46368}}} & {\color{green}{\textbf{0.40262}}} & 0.42334 & {\color{red}{\textbf{1.83464}}} & {\color{blue}{\textbf{0.92129}}} \\ \hline \end{tabular}} \end{table*} \begin{table}[!ht] \centering \caption{\label{tab:reconstruction}The average values of quality metrics for 20 reconstructed images. \textbf{\emph{DenseFuseRecons}} denotes the reconstruction model of DenseFuse. \textbf{\emph{MSDNetRecons}} denotes the reconstruction model of MSDNet. \textbf{\emph{Res2NetFuseRecons\_1}} denotes the reconstruction model of Res2NetFuse trained by an image. \textbf{\emph{Res2NetFuseRecons\_80000}} denotes the reconstruction model of Res2NetFuse trained by 80000 images.} \resizebox{3.5in}{!}{ \begin{tabular}{|c|c|c|c|} \hline Methods & SSIM & PSNR & MSE \\ \hline DenseFuseRecons & 0.99560 & 43.62612 & 0.00016 \\ \hline MSDNetRecons & {\color{red}{\textbf{0.99933}}} & {\color{red}{\textbf{52.10881}}} & {\color{red}{\textbf{0.00001}}} \\ \hline Res2NetFuseRecons\_1 & 0.99560 & 40.36431 & 0.00042 \\ \hline Res2NetFuseRecons\_80000 & 0.99888 & 46.50366 & 0.00005 \\ \hline \end{tabular}} \end{table} \subsubsection{Reconstruction Comparisons} We compare our reconstruction model with existing reconstruction models which are trained by 80000 images. The reconstruction models for comparison are from DenseFuse, MSDNet and our proposed method which is trained by 80000 images (batch size and epoch are all 4). Then, we randomly choose 20 natural images from MS-COCO in order to do reconstruction experiments. We utilize the structural similarity (SSIM), the peak signal to noise ratio (PSNR) and the mean squared error(MSE), calculated by using Eq.\ref{MSE}, in order to evaluate the reconstruction performance. \begin{eqnarray}\label{MSE} MSE = \frac{1}{W\times H}\sum_{x=1}^W\sum_{y=1}^H(I(x,y)-R(x,y))^2 \end{eqnarray} where $W$ and $H$ are the width and the height of the image, $I$ is the input image and $R$ is the reconstructed image. The reconstruction comparison results are shown in Table\ref{tab:reconstruction}. As shown in Table\ref{tab:reconstruction}, although Res2NetFuse does not achieve the best metrics values, it still obtains comparable reconstruction ability. Comparing with Res2NetFuseRecons\_80000, the reconstruction model trained by one image achieves acceptable reconstruction performance. This means the internal information of a single image is enough to train our lightweight network. Moreover, with this training strategy, our lightweight network needs much less training time. \subsubsection{Fusion Comparisons} In this part, for fusion comparison purposes, we also compare Res2NetFuse\_1, trained by an image, with DenseFuse, MSDNet and Res2NetFuse\_80000 trained by 80000 images. Among the compared methods, MSDNet is also from a multi-scale perspective. Therefore, when comparing MSDNet and Res2NetFuse, we ensured that the fusion strategy is the same. The fusion comparison results are shown in Table\ref{tab:fusionl1mean}. In Table\ref{tab:fusionl1mean}, the \textbf{\emph{red}} values mean the best values, the \textbf{\emph{blue}} values mean the second-best values, the \textbf{\emph{green}} values mean the third-best values. We can see that Res2NetFuse\_1 has comparable fusion ability with the other methods. In addition, although the MSDNet's reconstruction ability is better than that of Res2NetFuse, the fusion results of Res2NetFuse are better than that of MSDNet under the same fusion strategy. The reason is that the activity level maps of MSDNet are for different scales and, on the other hand, that of Res2NetFuse are for all scales. Therefore, the weight maps generated by the avtivity level maps of Res2NetFuse will be more stable. Comparing with the Res2NetFuse\_80000, we find that the metrics values are similar, which means the fusion performace of Res2NetFuse\_1 is acceptable. Therefore, even the Res2Net-based fusion model is trained by a single natural image, it can obtain a good fusion performance. The above comparisons on the performance of reconstruction and fusion proves that our training strategy is effective. Now we will summarize several reasons why the training strategy is effective: 1) The proposed method is a lightweight network, in contrast to the deep networks in other computer vision tasks. In theory, the training process could be done with less training data. And for some deep-learning-based image fusion methods, the deep network is mainly used for reconstruction, which requires less training data than a classification task. 2) In fact, natural images have strong internal data repetition and the internal statistics often provides strong predictive-power \cite{shocher2018zero}. Therefore, combining the strong generalization abilities of deep-learning, the lightweight network can be trained by a single natural image. 3) Multi-scale feature representations of Res2Net are of great importance to the proposed method, which can make it easier for the decoder to reconstruct the image. Therefore, through a comprehensive consideration, we choose Res2NetFuse\_1 as the final fusion model. The Res2NetFuse mentioned later will be trained by a single natural image. \subsection{Subjective \& Objective Evaluation} \label{Assessment} Our method is tested for 20 images, and three groups of experimental results are shown in Fig.\ref{results1}$-$Fig.\ref{results3}. \begin{figure*}[!ht] \centering \includegraphics[width=0.9\linewidth]{results1} \caption{The first group of experimental results. (a)Infrared image; (b)Visible image; (c)DCHWT; (d)JSR; (e)JSRSD; (f)DenseFuse; (g)FusionGAN; (h)MSDNet with $l_1$-norm fusion strategy; (i)MSDNet with mean fusion strategy; (j)Res2NetFuse with $l_1$ fusion strategy; (k)Res2NetFuse with mean fusion strategy.} \label{results1} \end{figure*} \begin{figure*}[!ht] \centering \includegraphics[width=0.9\linewidth]{results2} \caption{The second group of experimental results. (a)Infrared image; (b)Visible image; (c)DCHWT; (d)JSR; (e)JSRSD; (f)DenseFuse; (g)FusionGAN; (h)MSDNet with $l_1$-norm fusion strategy; (i)MSDNet with mean fusion strategy; (j)Res2NetFuse with $l_1$ fusion strategy; (k)Res2NetFuse with mean fusion strategy.} \label{results2} \end{figure*} \begin{figure*}[!ht] \centering \includegraphics[width=0.9\linewidth]{results3} \caption{The third group of experimental results. (a)Infrared image; (b)Visible image; (c)DCHWT; (d)JSR; (e)JSRSD; (f)DenseFuse; (g)FusionGAN; (h)MSDNet with $l_1$-norm fusion strategy; (i)MSDNet with mean fusion strategy; (j)Res2NetFuse with $l_1$ fusion strategy; (k)Res2NetFuse with mean fusion strategy.} \label{results3} \end{figure*} Through perceptual comparison, the fused results of DCHWT have some noise and salient features are not clear. In addition, the salient features of fused results obtained by JSR and JSRSD are so sharp. Furthermore, as shown in the three figures above, we can find that the results of FusionGAN are not stable, such as shown in Fig.\ref{results2}(g). On the other hand, the results of Res2NetFuse, MSDNet and DenseFuse are more consistent with human visual standards. But obviously, the results of Res2NetFuse are more stable and have more salient features. In order to verify objectively the effectiveness of the proposed method, we utilize some indices to evaluate the obtained fused results. The objective evaluation is shown in Table.\ref{tab:ob} \begin{table*}[!ht] \centering \caption{\label{tab:ob}The average values of 20 fused images.} \resizebox{\textwidth}{!}{ \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|} \hline \multicolumn{2}{|c|}{Methods} & $SSIM_a$ & EN & MI & $Q_{abf}$ & $FMI_{dct}$ & $FMI_w$ & SCD & MS\_SSIM \\ \hline \multicolumn{2}{|c|}{DCHWT} & 0.73078 & 6.53455 & 13.06910 & {\color{green}{\textbf{0.45890}}} & 0.38061 & 0.39700 & 1.61007 & 0.84278 \\ \hline \multicolumn{2}{|c|}{JSR} & 0.60912 & 6.38043 & 12.76086 & 0.36267 & 0.16738 & 0.21284 & {\color{green}{\textbf{1.75518}}} & 0.84735 \\ \hline \multicolumn{2}{|c|}{JSRSD} & 0.54471 & {\color{green}{\textbf{6.66771}}} & {\color{green}{\textbf{13.33541}}} & 0.32914 & 0.14560 & 0.18697 & 1.59142 & 0.76548 \\ \hline \multicolumn{2}{|c|}{DenseFuse} & 0.72829 & 6.66296 & 13.32592 & 0.43454 & {\color{red}{\textbf{0.41456}}} & {\color{blue}{\textbf{0.42525}}} & {\color{blue}{\textbf{1.83379}}} & {\color{red}{\textbf{0.92860}}}\\ \hline \multicolumn{2}{|c|}{fusionGAN} & 0.65207 & 6.36496 & 12.72993 & 0.21853 & 0.36097 & 0.36797 & 1.45818 & 0.73233 \\ \hline \multirow{2}*{MSDNet}& $l_1$-norm & {\color{blue}{\textbf{0.76365}}} & 6.40040 & 12.80079 & 0.44416 & 0.37547 & 0.41741 & 1.61825 & 0.83311 \\ \cline{2-10} ~& Mean & {\color{red}{\textbf{0.77453}}} & 6.28483 & 12.56966 & 0.39214 & {\color{green}{\textbf{0.39046}}} & 0.41116 & 1.67953 & {\color{green}{\textbf{0.87041}}} \\ \cline{2-10} \hline \multirow{2}*{Res2NetFuse}& $l_1$-norm & 0.72520 & {\color{red}{\textbf{6.81785}}} & {\color{red}{\textbf{13.63569}}} & {\color{red}{\textbf{0.48364}}} & 0.37552 & {\color{red}{\textbf{0.42924}}} & 1.69888 & 0.85384 \\ \cline{2-10} ~& Mean & {\color{green}{\textbf{0.74206}}} & {\color{blue}{\textbf{6.76675}}} & {\color{blue}{\textbf{13.53350}}} & {\color{blue}{\textbf{0.46368}}} & {\color{blue}{\textbf{0.40262}}} & {\color{green}{\textbf{0.42334}}} &{\color{red}{\textbf{1.83464}}} & {\color{blue}{\textbf{0.92129}}} \\ \hline \end{tabular}} \end{table*} In Table.\ref{tab:ob}, the best values are in \textbf{\emph{red}}, the second-best values are marked in \textbf{\emph{blue}} and the third-best values are in \textbf{\emph{green}}. As we can see, Res2NetFuse has some advantages with respect these results of fusion evaluation. The best values of EN, MI, $Q_{abf}$, $FMI_w$ and SCD indicate that our method can preserve more visual and salient information of the source images and contain less noise. And second-best values MS\_SSIM and $FMI_{dct}$ and third-best value $SSIM_a$ mean that our method preserve more structural information of the source images. In addition, the comparison between Res2NetFuse and MSDNet also indicates that Res2NetFuse could extract more powerful deep features, which are beneficial for image fusion tasks. Therefore, our method is an effective fusion architecture for infrared and visible images' fusion. \begin{figure}[!ht] \centering \includegraphics[width=\linewidth]{rgb} \caption{The fusion framework for color images.} \label{rgbframework} \end{figure} \begin{figure*}[!ht] \centering \includegraphics[width=0.85\linewidth]{rgbresults} \caption{The fused results for color images. (a)Infrared image; (b)Visible image; (c)Fused results} \label{rgbresults} \end{figure*} \subsection{Additional Experiments on RGB(Visible) and Infrared Images} \label{RGBresults} Inspired by \cite{27}, for color images, we convert the visible image to YUV space and the infrared image to gray sale image. Y channel is the luminance component, in addition, U and V are the chrominance components. We apply our method to fuse the Y channel and the gray scale image. Then, we convert the fused image combined with the U and V channels of visible image to the RGB space. Finally, the fused color image will be obtained. The fusion framework for color images is shown in Fig.\ref{rgbframework}, and the fused color results are shown in Fig.\ref{rgbresults}. In Fig.\ref{rgbresults}, we can see that the features of fused results are enhanced, which are consistent with human vision perception. Therefore, the fusion framework for color images is beneficial for RGB and infrared images' fusion tasks. \section{Conclusion} \label{conclusion} In this paper, we presented a novel architecture for fusion of infrared and visible images based on a multi-scale backbone Res2Net. We found that a single natural image can train the network very well for image fusion. Insights on the success of the proposed method were also presented and analyzed. We proposed to apply an attention model to the fusion strategy, which can generate a more effective weight map to fuse the salient features of source images. The experimental results show that our method outperforms the state-of-the-art methods. In future work, we will apply the proposed training strategy to other tasks of image processing. \bibliographystyle{IEEEtran}
{'timestamp': '2022-02-01T02:15:38', 'yymm': '2112', 'arxiv_id': '2112.14540', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14540'}
arxiv
\section{Introduction} Color image steganography is one of the essential branches of information hiding. It is widely used in the military, medicine, intellectual property protection, and other fields. Through human visual characteristics, color image steganography can hide secret information (usually bitstream or text) into a color image. We call the original color image a cover image, and the modified color cover image a stego image. The stego image is almost the same as the cover image, so it is not easy to arouse the suspicion of the third party and shows good imperceptibility. In recent years, the image hiding steganography based on deep learning has emerged. Image hiding steganography can hide the image as secret information into a cover image. This kind of steganography improves the steganographic capacity and greatly expands the application scope of steganography. Nowadays, image hiding steganography based on deep learning is a popular research direction in steganography. Image hiding steganography should have a large steganographic capacity and good imperceptibility to obtain a better application effect. However, there is a strong negative correlation between capacity and imperceptibility. The increase of steganographic capacity usually leads to a decrease in imperceptibility\cite{r1}.Therefore, it is difficult for the current image hiding steganography based on deep learning to take into account these two characteristics simultaneously\cite{r2}. As shown in Figure \ref{fig:1-1} , when the secret information is the same size image, the stego image may generate visible color distortion and artificial texture traces, which do not meet the imperceptibility requirement of image steganography. Therefore, currently controlling the steganographic traces in the invisible range of human eyes is the point of image hiding steganography. As shown in Figure \ref{fig:1-2}, some researchers tried to use the characteristics of color spaces and embedded the secret image into the channel, which does not relate to color information. This idea effectively reduces the color distortion of color stego images\cite{r4}. More than this, the idea provides researchers with a new path: to use the characteristics of color spaces to improve the imperceptibility of image steganography based on deep learning and make it fit the visual characteristics of the human eyes. Nevertheless, the influence of color spaces characteristics still needs to be verified in different deep learning steganography. \begin{figure}[t] \centering \includegraphics[width=1.0\textwidth]{1-1.jpg} \caption{\label{fig:1-1}We mark and enlarge the color distortion (a) and artificial texture traces (b) area in stego images generated by \cite{r3}.} \end{figure} \begin{figure}[t] \centering \includegraphics[width=1.0\textwidth]{1-2.jpg} \caption{\label{fig:1-2}Four groups of stego images generated by the model of \cite{r4}. This model uses the characteristics of YUV color space to improve the quality of stego images. There is only a slight difference in brightness between stego images and original images.} \end{figure} According to the research results of traditional steganography, the embedding domain will have a significant impact on the steganographic visual effect\cite{r5}\cite{r6}\cite{r7}. According to the difference of embedding domain, image steganography can be divided into two categories: The first type is the spatial domain steganography, which directly modifies the pixels in the image space. The second type is frequency-domain steganography, which uses the frequency domain transformation method to convert images into frequency sub-bands and modify them. Contrary to image information in the spatial domain, the frequency domain sub-bands are information human eyes can not directly observe. Therefore, in the process of frequency domain steganography, the steganographic traces of stego images is invisible if the modification of frequency sub-band is controlled\cite{r8}. Unlike traditional steganography, image hiding steganography based on deep learning primarily hides secret data in the spatial domain of the cover image. The information in the spatial domain is directly visible to the human eyes. Therefore, if modified this information directly, it is easy to create a color distraction or artificial texture traces. Combined with the research results of traditional image steganography, we believe that image hiding steganography based on frequency domain will show a better imperceptibility through the learning of the deep neural network. Based on the above inference, we try to embed a secret image into the frequency domain of a cover image to obtain better image quality. On this basis, the influence of different frequency sub-bands and color spaces on frequency domain steganography based on deep learning will be further discussed. In terms of frequency sub-bands, the characteristics of some frequency domain transform methods(such as DWT) are consistent with the characteristics of the human visual system (HVS)\cite{r9}. Hence Some traditional frequency domain steganography further improves the imperceptibility by using different frequency components and characteristics of HVS\cite{r10}. Similarly, we can further improve the imperceptibility of steganography by using the characteristics of image frequency sub-bands. In terms of the characteristics of color spaces, different color spaces will express image information in different ways. Hence they will produce different effects on steganography\cite{r11}. Moreover, each channel also has different visual characteristics in the same color space. Therefore, controlling each channel for steganography will also produce different steganography effects \cite{r12}. According to the characteristics of color spaces and the degree of image distortion, this paper selects the channel with the best steganographic effect as the embedding channel to further improve the imperceptibility of the model. At present, image hiding steganography faces the problems of color distortion and artificial texture traces. According to the characteristics of color spaces and frequency sub-bands, a color image hiding steganography model based on frequency sub-band selection is proposed in this paper. The model is based on the deep neural network of encoder-decoder structure. Firstly, DWT is used to transform the secret image and the B channel of the cover image into the frequency domain. Then to reduce the color distortion and texture modification trace of the stego image, the high-frequency sub-band of the cover image is selected as the embedding domain. In order to keep a good balance between capacity and efficiency, we choose a gray image as the secret image and a color image as the cover image. The experimental results show that compared with other deep learning image steganography models based on spatial domain, the proposed model significantly improves image quality, reduces color distortion and artificial texture traces. The imperceptibility of the model is significantly improved. In summary, the main contributions of this paper are: \begin{enumerate} \item We propose a steganographic model in the frequency domain. Our model has better imperceptibility than the same category color image steganographic model in the spatial domain. \item We analyze the influence of color spaces characteristics on the proposed model, find the most suitable embedding channel according to the characteristics of HVS and the principle of minimizing distortion. \item Combined with the channel selection, we add the frequency sub-band selection module in the proposed model. This module selects the high-frequency sub-band as the embedding domain, which effectively improves the imperceptibility. Moreover, the relationship between frequency sub-bands characteristics and the steganographic effect is discussed. \item To better compare the color difference between the original image and the stego image, we propose a new color image quality metric called CL-PSNR. CL-PSNR takes the color difference into account, which is more in line with the feeling of HVS to color images. \end{enumerate} The rest of the paper is organized as follows: In Section 2, we discuss the existing research results in related directions. In Section 3, we describe the structure of the model, the discussion of color spaces and imperceptibility, the selection of frequency sub-band, and the new color image quality metric. In Section 4, we present and analyze the experimental results. In Section 5, we conclude this work. \section{Related Work} Steganography is a technology of hiding information, which originated in ancient Greece and has a long history. The proposed steganography is the image hiding steganography based on deep learning, which means the steganography is based on deep learning knowledge and hiding the image with the image. Hence this section will introduce the development of image steganography based on deep learning. The representative achievements and problems of image hiding steganography will be discussed in detail. Moreover, the traditional image steganography will be used as a reference to improve imperceptibility. \subsection{Image Steganography Based on Deep Learning} In recent years, many image steganography methods based on deep learning have been proposed. ASDL-GAN was one of those earlier methods\cite{r13}. Although ASDL-GAN does not directly participate in the embedding and extraction process, its results inspire more scholars to improve the performance of steganography by using deep learning. Zhu et al. proposed Hidden, which first used a neural network for end-to-end training and has stronger robustness than traditional methods\cite{r14}. Hayes et al. proposed a HayesGAN to use an encoder network to hide text information in the image \cite{r15}. Tancik of Berkeley University proposed a StegaStamp framework based on the U-net structure \cite{r16}. They used a series of image enhancement methods to make the model robust in the real world. Huang et al. introduced the adversarial strategy in model training to better resist steganalysis\cite{r17}. Compared with the mature and stable traditional image steganography, the advantage of deep learning image steganography is to use the deep neural network to learn the steganographic method independently. Traditional image steganography techniques rely on artificial design, so it is difficult to improve the performance further. Therefore, the introduction of deep learning broke the deadlock. Moreover, with the development of deep learning technology, image steganography based on deep learning will have more space to develop. \subsection{image hiding steganography} In the early stage of deep learning image steganography, most secret information is a string or a bitstream, and the steganographic capacity is small (mostly 0.2bpp-4bpp)\cite{r2}. Fortunately, the image hiding steganography appeared. Image hiding steganography based on deep learning uses the experience of other deep learning steganography. It uses the image to hide the image, which significantly increases the capacity. The deep steganographic model proposed by Baluja is the first model using two same-size images\cite{r3}. It extracts the secret image features through a preprocessing network, then hides a secret image into a cover image by a hidden network, and finally extracts it by an extraction network. This model significantly increases capacity (24bpp). After that, Baluja tried to embed two secret images into another image and confuse the specific information of secret images\cite{r18}. This method improves capacity and enhances the security of secret information. Wu et al. proposed the StegNet. It is based on a deep neural network, and it can also hide the same size image, which only modifies 0.76\% cover image\cite{r19}. Van et al. proposed a new training scheme, which modifies the error back propagation to speed up the training of the network\cite{r20}. The above results use color images as secret information. However, gray image is also common secret information in image hiding steganography. Compared with the color image, gray image only contains semantic information, and its capacity is only one-third of the color image. The characteristics make the gray image more suitable as secret information in specific tasks. Rehman et al. proposed a steganographic model based on the coder-decoder network\cite{r21}. The model can embed a gray image into an RGB color image. Moreover, a new loss function is introduced to ensure the end-to-end joint training of the encoder-decoder network. Experiments show that the model can still obtain good image quality with a large capacity(8bpp). The image hiding steganography based on deep learning significantly improves the steganographic capacity, but its steganographic traces(color distortion or artificial texture traces) is visible to human eyes. Zhang et al. proposed ISGAN\cite{r4} to solve the problem of color distortion, which converts the RGB cover image into YUV color space, and then selects the Y channel of the cover image as the embedding domain to avoid the modification of color information. The model effectively reduces color distortion. However, slight brightness differences still exist. Hence there is still room for improvement of imperceptibility. Most of the image steganography methods based on deep learning are operate in the spatial domain. Unlike this kind of steganography, traditional image steganography can be carried out in both spatial and frequency domains. One of the most typical spatial domain steganography is to replace the least significant bit (LSB) of pixels with secret information\cite{r22}.On the other hand, Outguess\cite{r23} and J-UNIWARD\cite{r24} are typical frequency domain steganography. In traditional image steganography, frequency domain steganography usually obtain better robustness and can resist the attack of steganalysis more effectively. Moreover, thanks to the characteristics of frequency transformation, some frequency domain steganography use the HVS characteristics to process frequency domain information to improve the visual quality of the generated image\cite{r9}. There is almost no deep learning image steganography using frequency domain to hide the image. Therefore, relying on the powerful learning ability of deep neural networks and advantages of the frequency domain, the performance of image steganography is expected to be further improved. Although image hiding steganography based on deep learning effectively improves capacity, there are still noticeable color distortion and artificial texture traces. Inspired by traditional frequency domain steganography, this paper attempts to establish a frequency domain color image steganography model based on deep learning. We use the characteristics of color spaces and frequency sub-bands to improve imperceptibility further. Our model shows significant imperceptibility when keeping a large capacity compared with other models. \section{Methodology} We aim to establish a color image steganographic model using a deep neural network based on the frequency domain. We explore methods to improve imperceptibility according to characteristics of color spaces and frequency sub-bands. The proposed model mainly considers how to improve imperceptibility in the case of large capacity (8bpp). Hence the robustness is not discussed in this paper. Our model is a fully convolutional encoder-decoder network. The key to improving imperceptibility is adding the frequency sub-band selection module. The model inputs are a color cover image and a secret gray image. Encoder and Decoder networks output a color stego image and a reconstructed gray secret image. The structure of the proposed model is shown in Figure \ref{fig:3-1}. \begin{figure}[h] \centering \includegraphics[width=1.0\textwidth]{3-1.png} \caption{\label{fig:3-1}The structure of the color image steganographic model based on frequency sub-band selection. The model consists of a frequency sub-band selection module, encoder network, and decoder network. The encoder network includes a pre-processed network for feature extraction of the secret image.} \end{figure} The frequency sub-band selection module pre-processes the cover image. The module selects the B channel as the embedding channel and separates the diagonal high-frequency sub-band (cD). The frequency sub-bands of secret image ([sA, sH, sV, sD]) and cD are the inputs of the encoder network. The encoder network first extracts the features from [sA, sH, sV, sD] and then encodes with cD to hide the secret image. For the extraction of secret information, the decoder network receives the diagonal high-frequency sub-band (cD') as input. Finally, the decoder network outputs the reconstructed secret image through the decoding and inverse DWT. \subsection{Why B Channel} In order to ensure that the stego image has a quality closer to the original cover image, we hope to retain the original image information as much as possible. Therefore, the proposed model only selects one channel of cover image as the embedding channel, which means only 1/3 of the cover image is modified. The data to process is reduced, and the learning efficiency of the network is improved. Considering the influence of color space characteristics, we need to find the optimal embedding channel to obtain the minimum image distortion and the best visual effect. Many steganographic models tried to improve the quality of the generated image by using channels independent of color information (for example, ISGAN uses the Y channel of YUV color space). Therefore, we select the embedding channel in several typical color spaces according to channel characteristics to view the image quality generated by the proposed model. The experimental results are shown Figure \ref{fig:3-2}. \begin{figure}[t] \centering \includegraphics[width=1.0\textwidth]{3-2.png} \caption{\label{fig:3-2}A group of steganographic examples based on different embedding channels. The left column is the original cover image and the secret image (the second row) The others are the stego images and reconstructed secret images generated in the corresponding color space.} \end{figure} We use the proposed model to hide information in different color spaces. We select the common nonlinear luminance/chroma color space (YUV, LAB), intensity/saturation/hue color space (HSV), and the original color space (RGB) and select a channel for embedding in each color space. Since modifying the brightness channel is more imperceptible, we give priority to the brightness channel for YUV, LAB, and HSV. The three channels of RGB color space represent three primary colors, so we hid the image in R, G, and B channels, respectively. As shown in Figure 4, all generated images are almost the same as the cover image. Therefore, the steganographic quality of the proposed model is hardly affected by the characteristics of color space. It can be seen from previous studies that if the modification is visible, the sensitivity of vision to modification can be reduced by using a brightness channel as an embedding channel \cite{r4}. Vision is a subjective judgment. Hence we use the JND (the Just Notice Difference) to calculate the visual detection threshold. JND is the largest image distortion imperceptible to vision, which can judge whether the modification of the cover image reaches the threshold that human eyes can perceive. According to the calculation\cite{r25}, we can see that the JND threshold of the original cover image in Figure \ref{fig:3-2} is 7.46. However, the modification of stego images is far less than the threshold (the maximum modification is 1.30). Therefore, the modification caused by our model does not reach the range that human eyes can perceive. Moreover, in the following experimental part (4.2), we use the new metric proposed in this paper, CL-PSNR, closer to human visual perception to evaluate the quality of stego images. The results show that the CL-PSNR values of different color space experiments remain in the same range of good imperceptibility. Therefore, using other color spaces in our model can not effectively improve imperceptibility but will add unnecessary computational tasks and loss of accuracy (mostly from space transformation operations). Overall, our model uses the original RGB color space. Although three stego images generated based on R, G, and B channels are almost the same in Figure \ref{fig:3-2}, we still select the embedding channel according to the principle of minimizing distortion. We calculate the error per pixel of each stego image, in which the image distortion from the model based on the B channel is the slightest(error per pixel is 0.66 BPP). Moreover, human vision is less sensitive to the modification of channel B than the other two color channels\cite{r26}. Hence B channel is also the best choice. We select the B channel of RGB color space as the embedding channel based on the steganographic results in each color space. Based on the B channel, the stego image is visually close to the original image and has less distortion than that embedded in other channels. \subsection{Selection of Frequency Sub-band} After determining the embedding channel, the frequency sub-band selection module further selects a frequency sub-band as an embedding area. First, the B channel information in the spatial domain will be transformed into frequency domain information. At present, DCT(discrete cosine transform) and DWT are the most commonly used methods for frequency-domain transformation. Compared with DCT, DWT does not produce a blocking effect and can restore images more accurately. Moreover, DWT can also select different wavelet functions according by actual needs to decompose the image signal at different scales\cite{r27}. Therefore, to minimize the accuracy loss caused by frequency-domain transformation, we choose the DWT method to process B channel information. After experiments, we choose the dmey wavelet, which has a better network learning effect. In the complete steganographic process, the spatial-frequency domain transformation of images needs to be carried out twice, used for the data input of Encoder and Decoder. Similarly, the frequency-spatial domain transformation also needs to be carried out twice, used for the output of Encoder and Decoder. In order to further improve the imperceptibility, we select only part of the frequency information of the cover image as the embedding domain instead of modifying all sub-bands. The secret information is a gray image of the same size as the cover image. Hence it is not easy to hide information and maintain good invisibility in a limited embedding domain. In order to ensure that the generated stego image is as close as possible to the original image, we hope that the embedding domain has as little impact on the whole image as possible. After DWT, We will get four frequency sub-bands, [cA, cH, cV, cD]. Where cA is a low-frequency sub-band, corresponds to the region with smooth gray transformation and simple texture in the image. Besides, cH, cV, and cD are high-frequency sub-bands corresponding to the image region with intense gray transformation and complex texture. Although the four frequency sub-bands have the same dimension, most of the energy of the image will be concentrated on cA. On the contrary, cD only contains a small amount of detailed information. It means that the embedding area size provided by cD is the same as other sub-bands. However, with the same modification, its impact on the original image information is the smallest. Figure \ref{fig:3-4} shows images after the same modification on different frequency sub-bands. We set all values in cA and cD to 0. The modification percentage of (a) (which means the percentage of pixels with value error larger than 5 bpp in the whole image) is as high as 99.39\%. In contrast, the modification percentage of (b) is only 10.97\%, and the error range of (b) is smaller than that of (a). Compared with the original image, the maximum pixel value error of (b) is 47.52, while the maximum pixel value error of (a) is as high as 255 (the maximum gray value). Incidentally, performing the same modification on cV and cH, the modification percentage is about 22\%. Although their visual results is better than (a), cD is still the best embedding area choice. \begin{figure}[h] \centering \includegraphics[width=0.4\textwidth]{3-4.png} \caption{\label{fig:3-4} (a) It is the result of setting the values of cA to 0. Almost all information in the original image is lost. (b)Tt is the result obtained by setting the value of cD to 0, which is almost the same as the original image.} \end{figure} In addition to minimizing the modification range of the cover image, the characteristics of HVS are also an important reason we select cD. As shown Figure \ref{fig:3-5}, cA contains almost all the semantic information of the image. Low frequency often corresponds to gently transformed gray areas in the image, such as white walls, sky, etc. Therefore, it is easier for human eyes to detect the modification on cA, which does not fit the imperceptibility requirements of image steganography. Therefore, from the characteristics of HVS, cA is not suitable as an embedding domain. Unlike cA, other sub-bands contain detailed information such as the edge contour of the image. According to HVS characteristics, the vision is relatively insensitive to the modification of areas with complex texture, high contrast, or very bright/dark areas in the image \cite{r28}. Based on this property, we separate the diagonal high-frequency sub-band (cD) as the embedding domain. The cH and cV still contain low frequency information in one direction, so they are not considered embedding domains. \begin{figure}[h] \centering \includegraphics[width=0.6\textwidth]{3-5.png} \caption{\label{fig:3-5}The process of frequency sub-band selection module. Firstly, the B channel is separated, and then DWT operation is performed on the B channel to obtain frequency sub-bands. Finally, the model selects cD as the embedded area.} \end{figure} Figure \ref{fig:3-5} shows the process of the frequency sub-bands selection module. According to the influence of frequency sub-bands and the characteristics of HVS, the module selects cD as the embedding domain to reduce the impact of embedding on image quality. Therefore, the generated image has fewer texture traces and color distortion. After embedding, the output of the encoder network will combine with other frequency sub-bands and be transformed into the spatial domain through inverse DWT. According to the embedding process, we could not measure the embedding position and modification of the stego image in the spatial domain. Therefore, we use the heat map to reflect the modification of the proposed model. Figure \ref{fig:3-7} shows a cover image, a stego image, and a heat map based on the difference between the two images. \begin{figure}[h] \centering \includegraphics[width=0.6\textwidth]{3-6.png} \caption{\label{fig:3-6}The original image, the density image generated by the model, and the heat map based on the two image errors.} \end{figure} The heat map reflects the modification from steganography. In the heat map, red indicates that the pixel value of this position has increased, and blue indicates that the pixel value has decreased. The heat map has both red and blue areas, which means the model does not modify the cover image in only one direction. Since the color block in the heat map shows the outline of the cover image, we speculate that the network modification is determined by the data features of cD. Although almost all pixels in the heat map are colorful, the deviation of the overall pixel value is still within an acceptable range (in the example image, the maximum error is 14 bpp). As shown in Figure \ref{fig:3-6}, the stego image has a high image quality, which is almost the same as the cover image. \subsection{Model Architecture} After the pre-processing of the cover image, the model uses the encoder-decoder network to hide and extract the secret image. Encoder-decoder network is a common network structure in spatial domain steganography. We choose this network to explore whether it can learn the steganographic process in the frequency domain. Compared with other spatial domain steganographic models, the steganographic process is roughly the same, but the data transmitted in our model is frequency domain information. \begin{figure}[h] \centering \includegraphics[width=1.0\textwidth]{3-7.png} \caption{\label{fig:3-7}Detailed configuration of the encoder network (using 250×250 images). The blue blocks are convolution layers, which are used to extract the features of secret image and embedding.} \end{figure} First, the encoder network embeds the secret image into cD. Encoder network is mainly composed of three groups of convolution layers, connection layers, and the input/output layer. The encoder network receives two inputs: the input layer 1 receives the frequency sub-bands [sA, sH, sV, sD], which are obtained after DWT of the secret image. The input layer 2 receives cD from the frequency sub-band selection module. The first two groups of convolution layers pre-process [sA, sH, sV, sD] to extract the data features of the secret image. The output feature maps are connected with cD, and the last group of convolution layers is used for coding. The encoder network outputs the diagonal high-frequency sub-band (represented by cD'), which contains the frequency information of the secret image. Therefore, the stego image still needs to be obtained through the inverse operation of the frequency sub-band selection module. The decoder network is mainly composed of a group of convolution layers, connection layers and the input/output layer. After receiving the stego image, the decoder network separates the cD' according to the frequency sub-band selection module. Input layer 3 receives cD'. Convolution layers perform a decoding operation to extract the frequency information of secret image (represented by [sA', sH', sV', sD']). Finally, the inverse DWT is used to transform the [sA ', sH', sV', sD'] into spatial domain information, that is, to obtain the reconstructed secret image. \begin{figure}[h] \centering \includegraphics[width=0.6\textwidth]{3-8.png} \caption{\label{fig:3-8}Detailed configuration of the decoder network(using 250×250 images). The blue blocks are convolution layers, which are used to extract secret image.} \end{figure} In order to minimize the difference between the stego image and the original image, the secret image and the reconstructed secret image, the loss function we use is the MSE loss function calculated based on frequency domain: \begin{equation} \centering \text Loss(c,c',s,s') = \Vert{c-c'}\Vert^2+\beta \Vert{s-s'}\Vert^2 \end{equation} In equation (1), $c$ and $c'$ represent the frequency domain information of the cover image and stego image, $s$ and $s'$ represent the frequency domain information of the original secret image and reconstructed secret image. In the encoder-decoder structure, image information is transmitted in the form of frequency information. Hence the loss function is also calculated in the frequency domain. The parameter $\beta$ is used to adjust the weight of the decoder network. Although the MSE loss function has achieved a good result in the proposed model, we still expect to design a loss function based on HVS characteristics in the future, which achieves a better imperceptibility. We call the encoder-decoder network a basic model. In early experiments, we found that the steganographic effect of the basic model is better than that of the spatial domain steganographic model with the same structure(Table 2). This not only proves that the encoder-decoder network is also suitable for the deep learning steganography in the frequency domain, but also proves that the frequency domain is more conducive to network learning. Based on the basic model, we add a frequency sub-band selection module to form the final model, which further improves the imperceptibility of steganography. \section{Experiments} In this section, we designed a series of ablation experiments on color spaces and frequency sub-bands, determined the final model based on performances of imperceptibility. In the deep learning steganographic model of hiding a gray image with a color image, we choose Antique's model\cite{r21} and ISGAN\cite{r4} to compare with our final model. Finally, we verified the data generalization ability of the final model. \subsection{Implementation Details} \subsubsection{Dataset} We mainly used the Labeled Faces in the Wild (LFW) dataset during our experiments. This dataset provides more than 13k face images which sizes are reshaped to 250×250. Due to multi posture, illumination, expression, age, occlusion, and other factors, even the photos of the same person are very different. We randomly selected 4K images as the training set and 200 images as the testing set. The training set and testing set are equally divided into cover images and secret images. Secret images are uniformly processed into gray images. In addition, ILSVRC and PASCAL VOC 2012 are also used for model training to verify the final model has a good generalization ability. \subsubsection{Image Quality Evaluation Metric} Firstly, we chose the widely used image quality evaluation metrics: PSNR (Peak Signal to Noise Ratio) and SSIM (Structural Similarity) to measure the quality of generated stego image and reconstructed secret image. During experiments, we found that PSNR sometimes can not directly reflect the perception of vision (especially when evaluating the quality of color images). In Figure 10, a and b are the stego images obtained by the proposed model in two different color spaces. For the observer, it is difficult to detect the difference between a and b, but the result difference of PSNR is more than 30. We believe that this is because PSNR is a metric designed for gray image quality evaluation. Therefore, when evaluating the quality of color image, PSNR sometimes gives results different from human eyes perception. \begin{figure}[h] \centering \includegraphics[width=0.6\textwidth]{4-1.png} \caption{\label{fig:4-1}Image a and b both have almost the same similarity with the cover image, but there is a large difference in their PSNR values. Compared with PSNR, CL-PSNR more fit with human visual perception.} \end{figure} For the limitations of PSNR, we introduce CIE color-difference formula\cite{r29} and propose a new image quality evaluation metric named CL-PSNR. We first calculate the color difference between generated image and the original image, then normalize it and calculate the average value to replace the MSE in the original PSNR equation, which is represented by CL-MSE. \begin{equation} \centering \Delta E_{(x,y)} = \sqrt{ \left(\frac{\Delta L_{(x,y)}^{*} }{K_{L} S_{L}}\right)^2 + \left(\frac{\Delta C_{(x,y)}^{*} }{K_{C} S_{C}}\right)^2 + \left(\frac{\Delta H_{(x,y)}^{*} }{K_{H} S_{H}}\right)^2 } \end{equation} \begin{equation} \centering CL-MSE = \frac{\sum_{n=1}^{N} \frac{\Delta E_{n} }{MAX} }{N} \end{equation} Equation (2) calculates the CIE94 color-difference values of pixels $(L_{x}, a_{x}, b_{x})$ and $(L_{y}, a_{y}, b_{y})$, where $\Delta L_{*}$, $\Delta C_{AB}^{*}$, and $\Delta H_{AB}^{*}$ represent the lightness difference, saturation difference, and hue difference. $K_{L}$, $K_{C}$ and $K_{H}$ are parameter factors. $S_{L}$, $S_{C}$, and $S_{H}$ are correction coefficients of brightness, chroma, and hue. The default values for $K_{L}$ and $S_{L}$ are 1, and the values of $K_{C}$, $K_{H}$, $S_{C}$, and $S_{H}$ are adjusted according to different applications. In equation (3), $N$ means the total number of pixels. $MAX$ represents the maximum CIE color difference, rounded to 140. \begin{equation} \centering CL-PSNR = 10 \times log_{10}\left( \frac{(2^{n}-1)^2}{CL-MSE} \right) \end{equation} In equation (4), we use CL-MSE to replace MSE in the original PSNR equation, so CL-PSNR will consider the influence of color difference. Compared with PSNR, CL-PSNR is more fit with human visual perception. In order to further prove it, we select 100 pictures containing four different distortion types in TID2013 dataset\cite{r30} for verification. \begin{figure}[t] \centering \includegraphics[width=0.5\textwidth]{4-2.png} \caption{\label{fig:4-2}Selected images in TID2013. The distortion types involved JPEG compression, contrast change, color saturation change, and image color quantization with dither.} \end{figure} \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{4-3.png} \caption{\label{fig:4-3}CL-PSNR and MOS(Mean Opinion Score) distribution.} \end{figure} In Figure \ref{fig:4-3}, the vertical axis coordinate represents the Mean Opinion Score (MOS) given by the TID dataset, that is, the score for image quality obtained through subjective human eye experiment. We calculated the CL-PSNR values of sample images, represented them with points in the distribution diagram, and gave the fitting line. From the distribution trend, we can see that the MOS fraction increases with the increase of CL-PSNR, and CL-PSNR is linearly correlated with the MOS score. Therefore, CL-PSNR is suitable for the evaluation of color image distortion. We will add CL-PSNR as a new metric in experiments to evaluate the quality of the color stego image. \subsubsection{Neural Network Training Settings} We use Adam optimizer and train our model for 400 epochs. We set the initial learning rate to 0.001 and decreased to 0.0003 after 150 epochs. After 300 epochs, it decreases to 0.0001. The batch size is 16, and $\beta$ is 1 in the loss function. The model is implemented with TensorFlow, and an NVIDIA Tesla T4 GPU is used. \begin{figure}[h] \centering \includegraphics[width=0.8\textwidth]{4-4.png} \caption{\label{fig:4-4}Five groups of generated images by the final model. It is difficult for human eyes to distinguish the difference between original images and generated images.} \end{figure} Figure \ref{fig:4-4} shows the steganographic effect of the final models. The embedded secret information is a gray image of the same size as the cover image. Hence the capacity of the model is fixed at 8 bpp. \subsection{Ablation Experiments} We designed two ablation experiments to verify the effects of color spaces and frequency sub-bands characteristics on the proposed model. We determined the final model, which uses the cD of the B channel as the embedding domain. \subsubsection{Color Spaces} The following six experiments are designed to verify the superiority of the B channel as an embedding channel. From the perspective of imperceptibility, in order to reduce the sensitivity of human eyes to steganographic traces, we select brightness channels for embedding in YUV, LAB, and HSV color spaces. The three channels of RGB color space represent three primary colors, and there is little difference in the sensitivity of human eyes to their modification. Therefore, the last three experiments are embedded in R, G, and B channels, respectively. The experimental results in Table 1 include the results of error per pixel (denoted by C\_Error per pixel and S\_Error per pixel), peak signal to noise ratio (denoted by C\_PSNR and S\_PSNR), and structural similarity (denoted by C\_SSIM and S\_SSIM) of stego images and reconstructed secret images. We also give CL-PSNR values of stego images. The steganographic performances in each color space are given in figure 4 of Section 3.1, which will not be repeated in this section. \begin{table}[h] \centering \begin{tabular}{lllllll} \hline \begin{tabular}[c]{@{}l@{}}Color space\\ /Embedding \\ Channel\end{tabular} & \begin{tabular}[c]{@{}l@{}}C\_Error \\ per \\ pixel\end{tabular} & \begin{tabular}[c]{@{}l@{}}S\_Error\\ per\\ pixel\end{tabular} & \begin{tabular}[c]{@{}l@{}}C\_PSNR/\\ CL-PSNR\end{tabular} & S\_PSNR & C\_SSIM & S\_SSIM \\ \hline YUV/Y & 1.1529 & 3.5101 & 46.89/40.62 & 37.22 & 0.9919 & 0.9790 \\ \hline LAB/L & 1.3090 & 3.3554 & 45.80/34.36 & 37.61 & 0.9895 & 0.9803\\ \hline HSV/H & 0.9815 & 3.3464 & 48.29/40.75 & 37.63 & 0.9941 & 0.9803\\ \hline \textbf{RGB/R} & \textbf{0.7} & \textbf{3.31} & \textbf{82.12/43.37} & \textbf{37.72} & \textbf{0.9971} & \textbf{0.9999} \\ \hline \textbf{RGB/G} & \textbf{0.69} & \textbf{3.32} & \textbf{82.31/43.67} & \textbf{37.7} & \textbf{0.997} & \textbf{0.9999} \\ \hline \textbf{\begin{tabular}[c]{@{}l@{}}RGB/B\\ (final model)\end{tabular}} & \textbf{0.66} & \textbf{3.3586} & \textbf{82.31/44.33} & \textbf{37.75} & \textbf{0.9975} & \textbf{0.9999} \\ \hline \end{tabular} \caption{\label{tab:1}Comparison of steganographic results based on different color spaces or channels} \end{table} The experimental results show that in the above color spaces, the PSNR of stego images from each experiment is greater than 40, and the SSIM value is close to or greater than 0.99. The PSNR value of secret images is greater than 37, and the SSIM value is close to or greater than 0.98. Combined with table 1 and Figure 4, we believe that in the above color spaces, the generated images have the quality close to original images, and our model is hardly affected by the characteristics of color spaces. We believe that this is because, after frequency sub-bands selection, the model further reduces the steganographic range of the cover image. Hence the modification from embedding does not reach the JND threshold of the cover image. From the first three experiments and the last three experiments, it can be seen that the results of error per pixel, PSNR, CL-PSNR, and SSIM of steganography model based on RGB color space are better than other models. We think this is because the rounding operation of color space transformation may bring additional loss. Based on the principle of distortion minimization, we selected the B channel as the embedding channel of the proposed model. Compared with the modification of the other two color channels, human eyes are more insensitive to the modification of channel B. Moreover, the distortion under B channel is the smallest. \subsubsection{Frequency sub-band selection} In this section, we verified the advantages of frequency sub-bands selection. As shown in Table \ref{tab:2}, we compared the steganographic effects of models under different embedding domains based on the B channel. The embedding domain of the four experiments is the global spatial domain, the global frequency domain(cA+cH+cV+cD), the low frequency sub-band (cA), and the diagonal high-frequency sub-band (cD). \begin{table}[h] \centering \begin{tabular}{lllllll} \hline Embedding Area & \begin{tabular}[c]{@{}l@{}}C\_Error per \\ pixel\end{tabular} & \begin{tabular}[c]{@{}l@{}}S\_Error per \\ pixel\end{tabular} & \begin{tabular}[c]{@{}l@{}}C\_PSNR \\ /CL\_PSNR\end{tabular} & S\_PSNR & C\_SSIM & S\_SSIM \\ \hline Spatial Domain & 5.38 & 10.69 & 76.24/27.24 & 27.54 & 0.9225 & 0.7739 \\ \hline \begin{tabular}[c]{@{}l@{}}Frequency domain\\ (basic model)\end{tabular} & 1.73 & 3.40 & 79.52/38.03 & 37.47 & 0.9923 & 0.9785\\ \hline \begin{tabular}[c]{@{}l@{}}Low Frequency \\ sub-band\end{tabular} & 5.51 & 11.50 & 76.17/27.29 & 26.91 & 0.9211 & 0.7964 \\ \hline \textbf{\begin{tabular}[c]{@{}l@{}}High Frequency \\ sub-band\\ (final model)\end{tabular}} & \textbf{0.66} & \textbf{3.3586} & \textbf{82.31/44.33} & \textbf{37.75} & \textbf{0.9975} & \textbf{0.9999} \\ \hline \end{tabular} \caption{\label{tab:2} Results of steganography based on different embedding domains} \end{table} \begin{figure}[h] \centering \includegraphics[width=1.0\textwidth]{4-5.png} \caption{\label{fig:4-5}The first and third columns are the original cover image and secret image, and other images are the generated images. The right side of each line shows the residual images of stego images.} \end{figure} According to Table \ref{tab:2} and Figure \ref{fig:4-5}, the secret image generated based on spatial domain has obvious distortion. In contrast, the distortion of the image embedded in the frequency domain is slighter and visually closer to the original image (the second line of Figure \ref{fig:4-5}). Therefore, the proposed model can obtain a better imperceptibility in the frequency domain. We believe that this is due to the different characteristics of spatial domain information and frequency domain information. Compared with spatial domain information, frequency domain information is the result of image decomposition from multiple different scales, and its characteristics are more conducive to network learning. According to the experimental results of the last three groups in Table \ref{tab:2}, the C\_Error per pixel of the final model is only 0.66, the PSNR is as high as 82.31, and the SSIM of the stego image and the reconstructed secret image is almost saturated. In the residual images of Figure \ref{fig:4-5}, the steganographic trace generated by the final model is the smallest, so its stego image is closer to the original cover image. We attribute the advantage of the final model to the local modification of frequency domain and avoiding modifying cA, which has a large image energy concentration. When cD is selected for steganography, the dimension of its data accounts for only 1 / 4 of the overall frequency domain. And the data dimension is equal to other sub-bands, but it has less impact on the original image. According to the above experimental results based on color spaces characteristics and frequency sub-bands characteristics, the module frequency sub-band selection of the final model selects the diagonal high-frequency sub-band of the B channel as the embedding domain. \subsection{Comparison with Other Models} In order to verify that the proposed model is superior to similar steganographic models in imperceptibility, we compare the steganographic effect of our model with that of Antique's model\cite{r21} and ISGAN\cite{r4}. Both of them are steganographic models based on a color image hiding a gray image, so they have the same steganographic capacity (8bpp) as the proposed model. The three models are trained with the same dataset. \begin{table}[h] \centering \begin{tabular}{ccccc} \hline Model & C\_PSNR & S\_PSNR & C\_SSIM & S\_SSIM \\ \hline Antique’s Model & 33.7 & 39.9 & 0.95 & 0.96 \\ \hline ISGAN & 34.63 & 33.63 & 0.95 & 0.94 \\ \hline Proposed Model & 82.31 & 37.75 & 0.99 & 0.99\\ \hline \end{tabular} \caption{\label{tab:3}Comparison of steganographic performance of Antique's model, ISGAN, and proposed model.} \end{table} According to Table \ref{tab:3}, except S\_PSNR, other indicators of the final model are the highest, S\_SSIM and C\_SSIM of the final model reached 0.99, which is close to saturation. In addition, it is obvious from Figure 15 that the stego image generated by the final model is closer to the original image. And the distortion of the reconstructed secret image is also really difficult to detect. \begin{figure}[t] \centering \includegraphics[width=1.0\textwidth]{4-6.png} \caption{\label{fig:4-6}The generated images and their residual images based on LFW dataset. The results show that compared with the models of ISGAN and Antique, the image generated by the final model is closer to the original image and has a good imperceptibility.} \end{figure} \begin{figure}[h] \centering \includegraphics[width=0.9\textwidth]{4-7.png} \caption{\label{fig:4-7}(a) The color distortion between generated image and cover images; (b) The texture traces generated by steganography.} \end{figure} \subsubsection{Color Distortion} Figure \ref{fig:4-6} (a) shows the color distortion of different models. It is obvious that the tone of the stego image generated by Antique's model (the second column) is yellower, the stego image of ISGAN is slightly darker, while the stego image of the final model is basically the original image, and the residual image does not show the obvious modification. \subsubsection{Traces of Texture} Figure \ref{fig:4-7} (b) shows the texture traces of different models. Compared with the color distortion, the texture traces of stego image are more difficult to detect by vision, but after enlarging the stego image or multiple residual processing with the original image, we can still find the texture outline of the secret image in the stego image of antique's model and ISGAN(we enhance the brightness of the residual image, so as to make the texture trace in the residual image more obvious). This means that the third party can obtain the semantic information of the secret image according to some simple image processing. Therefore, the security of the secret image is also difficult to guarantee. In contrast, the residual images of the final model still have no visible texture traces, which means our model has a better imperceptibility. In summary, from the perspective of color distortion and texture traces, the proposed model has better performance in imperceptibility. \subsection{Generalization Ability} To further verify the generalization ability of the final model, we used the ILSVRC2012 and PASCAL\_VOC\_2012 dataset training model. \begin{figure}[h] \centering \includegraphics[width=1.0\textwidth]{4-8.png} \caption{\label{fig:4-8}Generated images based on different datasets. The final model can always generate images which close to original images.} \end{figure} \begin{table}[h] \centering \begin{tabular}{ccccccc} \hline Dataset& \begin{tabular}[c]{@{}c@{}}C\_Error \\ per \\ pixel\end{tabular} & \begin{tabular}[c]{@{}c@{}}S\_Error \\ per \\ pixel\end{tabular} & \begin{tabular}[c]{@{}c@{}}C\_PSNR\\ /CL-PSNR\end{tabular} & S\_PSNR & C\_SSIM & S\_SSIM \\ \hline LFW& 0.66 & 3.3586 & 82.31/44.33 & 37.75 & 0.9975 & 0.9999 \\ \hline ILSVRC2012 & 2.86 & 4.21 & 78.07/35.11 & 35.62 & 0.9914 & 0.966 \\ \hline PASCAL\_VOC\_2012 & 2.67 & 6.02 & 78.30/35.49 & 33.05 & 0.9918 & 0.9466 \\ \hline \end{tabular} \caption{\label{tab:4} Training results of the final model based on different datasets} \end{table} The data of the ILSVRC2012 dataset comes from the ImageNet dataset. PASCAL\_VOC\_2012 dataset is commonly used for target detection, including more than 20 object classes and more than 10 action classes. Compared with the LFW dataset used in previous experiments, the data characteristics of the two datasets are more complex, which is helpful for the generalization verification of the final model. Although the performances of training on ILSVRC2012 and Pascal\_VOC\_2012 are slightly lower than that of training on LFW, but its distortion is still within an acceptable range. In addition, all SSIM values of the three results are more than 0.99, which is close to saturation. The last three columns of images in Figure \ref{fig:4-8} are residual images of the original cover image and the stego image. When the residual is expanded to 5 times, the outline of the stego image appears, and when it is expanded to 10 times, the outline is clearer. This means that the final model can still show good imperceptibility on different datasets, and the steganographic performance remains at the same level. Therefore, the proposed model has good generalization ability. \section{Conclusion} In this paper, a color image steganographic model based on frequency sub-band selection is proposed. The model uses the frequency domain as the embedding domain. Moreover, we discuss and verify whether the characteristics of different color spaces and frequency sub-bands will affect the proposed model, which helps us determine the final model. Our model is an encoder-decoder structure model, so the research conclusion has reference significance for the same type of steganographic model and determined the final model. Experiments show that compared with other models, our model effectively reduces the color distortion and texture traces, which significantly improves the imperceptibility. At present, the stego image generated by our model is almost the same as the original cover image. However, there is still room for improvement in the quality of the reconstructed secret image. Moreover, our model has excellent performances in imperceptibility and capacity. Hence we will pay more attention to the improvement of its robustness in our future work. \printbibliography{} \end{document}
{'timestamp': '2021-12-30T02:22:25', 'yymm': '2112', 'arxiv_id': '2112.14437', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14437'}
arxiv
\section*{Negative Societal Impacts} \section{Introduction} \input{1_Introduction/1_introduction} \section{Related Works} \input{2_Related_Work/2_related_work} \section{Method} \input{3_Method/3_0_method} \subsection{Preliminaries} \input{3_Method/3_1_preliminaries} \subsection{Deformable Graph Convolution} \input{3_Method/3_2_deformable_graph_convolution} \input{3_Method/3_2_latent_graph_generation} \subsection{Deformable Graph Convolutional Networks} \input{3_Method/3_3_deformable_gcn} \section{Experiments} \input{4_Experiments/4_0_experiments} \subsection{Dataset} \input{4_Experiments/4_1_dataset} \subsection{Baselines and Implementation Details} \input{4_Experiments/4_2_baseline_and_experimental_settings} \subsection{Results on Node Classification} \input{4_Experiments/4_3_results} \subsection{Ablation Study and Analysis} \input{4_Experiments/4_4_ablation_study} \input{4_Experiments/4_5_analysis} \section{Conclusion} \input{5_Conclusion/5_conclusion} \section*{Acknowledgments} This work was partly supported by MSIT (Ministry of Science and ICT), Korea, under the ICT Creative Consilience program (IITP-2021-2020-0-01819) supervised by the IITP and Samsung Research Funding \& Incubation Center of Samsung Electronics under Project Number SRFC-IT1701-51. {
{'timestamp': '2021-12-30T02:22:27', 'yymm': '2112', 'arxiv_id': '2112.14438', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14438'}
arxiv
\section{Introduction} A recent report by the World Wide Fund for Nature (WWF) confirms that biodiversity and ecosystems are deteriorating worldwide \citep{almond2020living}. Population sizes of mammals, birds, amphibians, reptiles and fish have decreased by an average of 68\% between 1970 and 2016 across the world. This decrease in biodiversity has several causes, such as habitat loss due to pollution, species overexploitation or climate change. Biodiversity is important since it is a key indicator of overall healthy ecosystems which in their turn have important social and economic consequences for humans. In particular, biodiversity and ecosystems influence our water quality, air quality and climate, they secure our food production and impact the spread of infectious diseases originating from animals \citep{almond2020living,diaz2019summary}. Machine learning (ML) can help to more efficiently measure and monitor the well-being of ecosystems and the success of biodiversity conservation efforts \citep{huynh2018annotation,joly2020lifeclef,van2014nature,park2020illuminating}. As an example, this paper proposes a method for automatic classification of camera trap images, a type of motion triggered cameras used in biological studies to estimate animal population density and activity patterns \citep{ridout2009estimating, foster2012critique,rowcliffe2014quantifying,sollmann2018gentle,tabak2019machine, trolliet2014use}. Since manually labeling large numbers of camera trap images is time consuming and costly \citep{kelly2008estimating}, ML could be used to automatically detect animals and the species to which they belong in images. This work uses Convolutional Neural Networks \citep{lecun1998gradient,lecun2015deep} to classify camera trap images. Training a CNN on a dataset of camera trap images is challenging, because camera trap images often only depict a part of an animal, because of high intra-class variation due to differences in backgrounds, and because the class-distribution of camera trap datasets is typically highly imbalanced. This imbalance is inherent to camera trap datasets since it reflects the imbalance of ecosystems \citep{trebilco2013ecosystem}, and it results in biased classifiers that perform very well for a few majority classes but poorly for many minority classes. Classifiers that perform well on all classes would be of more value to ecologists, and moreover, rare or less observed animal species might even be of special interest to research. Therefore, solutions are needed to mitigate this imbalance when classifying camera trap images. To this end, we use a two-phase training method \citep{lee2016plankton} to mitigate class imbalance, for the first time to the best of our knowledge on camera trap images. In experiments we compare it to different data-level class imbalance mitigation techniques, and show that it improves performance on minority classes, with limited loss in performance for other classes, resulting in an increase in macro F1-score. \section{Related work} Pioneering studies that automatically classified camera trap images relied on manual feature extraction and smaller datasets \citep{figueroa2014fast,swinnen2014novel,yu2013automated,chen2014deep}. Better and more scalable results were later achieved with deep CNNs and larger datasets \citep{gomez2016towards,norouzzadeh2018automatically,tabak2019machine, willi2019identifying, schneider2020three}. Generally, models trained by these scholars achieve accuracies well above 90\%, but the models are biased towards majority classes, which severely affects their class-specific performance. Especially the performance for rare species is poor. Scholars dealt with this challenge by removing the rare classes from the dataset \citep{gomez2016towards,willi2019identifying}, with confidence thresholding and letting experts review the uncertain classifications \citep{willi2019identifying}, with weighted losses, oversampling and emphasis sampling \citep{norouzzadeh2018automatically} or by using a combination of additional image augmentations for rare classes and novel sampling techniques \citep{schneider2020three}. Although \citep{norouzzadeh2018automatically} managed to greatly increase the accuracy for a few rare classes using oversampling, none of the aforementioned techniques systematically improved accuracy for most of the rare species. It can thus be concluded that dealing with class-imbalance in the context of camera trap image classification is still an unsolved issue. Two categories of methods for mitigation of class imbalance in deep learning exist: data-level and algorithm-level techniques \citep{buda2018systematic, johnson2019survey}. The former refers to techniques that alter the class-distribution of the data, such as random minority oversampling (ROS) and random majority undersampling (RUS), which respectively randomly duplicate or randomly remove samples to obtain a more balanced dataset. More advanced techniques can also be used to synthesize new samples \citep{chawla2002smote,han2005borderline,he2008adasyn,wan2017variational,wang2017cgan,li2021plankton}, but these are computationally expensive, and they require a large number of images per class and images within a class that are sufficiently similar. Algorithm-level techniques are techniques that work on the model itself, such as loss functions or thresholding \citep{lin2017focal,nemoto2018classification,buda2018systematic,johnson2019survey,he2013imbalanced,buda2018systematic}. Two-phase training, a hybrid technique, was recently introduced and shown to obtain good results for training a CNN classifier on a highly imbalanced dataset of images of plankton \citep{lee2016plankton}, and it was later used by others for image segmentation and classification \citep{havaei2017brain,buda2018systematic}. Because of these promising results and the broad applicability of 2-phase training, we test 2-phase training for camera trap images. \section{Two-phase training} Two-phase training consists of the following steps \citep{lee2016plankton}. $\mathcal{D}_{orig}$ is the original, imbalanced dataset. Figure \ref{fig:two-phase fig} in the appendix shows an overview of two-phrase training. \begin{enumerate} \item \textbf{Phase 1}: a CNN $f_\theta$ is trained on a more balanced dataset $\mathcal{D}_{bal}$, obtained by any sampling method such as ROS, RUS or a combination thereof. \item \textbf{Phase 2}: the convolutional weights\footnote{I.e. all weights except the weights of the fully connected layers that project the CNN features to the classes.} of $f_\theta$ are frozen, and the network is trained further on the full imbalanced dataset $\mathcal{D}_{org}$. \end{enumerate} The 1st phase trains the convolutional layers with (more) equal importance allocated to minority classes, so they learn to extract relevant features for these classes as well. In the 2nd phase the classification layers learn to model the class imbalance present in the dataset. \section{Dataset \& Experiments} We used the 9th season of the publicly available Snapshot Serengeti (SS) dataset, which is generated by a grid of 225 cameras spread over the Serengeti National Park in Tanzania \citep{swanson2015snapshot}. The images were labeled by citizen scientists on the Zooniverse platform. After filtering some images, the full dataset $\mathcal{D}_{orig}$ contains 194k images belonging to 52 classes. The class-distribution of this dataset is depicted in fig. \ref{fig:season9_species fig} in the appendix, and is highly imbalanced, with the three majority classes accounting for just under 75\% of the data. We used this smaller subset of the full SS dataset for computational tractability, and to ensure insights remain valid for ecologists with access to smaller datasets. Appendix \ref{app:hyperparams} lists the hyperparameters\footnote{Our code is publicly available: \url{https://github.com/FarjadMalik/aigoeswild}.}. First we trained the baseline CNN on the full dataset $\mathcal{D}_{orig}$. Next, we trained 4 models with different instantiations of $\mathcal{D}_{bal}$ for phase 1 of two-phase training. \begin{enumerate} \item $\mathcal{D}_{bal}^1$: ROS (oversampling) classes with less than 5k images until 5k, see appendix fig. \ref{fig:ROS}. \item $\mathcal{D}_{bal}^2$: RUS (undersampling) classes with more than 15k images until 15k. \item $\mathcal{D}_{bal}^3$: ROS classes with less than 5k images until 5k as in 1., and RUS classes with more than 15k images until 15k as in 2. Shown in fig. \ref{fig:ROS&RUS} in the appendix. \item $\mathcal{D}_{bal}^4$: ROS classes with less than 5k images until 5k as in 1., and RUS classes with more than 5k images until 5k. \end{enumerate} We used a lower sample ratio for classes with very few images to avoid overfitting (appendix \ref{app:Sampling}). As evaluation metrics we used not only top-1 accuracy but also precision, recall and F1-score, since these metrics are more informative to class-imbalance. We report their values macro-averaged over classes as well as the class specific values (in appendix tables \ref{tab:baseline1}-\ref{tab:rus_perspecies_stat}). The results of the models after phase 1 correspond to the results that we would obtain by only using ROS, RUS or a combination of both (and no two-phase training). These results will thus serve as a baseline. \section{Results} \label{sec:results} \begin{table} \footnotesize \centering \begin{tabular}{lrrrr} \toprule \textbf{Model} & \textbf{Phase 1: Accuracy} & \textbf{Phase 2: Accuracy} & \textbf{Phase 1: F1} & \textbf{Phase 2: F1} \\ \midrule $\mathcal{D}_{orig}$: Baseline & \textbf{0.8527} & / & {0.3944} & / \\ $\mathcal{D}_{bal}^1$: {ROS} & {0.8326} & \textbf{0.8528} & {0.3843} & {0.4012}\\ $\mathcal{D}_{bal}^2$: {RUS} & {0.8012} & {0.8491} & {0.3681} & \textbf{0.4147} \\ $\mathcal{D}_{bal}^3$: ROS\&RUS(15K) & 0.8346 & 0.8454 & \textbf{0.4179} & 0.4094\\ $\mathcal{D}_{bal}^4$: ROS\&RUS(5K) & 0.7335 & 0.8066 & 0.3620 & 0.4001\\ \bottomrule \end{tabular} \caption{Model Comparison - Top-1 accuracy and Macro F1-score.} \label{tab:modelcomparison_top1_F1} \end{table} \paragraph{Accuracy and Macro F1.} Table \ref{tab:modelcomparison_top1_F1} shows the accuracy and F1-score of the models after the 1st and the 2nd phase\footnote{Appendix \ref{app:extra-results} contains more results and in-depth discussion.}. Training on more balanced datasets reduces accuracy in phase 1 for all models compared to the baseline which was trained on the imbalanced dataset $\mathcal{D}_{orig}$. However, further training the classification layers in phase 2 on the full dataset increases accuracy back to more or less the baseline level for all models (except ROS\&RUS(5K)), meaning that two-phase training lost little to no accuracy. The phase 2 mean accuracy is substantially higher than the phase 1 mean accuracy. The F1-scores of most models also drop in phase 1. Interestingly, phase 2 raises the F1-score of most models again, and all models obtain an F1-score after phase 2 that is higher than the baseline: 3.0\% on average. The RUS model obtains the highest F1-score after phase 2: an increase of 5.1\% compared to the baseline, while the ROS\&RUS(15K) model obtain the highest F1-score overall\footnote{We consider the F1-score of ROS\&RUS(15K) after phase 1 an anomaly which needs further analysis.}. Most two-phase trained models outperform their counterparts which were only trained on more balanced datasets. As for the accuracy, the mean F1-score in phase 2 is substantially higher than the mean F1-score in phase 1: 6.1\%. These observations lead us to conclude that 1) two-phase training outperforms using only sampling techniques across most sampling regimes, and 2) two-phase training can increase the F1-score without substantial loss in accuracy, meaning it improves minority class predictions with very limited loss in majority class performance. These findings are in line with the results of \citep{lee2016plankton}, though they report greater increases in F1-scores than us, possibly due to an even more imbalanced dataset. They also find RUS to work best for creating $\mathcal{D}_{bal}$ for phase 1. The F1-scores are substantially lower than the accuracies (idem for precision and recall, appendix tables \ref{tab:modelcomparison_precision}-\ref{tab:modelcomparison_recall}). This is because the class-specific values for these metrics are high for the majority classes, but extremely low for many minority classes, confirming that the imbalanced data creates a bias towards the majority classes. \paragraph{Class-specific performance.} Class-specific F1-scores increase with two-phase training for the majority of (minority) classes. Two-phase training with RUS leads to the greatest average increase of F1-score per class: 3\% (ignoring the classes for which the F1-score remained 0.0\%). This increase is most notable for minority classes. RUS performing best is remarkable, since we trained the RUS model in phase 1 with only 85k images, compared to 131k--231k for the other models. Fig. \ref{fig:f1_comparison_delta_base_rus} shows the changes in F1-score due to two-phase training with RUS. \begin{figure} \centering \begin{subfigure}{0.5\textwidth} \centering \includegraphics[width=0.96\linewidth,keepaspectratio]{f1_comparison_delta_base_rus.png} \caption{} \label{fig:f1_comparison_delta_base_rus} \end{subfigure}% \begin{subfigure}{0.5\textwidth} \centering \includegraphics[width=0.96\linewidth,keepaspectratio]{f1_comparison_delta_rus_phases.png} \caption{} \label{fig:f1_comparison_delta_rus_phases} \end{subfigure} \caption{Relative difference in F1-score per species of (\subref{fig:f1_comparison_delta_base_rus}) the two-phase RUS model vs. the baseline, and (\subref{fig:f1_comparison_delta_rus_phases}) phase 2 vs. phase 1 of the RUS-model. The appendix contains larger versions: figs. \ref{fig:f1_comparison_delta_base_rus_l}, \ref{fig:f1_comparison_delta_rus_phases_l}. Species are sorted in descending order according to their occurrence frequency.} \label{fig:f1_comparisons} \end{figure} \section{Conclusion} We explored the use of two-phase training to mitigate the class imbalance issue for camera trap image classification with CNNs. We conclude that 1) two-phase training outperforms using only sampling techniques across most sampling regimes, and 2) two-phase training improves minority class predictions with very limited loss in majority class performance, compared to training on the imbalanced dataset only. In the future we would like to rerun our experiments with different random seeds to obtain more statistically convincing results, compare two-phase training to other algorithm-level imbalance mitigation techniques, and test it on varying dataset sizes and levels of class imbalance. \clearpage
{'timestamp': '2021-12-30T02:25:13', 'yymm': '2112', 'arxiv_id': '2112.14491', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14491'}
arxiv
\section{Introduction} In this era of informatization and data in trajectories, nature and human activities will be recorded as a large amount of asynchronous sequential data, for instance, the record of occurrence of earthquakes and aftershocks \cite{1ogata1998space}, transaction history of financial markets \cite{2bacry2015hawkes}, electronic health record \cite{3wang2018supervised}, equipment failure history \cite{4zhang2020survival} and user behavior in social networks \cite{5zhou2013learninga,6zhao2015seismic}, such as Weibo, Twitter, Facebook, etc. all are asynchronous events sequences data. These asynchronous sequences contain valuable knowledge and information, researchers utilize a variety of methods to better mine these knowledge and information from the data. Among a diversity of methods, point process is one of the most widely used methods in this field, and in point process models, Hawkes process \cite{7hawkes1971spectra} is one of the most commonly used model. The self-exciting progress in Hawkes process fits the interaction between events to some extent, thus the application of Hawkes process achieves certain results in sequence analysis. For example, Zhou et al. present alternating direction method of multipliers (ADMM)-based algorithm to learn Hawkes process to discover the hidden network of social influence \cite{7hawkes1971spectra}, Xu et al. make use of non-parametric Hawkes process to reveal the Granger causality between the users activity on watching internet protocol television (IPTV) \cite{8xu2016learning}. Hansen et al. demonstrate the great expressive potential of Hawkes process in neuroscience with least absolute shrinkage and selection operator (LASSO) method \cite{9hansen2015lasso}. Reynaud-Bouret and Schbath provide a new way to detect the favored or avoided distances between genomic events along deoxyribonucleic acid (DNA) sequences \cite{10reynaud2010adaptive}. Zhang et al. \cite{4zhang2020survival} modify the traditional Hawkes process, introducing the time-dependent background intensity to Hawkes process to analyze the background probability of failure and relationship between failures in compressor station. However, traditional Hawkes process only considers the positive superposition of effect of historical events, which severely constrains the fitting ability of this type of model. Meanwhile, the lack of nonlinear operations in traditional Hawkes process also sets an upper limit for Hawkes’ expressive ability. Thus, in recent years, due to the strong fitting ability of neural networks and especially the sequence modeling ability of RNN, the research direction in this field is transferred to the neural point process model. For instance, Du et al. \cite{11du2016recurrent} embed the information of sequence data (including time-stamp and event type) into RNN, and come up with the recurrent marked temporal point processes (RMTPP) to model the conditional intensity function by nonlinear dependency of the history. And similar to RMTPP, Mei et al. \cite{12mei2017neural} propose the continuous-time LSTM (Long Short-Term Memory) to model the conditional intensity of point process, which is called as neural Hawkes process, and in this continuous neural Hawkes process, the influence of the previous event decays with time continuously. Xiao et al. use two RNN to model the conditional intensity function, one is used to process time stamp information, and the other is used to process historical event information \cite{13xiao2017modeling}. Inevitably, these RNN based-models also inherit the drawbacks of RNN, for instance, it may take a long time for the patient to develop symptoms due to certain sequel, which has obvious long-term characteristics, such as diabetes, cancer and other chronic diseases, while these RNN-based models are hard to reveal the long-term dependency between the distant events in the sequences \cite{14bengio1994learning}. The ideal point process model should be able to solve these problems. Moreover, in the training of RNN-based models, such problems as vanishing and exploding Gradients \cite{15pascanu2013difficulty} often occur, and then affect the performance of the model. It’s worth noting that in traditional sequence learning problem, such as machine translation \cite{16raganato2018analysis} and speech recognition \cite{17dong2018speech}, transformer model \cite{18vaswani2017attention} based on self-attention \cite{19DBLP:journals/corr/BahdanauCB14} mechanism achieves distinct performance improvement without application of CNN and RNN, meanwhile, the transformer structure free-from recurrent modules makes the model have higher computational efficiency. These achievements give a new insight on the development of sequential data learning. On account of this fact, Zhang et al. present self-attention Hawkes process \cite{20zhang2020self}, furthermore, Zuo et al. \cite{21DBLP:conf/icml/ZuoJLZZ20} propose transformer Hawkes process based on the attention mechanism and encoder structure in transformer. This model utilizes pure transformer structure without using RNN and CNN, and achieves state-of-the-art performance, but there is still much room for improvement in the transformer models, for instance, transformer simply stack the encoder layer to learn sequence data, and foregoes the recursive bias learning in RNN, while this recursive learning might be more important than commonly believed. Dehghani et al. point out that re-introduce recurrence calculation in transformer maybe promote the performance of transformer, which is called as universal transformer \cite{22DBLP:conf/iclr/DehghaniGVUK19}, this model combines the advantage of transformer and RNN, organically combines the self-attention and recurrence learning mechanism. In recurrence process, Dehghani et al. make use of the ACT mechanism \cite{23graves2016adaptive} to decide when the recurrence process will halt. The experimental results of universal transformer demonstrate that the effectiveness of the combination of self-attention mechanism and recurrence mechanism. Based on the achievements of universal transformer, we tend to work out a new framework of transformer Hawkes process based on the idea of universal transformer, we name it as universal transformer Hawkes process. We introduce the recurrent structure in transformer Hawkes process, and make our model to achieve Turing completeness compared with previous transformer model. Moreover, we add a convolution module to the position-wise-feed-forward-layer, which enhance the local perception ability of universal transformer Hawkes process. We conduct the experiments on multiple dataset to compare with state-of-the-art baselines, to validate the effectiveness of our model. We also demonstrate whether the additional RNN layers will have a positive impact on fitting mutual interdependence among the events in the sequence. In addition, to demonstrate the effectiveness of the ACT mechanism, we compare the performances of universal transformer with and without the ACT mechanism, and verify that the halting mechanism of dynamic iteration will make the model perform better overall. Our paper is organized as follows. In Section 2, we introduce the related work about Hawkes process and point process in view of the neural network. In Section 3, we are going to instruct our model in details, including structure, condition intensity function, prediction tasks and training process. At last, Section 4 lists our experimental results to illustrate the advantages of universal transformer Hawkes process and t ACT mechanism. At last, Section 5 concludes the article. \section{Related work} \subsection{Hawkes process} Hawkes process has form shown as the following: \begin{equation} \label{eq1} \lambda (t) = \mu (t) + \sum\limits_{i:t_i < t} {\phi (t - t_i )} \end{equation} where $\mu (t)$ is background intensity function, indicates the background probability of event occurrence, $\phi (t)$ is the impact function, which used to measure the historical event influence, and $\sum\limits_{i:t_i < t} {\phi (t - t_i )} $ records the impact of all historical events on the current instant. Traditional Hawkes process model in Eq. 1 assumes the positive superposition of past historical impact. Until now, there are many variants of traditional Hawkes process. Zhao et al. firstly make use of Hawkes process to model the Twitter data to predict the final number of reshares, which only have small relative error \cite{6zhao2015seismic}. Xu et al. use the non-parametric method to represent the Hawkes process, and utilize a corresponding learning algorithm to get the better performance of the model, and then the Granger causality on of IPTV user on watching program is obtained \cite{8xu2016learning}. Kobayashi and Lamhbiotte present a time-dependent Hawkes process, whose impact functions are time-dependent. They validate the method on Twitter data and prove that there is a systematic improvement to the previous method \cite{24kobayashi2016tideh}. Yang et al. develop an online learning method of Hawkes process based on the nonparametric method \cite{25yang2017online}. In 2018, Alan reviews and summarizes the application of the Hawkes process proposed by him in the financial field \cite{26hawkes2018hawkes}. Mohler presents a novel modulated Hawkes process, to quickly identify risks and trigger appropriate public safety responses in communities to prevent a range of social harm events, such as crime, drug abuse, traffic accident and medical emergencies \cite{27mohler2018improving}. Zhang et al. \cite{4zhang2020survival} make significant improvement to the Hawkes process model, the Weibull background intensity is used instead of constant background intensity. Weibull background intensity is a kind of time-dependent background intensity, which can better describe the trend of the base possibility of the event over time. After verifying the effectiveness of this Weibull-Hawkes process and the corresponding learning algorithm, based on this new model, Zhang et al. analyze the failure sequence of the compressor station and list the trend of background probability of failures in the compressor station over time and the Granger causality between the failures, and some suggestions are made for the production of the compressor station. \subsection{Transformer and Universal Transformer} In 2017, Vaswani et al. propose transformer model \cite{18vaswani2017attention}, which makes full use of self-attention \cite{19DBLP:journals/corr/BahdanauCB14} module, and discards the CNN and RNN structure, achieves a great improvement in the field of sequence learning, such as natural language processing \cite{28chowdhary2020natural}. However, recent research shows that the recurrent learning in RNN can have a greater role beyond imagination, thus, Dehghani et al. propose universal transformer \cite{22DBLP:conf/iclr/DehghaniGVUK19} which combine the recurrent learning and self-attention mechanism, moreover, in order to better allocate model computing resources, the ACT mechanism \cite{23graves2016adaptive} is introduced into models, then, this model achieves better results than transformers. \subsection{Neural Hawkes Process} In general, the neural network has a stronger nonlinear fitting ability than other models, especially RNN is better at learning sequence data than other neural networks, so it has been often used in the processing of sequence data such as speech and text. Therefore, researchers also hope to use RNN to fit asynchronous event sequence data. Du et al. present RMTPP models \cite{11du2016recurrent}, to learn the history effect via RNN, including history event type and time-stamp. For the first time, this neural model abandons the overly strong assumptions of the Hawkes process and other point process models, and achieves greater improvements. Xiao et al. make use of two RNN to model the event sequence, one of them is used to model the background intensity and the other is used to model the impact of historical events \cite{13xiao2017modeling}. This method allows a black-box treatment for modeling the conditional intensity function, and end to end training can make model event sequences easier. Mei and Eisner propose a new form of LSTM \cite{12mei2017neural}, the continuous time LSTM, whose state can decay to another with time, and based on this LSTM they come up with the neural Hawkes process to model the asynchronous event sequence, which obtains better model performance. While the shortcomings of RNN gradually appear, researchers tend to use better neural networks to model event sequences. Zhang et al. \cite{20zhang2020self} firstly utilize self-attention mechanism to get the Hawkes process of the sequence. And based on the achievement of transformer, and enlighten by \cite{18vaswani2017attention}, Zuo et al. utilize the encoder structure in transformer, and propose the transformer Hawkes process (THP) \cite{21DBLP:conf/icml/ZuoJLZZ20}, this model encodes and converts event sequence data into hidden representations, and then maps hidden representations into continuous conditional intensity functions. \section{Proposed Model} \begin{table}[!htbp] \caption{Nomenclature} \label{tb1} \resizebox{150mm}{93mm}{ \begin{tabular}{cccc} \hline Symbols & Description & Variable names in ACT mechanism & Size\\ \hline $S_e$ &The dataset of sequences & / & / \\ $s_n$ & The $n$-th sequence &/ & / \\ $I_n$ & The length of $n$-th sequence &/ & / \\ $N$ &The total number of sequences &/ & $\mathbb{N}^ +$ \\ $C$ &The total number of type of events in sequences &/ & $\mathbb{N}^ +$ \\ $t_i$ & The time stamp of $i$-th event &/ & $\mathbb{R}$ \\ $c_i$ & The event type of $i$-th event &/ & $\mathbb{N}^ +$ \\ $D$ &The model dimension of universal transformer & /& $\mathbb{N}^ +$ \\ $\bm{K}$ & The embedding matrix of event type & /& $\mathbb{R}^ {D\times C}$ \\ max\_n & The max iteration times of ACT mechanism & /& $\mathbb{N}^ +$ \\ $\mathbb{I}( \cdot )$ &Indicator function &/& / \\ \textit{EncodingLayer} & The encoding layer in ACT mechanism &/ & / \\ $T_h$ & The threshold in ACT mechanism & threshold & $\mathbb{R}$ \\ $\bm{W}_p$ & The weight p in ACT mechanism & weight\_p & $\mathbb{R}^ {D\times 1}$ \\ $S$ & The state variable in ACT mechanism & state & $\mathbb{R}^ {I_n\times D}$ \\ $P_S$ & The previous state variable in ACT mechanism & previous\_state & $\mathbb{R}^ {I_n \times D}$ \\ $h_p$ & The halting probability variable in ACT mechanism &halting\_probability & $\mathbb{R}^ {D}$ \\ $R_e$ &The remainders variable in ACT mechanism &remainders & $\mathbb{R}^ {D}$ \\ $n$ & The upgrade times of state in ACT mechanism & n\_updatas & $\mathbb{R}^ {D}$ \\ $S_r$ & The still running variable in ACT mechanism &still\_running & $\mathbb{R}^ {D}$ \\ $n_h$ & The new halted variable in ACT mechanism &new\_halted & $\mathbb{R}^ {D}$ \\ $W$ & The update weight of ACT mechanism &update\_weight & $\mathbb{R}^ {D}$ \\ $L$ &he number of multi-head attention & /& $\mathbb{R}$ \\ $\left\{ {{\bm{A}}_l } \right\}_{l = 1}^L $ & The number of multi-head attention &/ & $\mathbb{R}^ {D_V}$ \\ ${D_K}$ &The dimension of query and key vector &/ & $\mathbb{N}^ +$ \\ ${D_V}$ & The dimension of value vector &/ & $\mathbb{N}^ +$ \\ $\left\{ {{\bm{Q}}_l } \right\}_{l = 1}^L$ &The query variable of multi-head attention &/ & $\mathbb{R}^{I_n \times D_K }$ \\ $\left\{ {{\bm{K}}_l } \right\}_{l = 1}^L$ &The key variable of multi-head attention &/ & $\mathbb{R}^{I_n \times D_K }$ \\ $\left\{ {{\bm{V}}_l } \right\}_{l = 1}^L$ &The value variable of multi-head attention &/ & $\mathbb{R}^{I_n \times D_V }$ \\ $\left\{ {{\bm{W}}_Q^l } \right\}_{l = 1}^L$ &The query matrix of multi-head attention &/ &$\mathbb{R}^{D \times D_K }$ \\ $\left\{ {{\bm{W}}_K^l } \right\}_{l = 1}^L$ &The key matrix of multi-head attention &/ & $\mathbb{R}^{D \times D_K }$ \\ $\left\{ {{\bm{W}}_v^l } \right\}_{l = 1}^L$ &The value matrix of multi-head attention &/ &$\mathbb{R}^{D \times D_K }$ \\ $W_{multi}$ & The aggregation matrix of multi-head attention &/ & $\mathbb{R}^{LD_V \times D }$\\ $\bm{A}'$&Obtained from $\bm{A}$ passes through fully connected layer FC1 &/ & $\mathbb{R}^{I_n \times D }$ \\ $\bm{A}''$& Obtained from $\bm{A}'$ passes through CNN layer and fully connected layer FC2 &/ & $\mathbb{R}^{I_n \times D_H }$ \\ $D_{RNN}$& The dimension of RNN in the model &/ & $\mathbb{N}^ {+}$ \\ $S'$ & Obtained from , the output of ACT mechanism, passes through fully connected layer FC3 &/ & $\mathbb{R}^{I_n \times D_{RNN}}$ \\ $S''$ & Obtained from passes through RNN and fully connected layer FC4 &/ & $\mathbb{R}^{I_n \times D}$ \\ $\bm{H}$ &The hidden representation of sequence &/ & $\mathbb{R}^{I_n \times D}$ \\ $\bm{h}(t_i)$ & The hidden representation of \textit{i}-th event &/ & $\mathbb{R}^{ D}$ \\ $\mathcal{H}_t$ & The previous history at time \textit{t} & / & / \\ $b_c$ & The background intensity of event type \textit{c} &/ & $\mathbb{R}$ \\ ${\alpha _c } $ & Thecontinuous parameter of conditional intensity function of event type &/ & $\mathbb{R}^{1\times D}$ \\ ${\bm{w}}_c^T $& Historical weight parameter of conditional intensity function of event type &/ & $\mathbb{R}^{1\times D}$ \\ $\bm{W}_{time}$ & The prediction parameter of time-stamp&/ & $\mathbb{R}^{1\times D}$ \\ $\bm{W}_{type}$ &The prediction parameter of event type &/ & $\mathbb{R}^{C\times D}$ \\ \hline \end{tabular}} \end{table} For sequences of asynchronous events, we need to determine what model they have. The symbols used in the paper are shown in Table 1, and in general, we formulate it as following: assume that there are $N$ sequences in the dataset of the asynchronous events, represented as $S_e = \{ s_n \} _{n = 1}^N$ , and for each sequence, note that their lengths are not the same, for the $n$-th sequence $s_n = \{ t_i ,c_i \} _{i = 1}^{I_n } $ , its length is $I_n$ , each sequence $s_n$ is composed with $I_n$ tuples, $t_i$ is the time-stamp of $i$-th event, and $c_i\in C$ is the corresponding event type. In the forward phase, for arbitrary sequence $s_n = \{ t_i ,c_i \} _{i = 1}^{I_n } $ , the entire sequence could be directly input to the universal transformer, supposing the model dimension is $D$ , then all these events in the sequences (including their time-stamp) can be represent by their corresponding $D$-dimensional vectors, then this sequence can be described by the hidden representation of event sequence ${\bm{H}} \in \mathbb{R}^{D \times I_N } $ . The continuous conditional intensity function can be calculated by ${\bm{H}} \in \mathbb{R}^{D \times I_N } $ and the equation we proposed in section 3.2. \subsection{Universal Transformer Hawkes Process} First, we need to map the asynchronous event sequence into the temporal encodings, which denote the occurring times of events, and event-type encodings. According to point process theory, the time-stamps of events in the event sequences are the coordinate on the temporal axis, in other words, time-stamps are temporal position of events. Analogous to the text sequence, the time-stamps in the event sequence are equivalent to the position of the words, and the event type embedding vectors are equivalent to the semantic vectors of the words. Thus, for the temporal encodings, we can leverage the position encoding approaches in nature language processing to encode the time-stamps of events, similar as [18,21], the position encoder for the occurring time-stamp of event is shown as Eq.2: \begin{equation} \label{eq2} [{\bm{x}}(t_i )]_j = \left\{ {\begin{array}{*{20}c} {\cos \left( {t_i /10000^{\frac{{j - 1}}{D}} } \right),{\rm{if}}\:j\:{\rm{is}}\:{\rm{odd}},} \\ {\sin \left( {t_i /10000^{\frac{j}{D}} } \right),{\rm{if}}\:j\:{\rm{is}}\:{\rm{even}}.} \\ \end{array}} \right. \end{equation} Thus, for the time-stamp $t_i$ of event, its corresponding temporal encoding is $ {\bm{x}}(t_i ) \in \mathbb{R}^D $ , where $D$ is the model dimension of universal transformer, and in order to get event-type encoding, we set embedding matrix ${\bm{K}} \in \mathbb{R}^{D \times C} $, and each kind of event is corresponding to an one-hot encoding ${\bm{c}}_i \in \mathbb{R}^C $ , then we can get the event-type encoding $ {\bm{Kc}}_i \in \mathbb{R}^D $ . We define that $\bm{X}^T$ and $({\bm{KC}}_n )^T$ are the corresponding temporal encoding and event-type encoding of the sequence, where $ {bm{X}} = \{ {bm{x}}(t_1 ),{bm{x}}(t_2 ),...,{bm{x}}(t_{I_n } )\} \in \mathbb{R}^{D \times I_n } $ and ${bm{C}}_n = [c_1 ,c_2 ,...,c_{I_n } ] \in \mathbb{R}^{C \times I_n } $ . In order to get the hidden representation of event sequence, we need to input the above temporal and event-type encodings into the recurrent part in universal transformer, which is shown as Fig. 1 and Fig. 2. \begin{figure}[!htbp] \centering \includegraphics[scale=0.7]{1.pdf} \caption{Schematic diagram of universal transformer with pure recurrence, the model simply uses the hidden state as a recurrent variable } \label{fig1} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[scale=0.7]{2.pdf} \caption{Schematic diagram of universal transformer based on ACT algorithm, in the model, ACT algorithm provides a measure of how well of learning of different elements in the variable.} \label{fig1} \end{figure} Different with traditional transformer, for universal transformer, the temporal and event-type encodings will be alternatively and recursively refined by attention and convolutional layers until a certain stop condition is met, then the final hidden representation will be acquired. In universal transformer with pure recurrence illustrated in Fig. 1, the hidden state will iterate the predetermined number of times, and the final hidden state is set as the hidden representation of event sequence. The corresponding implementation process is shown as the Algorithm 1: \begin{algorithm} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \caption{Universal Transformer with pure recurrence.} \label{alg1} \begin{algorithmic}[2] \REQUIRE The maximum number of iterations: max\_n, event-type encoding $({\bm{KC}}_n )^T $, temporal encoding (position encoding) $\bm{X}^T$ and \textit{EncodingLayer} in model. \ENSURE Hidden representation of event sequence ${\bm{H}} \in \mathbb{R}^{D \times I_N } $ (State) \STATE Initialize state $n\leftarrow0$, $ {\bm{S}} \leftarrow ({\bm{KC}}_n )^T $ . \STATE \textbf{while} $(n<\rm{max\_n})$ \textbf{do} \STATE ${\bm{S}} \leftarrow {\bm{S}} + {{ }}{\bm{X}}^T $ \STATE ${\bm{S}} \leftarrow output\;of\;{\rm{the}}\;i{\rm{ - th }}\;{\rm{encoding\;layer}}({\bm{S}})$ \STATE \textbf{end while} \STATE \textbf{return} ${\bm{H}} \leftarrow {\bm{S}}$ \end{algorithmic} \end{algorithm} In iterative process, some symbols, such as words and phonemes, in our application scenario they are the temporal and event-type encodings, are usually more ambiguous than other elements in the sequence, the more ambiguous these symbols are, and the more refining processes are required. However, the above algorithm simply refines equally among each element in the sequence, it is easy to see that this mechanism is too rough and doesn’t meet the requirement we mentioned. Thus, similar as \cite{22DBLP:conf/iclr/DehghaniGVUK19}, we adopt the ACT mechanism \cite{23graves2016adaptive} in our proposed universal transformer Hawkes process, which is a mechanism can dynamically adjust the number of refinedness for each symbol in the sequence. The ACT mechanism updates the symbols in the sequence according to their state parameter. Since ACT method is used in speech recognition and other scenarios and cannot be directly applied to event sequence data, we are going to make some certain modifications to the concrete implementation procedure of the ACT mechanism. The modified ACT mechanism is illustrated in Algorithm 2, and the information flow diagram of ACT mechanism in Universal transformer is shown in Fig. 3. \begin{algorithm} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \caption{Universal Transformer based on ACT mechanism.} \label{alg2} \begin{algorithmic}[2] \REQUIRE The maximum number of iterations: max\_n, event-type encoding $({\bm{KC}}_n )^T $, temporal encoding (position encoding) $\bm{X}^T$, threshold $T_h$ and \textit{EncodingLayer} in model.\\ \textbf{Paremeter}:${\bm{W}}_p \in \mathbb{R}^{D \times 1} $ \ENSURE Hidden representation of event sequence ${\bm{H}} \in \mathbb{R}^{D \times I_N } $ (State) \STATE Initialize state $n \leftarrow {0},R_e \leftarrow 0,h_p \leftarrow 0,P_s \leftarrow 0 $ and $ {\bm{S}} \leftarrow ({\bm{KC}}_n )^T $ . \STATE \textbf{while} there is any element in $\left( {(h_p > T_h )\& (n < \max \_n)} \right)$ is true, \textbf{do} \STATE ${\bm{S}} \leftarrow {\bm{S}} + {{ }}{\bm{X}}^T $ \STATE $p \leftarrow Sigmoid (S{\bm{W}}_p )$ \STATE $S_r \leftarrow \mathbb{I}(h_p < 1.0)$ \STATE $N_h \leftarrow (h_p + (p*\mathbb{I}(S_r > T_h ))*S_r$ \STATE$S_r \leftarrow (h_p + (p*\mathbb{I}(S_r \geqslant T_h ))*S_r $ \STATE$ h_p \leftarrow h_p + p*S_r $ \STATE$ R_e \leftarrow R_e + N_h *(1 - h_p ) $ \STATE$ h_p \leftarrow h_p + N_h *R_e $ \STATE$ n \leftarrow n + S_r + N_h $ \STATE$ W \leftarrow p*S_r + N_h *R_e $ \STATE$ S \leftarrow EncodingLayer(S) $ \STATE$ P_S \leftarrow S*W + P_S *(1 - W) $ \STATE \textbf{end while} \STATE \textbf{return} ${\bm{H}} \leftarrow {{P_S}}$ \end{algorithmic} \end{algorithm} \begin{figure}[!htbp] \centering \includegraphics[scale=0.7]{3.pdf} \caption{Diagram of universal transformer based on ACT mechanism, the figure shows the information flow and update process of different variables } \label{fig3} \end{figure} We can see that universal transformer without ACT mechanism and RNN have obvious similarities, in both models, there is only state calculated recursively in the iteration, and universal transformer with ACT mechanism is more similar to LSTM, because there are multiple variables to be updated in the recurrence, and the updated weights are to some extent consistent with the forgetting gate in LSTM. These facts show that universal transformer with ACT mechanism will have a stronger learning ability than universal transformer without ACT mechanism. \begin{figure}[!htbp] \centering \includegraphics[scale=0.7]{4.pdf} \caption{The diagram of encoding layer in universal transformer, the self-attention mechanism of universal transformer is similar to the normal transformer, and we modify position-wise-feed-forward part, add a convolutional layer between the two fully connected layers to enhance the local perception ability of the model. } \label{fig4} \end{figure} In both algorithms, we all are going to feed the state in Algorithm 1 and 2 into the encoding layer, whose flow-chart is illustrated in Fig. 4, encoding layer is composed with two parts, i.e., multi-head attention part and position-wise-feed-forward part. In encoding layer, we also utilize the commonly used techniques in transformer to relieve the difficulty in training, such as the residual connection \cite{29he2016deep} and layer normalization \cite{30ba2016layer}. In multi-head attention part, we also adopt dot-product attention, which can be written as Eq.3: \begin{equation} {\bm{A}} = Softmax\left( {\frac{{{\bm{QK}}^T }} {{\sqrt {D_K } }}} \right){\bm{V}} \end{equation} where \begin{equation} {\bm{Q}} = {\bm{SW}}_Q ,{\bm{K}} = {\bm{SW}}_K ,{\bm{V}} = {\bm{SW}}_V \end{equation} state $S$ is the input to the encoding layer, $\bm{Q}$,$\bm{K}$,and $\bm{V}$ are respectively query, key and value matrices, which are obtained by different linear transformations ${\bm{W}}_Q ,{\bm{W}}_K \in \mathbb{R}^{D \times D_K } $ , $ {\bm{W}}_V \in \mathbb{R}^{D \times D_V } $ of state $S$ . And in order to improve the diversity and expressive ability of model, we make use of multi-head self-attention to make the model perform better. If we utilize L heads self-attention, then, we can get $L$ outputs ${\bm{A}}_1 ,{\bm{A}}_2 ,...,{\bm{A}}_L $ , which are computed by different sets of matrices $\left\{ {{\bm{W}}_Q^l ,{\bm{W}}_K^l ,{\bm{W}}_V^l } \right\}_{l = 1}^L $ . The formula for multi-head attention is shown as Eq.5: \begin{equation} {\bm{A}} = \left[ {{\bm{A}}_1 ,{\bm{A}}_2 ,...,{\bm{A}}_L } \right]{\bm{W}}_{multi} \end{equation} In Eq.5, ${\bm{W}}_{multi} \in \mathbb{R}^{LD_V \times D}$ is the aggregation matrix. It is worth noting that the events in the sequence occur in sequential order, thus, it has the characteristic called as “future invisibility”, we need to block the impact of future events on current time. We utilize the masked self-attention mechanism similar as \cite{18vaswani2017attention}. For example, we set ${\bm{E}} = {\bm{QK}}^T $ , the masked self-attention mechanism will set the element in the $i$-th row in $\bm{E}$ ranged in ${\bm{E}}(i,i + 1),{\bm{E}}(i,i + 2),..,{\bm{E}}(i,D)$ to negative infinite, which will ensure that the self-attention weight of future events obtained through softmax function is 0. After getting the attention output ${\bm{A}}$ it will be fed into position-wise-feed-forward part, which is shown in the right part of Fig. 4. To improve model’s local perception of the sequence, we introduce the CNN module in position-wise-feed-forward part, more specifically, fully connected layer FC1 transforms attention output ${\bm{A}}$ into a higher-dimensional linear matrix ${\bm{A'}} \in \mathbb{R}^{I_n \times D_H } $ . Then it pass through the convolutional layer, nonlinear layer, and pooling layer, and fully connected layer FC2 will convert it to the original dimension ${\bm{A''}} \in \mathbb{R}^{I_n \times D}$. After the Algorithm 1 or 2 completely stop, we will get the output $H$, and at last, will be as the input of postprocessing part, which is constituted with fully connected layer FC3, RNN layer and final fully connected layer FC4. This structure is motivated by \cite{21DBLP:conf/icml/ZuoJLZZ20},\cite{31wang2019language}, and in fact the additional RNN can make model better fit the sequential data, in a nutshell, the FC3 transforms input $S$ or $P_S$ to $S' \in \mathbb{R}^{I_n \times D_{{\rm{RNN}}} } $ and $S'$ will be recurrently iterated by the RNN, note that the types of RNN can be selected as LSTM or GRU, then the FC4 converts $S'$ into $S'' \in \mathbb{R}^{I_n \times D } $ , at last, $S''$ will be assigned to the hidden representation ${\bm{H}} \in \mathbb{R}^{I_n \times D} $ of the sequence of events. The effectiveness of postprocessing part in UTHP is decided by the characteristic of the dataset, and we will discuss this issue in subsection 4.3.2 and analyzed it in experiments. \subsection{Conditional Intensity Function} In general, point processes are supposed to be described by their corresponding conditional intensity functions. However, after encoding operation of universal transformer, we can only get the discrete conditional intensity established by hidden representation of event sequence. Therefore, we need to construct the continuous conditional intensity function on the foundation of hidden representation of event sequence. For every kind of event, we denote $\lambda _c (t\left| {\mathcal{H}_t } \right.)$ as corresponding conditional intensity function of UTHP, and here $\mathcal{H}_t = (t_i ,c_i ):t_i < t$ is the history of past events at time \textit{t}. Similar as \cite{21DBLP:conf/icml/ZuoJLZZ20}, the form of conditional intensity function is shown as Eq.6: \begin{equation} \lambda _c (t\left| {\mathcal{H}_t } \right.) = f(b_c + \alpha _c \frac{{t - t_i }} {{t_i }} + {\bm{w}}_c^T {\bm{h}}(t_i )) \end{equation} In Eq.6, $t \in [t_i ,t_{i + 1} )$, and $b_c$ is the background intensity, indicates the possibility of an event occurring without considering historical information. $\alpha _c \frac{{t - t_i }}{{t_i }}$ is continuous conditional intensity function in the interval $[t_i ,t_{i + 1} )$ , where $\alpha _c$ is predefined parameter and can be modified to trainable parameter in subsequent improvements, and ${\bm{w}}_c^T {\bm{h}}(t_i ))$ represents the history impact to the conditional intensity function. $f( \cdot )$is the softplus function, which is a smooth improvement of the ReLU nonlinear function. Softness parameter of softplus function is $\beta$ , using this nonlinear function makes the conditional intensity function smoother and make the new model have a better expressive ability. And the overall conditional intensity function for the whole sequence is given as follow: \begin{equation} \lambda (t\left| {\mathcal{H}_t } \right.){\rm{ = }}\sum\limits_{c = 1}^C {\lambda _c (t\left| {\mathcal{H}_t } \right.)} \end{equation} \subsection{Prediction} In point process theory, prediction is one of the most important tasks. For instance, it can be used to predict when does the patient develop which disease, and when and what events will happen in social networks. After obtaining the conditional intensity function, in view of \cite{32daley2007introduction}, we can predict the possible types and occurrence times of future events according to conditional intensity function and Eq.8: \begin{equation} \begin{array}{l} p(\left. t \right|{\cal H}_t ) = \lambda (\left. t \right|{\cal H}_t )\exp t( - \int_{t_i }^t {\lambda (\left. s \right|{\cal H}_t )} ds) \\ \hat t_{i + 1} = \int_{t_i }^\infty {t\cdot p(\left. t \right|{\cal H}_t )dt} \\ \hat c_{i + 1} = \mathop {\arg \max }\limits_c \frac{{\lambda _c (\hat t_{i + 1} |{\cal H}_{i + 1} )}}{{\lambda (\hat t_{i + 1} |{\cal H}_{i + 1} )}} \\ \end{array} \end{equation} The existence of the integral of the conditional intensity function in Eq.8 makes the prediction become difficult, although we can use the Monte Carlo sampling method \cite{33robert2013monte} to calculate it, this is still very inefficient. Due to the powerful fitting ability of neural network, we make use of neural work to predict the future event type and time-stamps, which can be shown as Eq.9: \begin{equation} \begin{array}{l} \hat t_{i + 1} = {\bm{W}}_{time} {\bm{h}}(t_i ) \\ \widehat{\bf{p}}_{i + 1} = Softmax({\bm{W}}_{type} {\bm{h}}(t_i )) \\ \hat c_{i + 1} = \mathop {\arg \max }\limits_c {\bm{\hat p}}_{i + 1} (c) \\ \end{array} \end{equation} According to \cite{32daley2007introduction}, given the sequence $s_n = \{ t_i ,c_i \} _{i = 1}^{I_n } $ , and conditional intensity function, we can get its log-likelihood expression: \begin{equation} L(s_n ) = \sum\limits_{i = 1}^{I_n } {\log } \,\lambda (\left. {t_i } \right|\mathcal{H}_i ) - \int_{t_1 }^{t_{I_n } } {\lambda (\left. t \right|\mathcal{H}_t )} dt \end{equation} Assuming there are $N$ sequences, then the model parameters can be solved by maximum log-likelihood principle: \[ \max \sum\nolimits_{n = 1}^N {L(s_n )} \] However, there is difficulty in solving $\Lambda = \int_{t_1 }^{t_{I_n } } {\lambda \left( {\left. t \right|\mathcal{H}_t } \right)} dt$ because we use universal transformer to obtain the conditional intensity function, it is hard to obtain the closed-form of $\Lambda$ , fortunately, we have two alternative methods to solve it. The first method is the Monte Carlo sampling integration method \cite{33robert2013monte}, which is shown in Eq.11: \begin{equation} \label{eq11} \hat \Lambda _{MC} = \sum\limits_{i = 2}^L {\left( {t_i - t_{i - 1} } \right)} (\frac{1} {M}\sum\limits_{m = 1}^M {\lambda (u_m )} ) \end{equation} where $u_m \sim U(t_{i - 1} ,t_i )$ , and $u_m$ is sampled from the uniform distribution in support set $[Ut_{i - 1} ,t_i ]$. $\hat \Lambda _{MC}$ calculated by this method is an unbiased estimate of $\Lambda$. The second method is numerical analysis method \cite{34stoer2013introduction}, for instance, based on the trapezoidal rule, we can get the estimate as shown in Eq.12: \begin{equation} \hat \Lambda _{NI} = \sum\limits_{i = 2}^{I_n } {\frac{{t_i - t_{i - 1} }} {2}} (\lambda (\left. {t_i } \right|\mathcal{H}_i ) + \lambda (\left. {t_{i - 1} } \right|\mathcal{H}_{i - 1} )) \end{equation} In spite of the bigger estimate error than the Monte Carlo method, $\hat \Lambda _{NI}$ is still a valid approximation of $\Lambda$ . After dealing with the solution of $\Lambda$ , we are going to define the prediction loss of time-stamp and event type, for a sequence of length $I_n$ , we will make $I_n-1$ predictions of time-stamp and event type, in other words, we will not predict the first event. Therefore, the predict loss of next time-stamp and event prediction for sequence $s_n$ is shown as Eq.13 and 14: \begin{equation} L_{time} (s_n ) = \sum\nolimits_{i = 2}^{I_n } {(t_i - \hat t_i )^2 } \end{equation} \begin{equation} L_{type} (s_n ) = \sum\nolimits_{i = 2}^{I_n } { - {\mathbf{c}}} _i^T \log (\widehat{\mathbf{p}}_i ) \end{equation} where $\bm{c}_i$ is one-hot encoding with the ground-truth event type . In summary, given the dataset including the sequences$\{ s_n \} _{n = 1}^N$ , we need to solve: \begin{equation} \min \sum\limits_{n = 1}^N { - L(s_n )} + \alpha _{type} L_{type} (s_n ) + \alpha _{time} L_{time} (s_n ) \end{equation} where $\alpha _{type}$ and $\alpha _{time}$ are hyper-parameters, which will help keep training stable. This objective function can be efficiently solved by stochastic gradient optimization algorithm, such as adaptive moment estimation (ADAM) \cite{35kingma2014adam}, and we use the default parameters of ADAM: learning rate=0.0001, betas are 0.9 and 0.999, eps = $10^{-8}$, weight\_decay = 0, for all these experiments, when we solves log-likelihood of models, we set $\alpha _{type}=0$ and $\alpha _{time}=0$ , and when performing prediction tasks, we fix $\alpha _{type}=1$ and $\alpha _{time}=0.01$ . \section{Experiments} We compare our model with three baselines on six events sequence datasets, we evaluate these models by per-event-loglikelihood (in nats), root mean square error (RMSE) and event prediction accuracy on held-out test sets, we first introduce the details of the data set and baselines, and then list our experimental results. \subsection{Datasets} In this subsection, we utilize benchmark six datasets of event sequence to conduct experiments, Table 2 introduces the characteristics of each dataset. \begin{table}[] \centering \caption{Characteristics of datasets. Each row corresponds to the description of this data set, including the total type number of events, the smallest, average, and largest sequence length.} \begin{tabular}{ccccc} \hline \multirow{2}{*}{Dataset} & \multirow{2}{*}{C} & \multicolumn{3}{c}{Sequence Length} \\ \cline{3-5} & & Min & Aver. & Max \\ \hline Synthetic & 5 & 20 & 60 & 100 \\ Retweets & 3 & 50 & 109 & 264 \\ MemeTrack & 5000 & 1 & 3 & 31 \\ MIMIC-II & 75 & 2 & 4 & 33 \\ StackOverflow & 22 & 41 & 72 & 736 \\ Financial & 2 & 829 & 2074 & 3319 \\ \hline \end{tabular} \end{table} \textbf{Synthetic} \cite{12mei2017neural}: Mei generates a set of synthetic sequences based on Hawkes process with random sampling the parameters and thinning algorithm. \textbf{Retweets} \cite{6zhao2015seismic}: This dataset contains lots of sequences of tweets, every sequence corresponds to an origin tweet (for instance, the original content some user post) and its following retweets. The time and label of user of each retweet is recorded in the sequence, and users are divided into three categories based on the number of their followers: “small”, “medium”, and “large”. \textbf{MemeTrack} \cite{36leskovec2014snap}: This dataset contains 42000 different meme posting in 5000 websites in the duration of 10 months, each sequence represents this meme from its birth to its final disappearance, and each event in the sequence corresponds to a time stamp and a website id. \textbf{StackOverflow} \cite{36leskovec2014snap}: StackOverflow is a famous programming question-answering website. StackOverflow rewards users with badges to encourage them to participate in community activities, meanwhile, the same badge can be given to the same user, this dataset includes the lots of users reward histories during two years, which are treated as sequences, and each event in sequences indicates the acquisition of badge. \textbf{Electrical Medical Records} \cite{37johnson2016mimic}: MIMIC-II dataset contains patients’ visit record to a hospital’s ICU in the course of seven years. Each patient’s record is treated as a sequence, and each event contains the corresponding time-stamp and diagnosis. \textbf{Financial Transactions} \cite{11du2016recurrent}: This financial dataset contains large number of short-term transaction records of a stock in one day. The operation of each transaction is recorded as the event, and this dataset contains several long sequences, which only have two kinds of events: “buy” and “sell”, and the unit of the time-stamp is millisecond. \subsection{Baselines} \textbf{RMTPP} \cite{11du2016recurrent}: Du et al. come up with a recurrent network, which can model the event types and time-stamp in the sequence by embedding history to the vector. \textbf{NHP} \cite{12mei2017neural}: Mei and Eisner present the neural Hawkes process based on the continuous-time LSTM, which has decay property of history events impact. \textbf{THP} \cite{21DBLP:conf/icml/ZuoJLZZ20}: On the foundation of existing achievement of transformer, Zuo et al. propose the transformer Hawkes process, which achieves state-of-the-art performance. We get the following experimental results based on the model and the hyper-parameter they provide. For NHP model, we also use ADAM optimizer with same hyper-parameter i.e., we set learning rate=0.0001, betas are 0.9 and 0.999, eps =$10^{-8}$ , weight\_decay = 0, and the number of hidden nodes of the continuous-time LSTM is 64, for Synthetic, Retweets and MemeTrack dataset, we set batch size to 16. The hyper-parameter configurations of THP and UTHP are given in section 4.5. \subsection{Experimental results and comparison} In this part, we are going to compare the performance of UTHP and baselines on datasets of multiple event sequences. First, we utilize loglike (per-event-loglikelihood) as the measurement of models’ performance on Synthetic, Retweets and MemeTrack datasets, which is shown in Table 3: \begin{table}[] \centering \caption{The loglike on three dataset, from left to right, each column is a different model, and each row is a different dataset} \begin{tabular}{ccccc} \hline Datasets & RMTPP & NHP & THP & UTHP \\ \hline Synthetic & \textbackslash{} & -1.33 & \textbf{0.834} & 0.796 \\ Retweets & -5.99 & -5.06 & \textbf{-4.69} & -4.75 \\ MemeTrack & -6.04 & -6.23 &\textbf{ 0.68} & 0.31 \\ \hline \end{tabular} \end{table} From Table 3, we can see that transformer models achieve obvious improvement than previous one, and although our UTHP model does not reach the state-of-the-art level, it still achieves second best. After this, we compare the performance of different models on complex datasets, including StackOverflow, MIMIC-II and Financial datasets. Because of the importance of event and time prediction of point process, while we compare the performance of models on these datasets, the multiple metric criteria will be adopted, involving per-event-log-likelihood, the predict accuracy for event and RMSE of time-stamp prediction. For transformer based model, we utilize Eq. 9 to make predictions, and for RNN based model, Eq. 10 is used. Table 4, Table 5 and Table 6 summarize the experimental results on these datasets. \begin{table}[] \centering \caption{Different models’ performance on StackOverflow dataset, each row is the different metric criteria, including accuracy, RMSE and loglike (per-event-loglikelihood)} \begin{tabular}{ccccc} \hline StackOverflow & RMTPP & NHP & THP & UTHP \\ \hline Accuracy & 45.9 & 46.3 & 46.8 & \textbf{46.9} \\ RMSE(d) & 9.78 & 9.83 & 4.99 & \textbf{4.42 } \\ Loglike & -2.60 & -2.55 & -0.56 & \textbf{-0.55 }\\ \hline \end{tabular} \end{table} \begin{table}[] \centering \caption{Different models’ performance on MIMIC-II dataset.} \begin{tabular}{ccccc} \hline MIMIC-II & RMTPP & NHP & THP & UTHP \\ \hline Accuracy & 81.2 & 83.2 & 83.2 & \textbf{84.4} \\ RMSE(d) & 6.12 & 6.13 & 0.86 & \textbf{0.85} \\ Loglike & -1.35 & -1.38 & \textbf{-0.14} & -0.18 \\ \hline \end{tabular} \end{table} \begin{table}[] \centering \caption{Different models’ performance on Financial dataset.} \begin{tabular}{ccccc} \hline Financial & RMTPP & NHP & THP & UTHP \\ \hline Accuracy & 61.95 & 62.20 & 62.23 & \textbf{62.52} \\ RMSE(s) & 1.56 & 1.56 & 0.02575 & \textbf{0.02574} \\ Loglike & -3.89 & -3.60 & -1.39 & \textbf{-1.16} \\ \hline \end{tabular} \end{table} From these results, we can see that our proposed UTHP model achieves obvious improvement than the baselines among the different scenarios, different data sets have markedly different characteristics, for instance, the number of classes of MIMIC-II dataset is 75, and the average length is only 4, while the number of classes of Financial dataset is only 2, and the average length is 2074. In all of these datasets, our model improves relatively significantly. This suggests that UTHP can better model complex asynchronous event sequences and learn long-term and short-term event dependencies than existing baseline models. \begin{figure}[!htbp] \label{fig3} \centering \subfigure[MIMIC-II]{ \includegraphics[width=4.5cm]{mic_acc.pdf} } \quad \subfigure[StackOverflow]{ \includegraphics[width=4.5cm]{so_acc.pdf} } \quad \subfigure[Fianancial]{ \includegraphics[width=4.5cm]{fi_acc.pdf} } \caption{Prediction accuracies of RMTPP, NHP, THP and UTHP. Based on the five times train-dev-test partition, five experiments are performed on each dataset, the mean and standard deviations of different models are depicted.} \end{figure} \begin{figure}[!htbp] \centering \subfigure[MIMIC-II]{ \includegraphics[width=4.5cm]{mic_rsme.pdf} } \quad \subfigure[StackOverflow]{ \includegraphics[width=4.5cm]{so_rmse.pdf} } \quad \subfigure[Fianancial]{ \includegraphics[width=4.5cm]{fi_rmse.pdf} } \subfigure[Zoom in of RMSE of THP and UTHP on the datasets]{ \includegraphics[width=7cm]{rmsestd.pdf} } \caption{The mean and standard deviation for different models obtained from the five experiments in term of RMSE metric for RMTPP, NHP, THP and UTHP.} \end{figure} Fig. 5 and Fig.6 visualizes the accuracies of different models and RMSE of baselines and UHP, due to the dispersion of the data, the error bars are wide. We can find out that the results of UTHP better than the other baselines. \subsection{Ablation study} In this subsection, we are going to discuss the impact to the performance of three significance part in models, the postprocessing part, CNN module in the position-wise-feed-forward part and ACT mechanism, we demonstrate experimentally how the presence of these three parts affects the performance of the model. \subsubsection{Ablation study of the postprocessing part} As we mentioned in subsection 3.1, the introduction of the additional postprocessing part will have an impact on the transformer-based models, and the impact on the model varies with the dataset. In this subsection, we will demonstrate the impact of the introduction of RNN. Previous experimental results prove that RNN (including LSTM and GRU) can successfully capture the short-term dependencies in the sequence, but not for long-term dependencies. Thus, we can assume that if we introduce the RNN in the additional postprocessing part to the transformer-based model, it will have better performance to capture the dependencies between the events on the dataset with short-term characteristic, and have relatively poor performance of dependencies fitting on the dataset with long-term characteristic. To validate whether the facts are consistent with our assumptions, validation experiments are carried out on the dataset with long-term property, i.e., MIMIC-II, and dataset with short-term property, i.e., Financial dataset, and the event prediction accuracies are used to measure how well the model fits the dependencies between events. The experimental results are shown as Table 7 and Fig. 7: \begin{table}[] \centering \caption{Consider that whether there is an additional RNN layer in the postprocessing part, UTHP and THP’s event prediction accuracy rates on MIMIC-II dataset and financial dataset.} \begin{tabular}{ccccc} \hline & \multicolumn{2}{c}{MIMIC-II} & \multicolumn{2}{c}{Financial} \\ \hline & With RNN & Without RNN & With RNN & Without RNN \\ \hline \begin{tabular}[c]{@{}c@{}}Accuracy of THP\end{tabular} & 81.44 & \textbf{83.18} &\textbf{ 62.23} & 60.22 \\ \begin{tabular}[c]{@{}c@{}}Accuracy of UTHP\end{tabular} & 83.34 & \textbf{84.43 } & \textbf{62.52 } & 62.04 \\ \hline \end{tabular} \end{table} From the experimental results, we can discover that for transformer-based model, addition RNN layer in the postprocessing part has a negative effect on the experimental results of MIMIC-II dataset, and has a positive impact on the financial dataset. These facts verify that our hypothesis, RNN do enhance the fitting ability to events short-term dependencies, and weaken the fitting ability to the events long-term dependencies. \begin{figure}[!htbp] \label{fig3} \centering \subfigure[MIMIC-II]{ \includegraphics[width=4.5cm]{rnnmimic.pdf} } \quad \subfigure[Financial]{ \includegraphics[width=4.5cm]{rnnFinancial.pdf} } \quad \caption{Visualization of ablation experimental results with and without an additional RNN layer in the postprocessing part.} \end{figure} In addition, UTHP model demonstrates its robustness without RNN on the financial dataset. The reason is that our model already has a recursive structure, which helps it better model short-term data. This also reflects the value of UTHP model we proposed. \subsubsection{Ablation study of CNN module in the position-wise-feed-forward part} In general, CNN module will enhance the local perception ability of the model, which is the reason why we add CNN module into the position-wise-feed-forward part. In order to judge whether the introduction of the CNN module is effective, we conduct the comparison experiments, compare the UTHP based on ACT algorithm with CNN and without CNN module in position-wise-feed-forward part on StackOverflow, MIMIC-II and Financial dataset. The experiment results are shown as Table 8 and Fig. 8. \begin{table}[] \centering \caption{Model performance comparisons of UTHP based on ACT algorithm with CNN and without CNN module in position-wise-feed-forward part} \begin{tabular}{cccc} \hline & UTHP & With CNN & Without CNN \\ \hline \multirow{3}{*}{Accuracy} & StackOverflow & \textbf{46.87} & 46.76 \\ & MIMIC-II & \textbf{84.43} & 83.83 \\ & Financial & 62.52 & \textbf{62.52} \\ \hline \end{tabular} \end{table} \begin{figure}[!htbp] \centering \includegraphics[scale=0.3]{cn.pdf} \caption{Accuracy comparison of UTHP based on ACT algorithm with CNN and without CNN module in position-wise-feed-forward part.} \label{fig3} \end{figure} \subsubsection{Ablation study of ACT mechanism} From the above experimental results, we can find out that the introduction of CNN module in position-wise-feed-forward part obviously raises the event prediction accuracy. This fact indicates that CNN module enhance the ability to model connections between events of UTHP through its local perception characteristics, which indicates that the introduction of CNN module in position-wise-feed-forward part is effective. In subsection 3.1, we introduce the reasons for adding the ACT mechanism to the model, ACT mechanism will dynamically regulate the calculation of input in the transformer, make the model use more computing resources to where it is needed more. The concept of this effect is similar to and complementary to the self-attention mechanism, and theoretically makes the model perform better. And in order to investigate the effect of the ACT mechanism on UTHP, we conducted a series of comparative experiments, we compare pure UTHP under different recursive iteration times (the corresponding algorithm is Algorithm 1) and UTHP with ACT mechanism (the corresponding algorithm is Algorithm 2 and maximum number of iterations max\_n=2). These results are summarized in Table 9: \begin{table}[] \centering \caption{Model performance comparisons of UTHP based on ACT mechanism and UTHP with pure recurrence} \begin{tabular}{ccccccc} \hline & Times of iteration & ACT & 1 & 2 & 3 & 4 \\\hline \multirow{3}{*}{StackOverflow} & Accuracy & \textbf{46.87} & 46.67 & 46.70 & 46.70 & 46.72 \\ & RMSE & \textbf{4.42} & 4.52 & 4.47 & 4.47 & 4.47 \\ & Loglike & \textbf{-0.55} & -0.60 & -0.58 & -0.58 & -0.57 \\ \multirow{3}{*}{MIMIC-II} & Accuracy & \textbf{84.43} & 82.34 & 82.63 & 83.05 & 81.95 \\ & RMSE & \textbf{0.85} & 0.90 & 0.87 & 0.89 & 0.85 \\ & Loglike & -0.18 & -0.21 & -0.19 & -0.18 & \textbf{-0.17} \\ \multirow{3}{*}{Financial} & Accuracy & \textbf{62.52} & 62.52 & 62.45 & 62.43 & 62.29 \\ & RMSE & 0.02574 & 0.02574 & 0.02572 & \textbf{0.02571} & 0.02572 \\ & Loglike & -1.16 & -1.24 & \textbf{-0.76} & -0.80 & -0.77 \\ \hline \end{tabular} \end{table} For the pure recurrence of UTHP, we considered four different iteration times as the first row in Table 9, and when the number of iterations is once, it indicates that hidden representation of sequences will directly output the model, rather than recurrently iterate in the model, from the results we can find out that UTHP with ACT mechanism performs than pure recurrence UTHP overall. Especially in terms of the accuracies of event prediction, UTHP with ACT mechanism are all better than UTHP with pure recurrence. For a more intuitive comparison, we visualize these experimental results and error bars, as shown in Fig. 9, Fig. 10, and Fig. 11. \begin{figure}[!htbp] \label{fig3} \centering \subfigure[Accuracy]{ \includegraphics[width=4.5cm]{soacc.pdf} } \quad \subfigure[RMSE]{ \includegraphics[width=4.5cm]{sormse.pdf} } \quad \subfigure[Loglike]{ \includegraphics[width=4.5cm]{solog.pdf} } \caption{Model performance curves of UTHP with ACT mechanism and pure UTHP on StackOverflow dataset.} \end{figure} \begin{figure}[!htbp] \label{fig3} \centering \subfigure[Accuracy]{ \includegraphics[width=4.5cm]{miacc.pdf} } \quad \subfigure[RMSE]{ \includegraphics[width=4.5cm]{mirmse.pdf} } \quad \subfigure[Loglike]{ \includegraphics[width=4.5cm]{milog.pdf} } \caption{Model performance curves of UTHP with ACT mechanism and pure UTHP on MIMIC-II dataset.} \end{figure} \begin{figure}[!htbp] \label{fig3} \centering \subfigure[Accuracy]{ \includegraphics[width=4.5cm]{bookacc.pdf} } \quad \subfigure[RMSE]{ \includegraphics[width=4.5cm]{bookrmse.pdf} } \quad \subfigure[Loglike]{ \includegraphics[width=4.5cm]{booklog.pdf} } \caption{Model performance curves of UTHP with ACT mechanism and pure UTHP on Financial dataset.} \end{figure} From these figures, we can see that compared to the error bar, UTHP with ACT mechanism has a clear gap with pure UTHP when it performs well, such as the accuracy, RMSE and Loglike curves on StackOverflow dataset, and the accuracy curves on MIMIC-II dataset. And comparing with the standard deviation, when pure UTHP results are better than UTHP with mechanism, the difference is not so obvious. This further verifies that the introduction of the ACT mechanism will improve the overall performance of UTHP. In addition, with the increasing of iteration times, the Loglike on these datasets of pure UTHP are also increasing. The fact represents that the increment of iteration items enhance the modeling ability of UTHP. \subsection{Fewer model parameters of UTHP} Because of the recurrence structure of UTHP, there is only one encoding layer in our model, while THP utilize the stacking of multiple encoding layer, in other words, UTHP model share the parameters in the encoding layer. By this way, we find that our proposed architectures improve model performance, and also reduce model parameters. For instance, in subsection 4.3, on each dataset, UTHP and THP adopt the similar hyper-parameters, which is shown as Table 10 and Table 11, the only difference is that UTHP has only one encoding layer, and there is a CNN module in the position-wise-feed-forward part of encoding layer. \begin{table}[] \centering \caption{Hyperparameter configurations of THP.} \begin{tabular}{ccccccc}\hline Dataset & Synthetic & Retweets & MemeTrack & Financial & MIMIC-II & \begin{tabular}[c]{@{}c@{}}StackOverflow\end{tabular} \\ \hline $D$ & 64 & 64 & 64 & 128 & 64 & 512 \\ $D_H$ & 256 & 256 & 256 & 2048 & 256 & 1024 \\ $D_{\rm{RNN}}$ & 128 & 128 & 128 & 128 & 0 & 128 \\ $D_Q=D_V$ & 16 & 16 & 16 & 64 & 16 & 512 \\ Heads of attention & 3 & 3 & 3 & 6 & 3 & 4 \\ Layers of transformer & 2 & 2 & 2 & 2 & 2 & 2 \\ Dropout & 0.1 & 0.1 & 0.1 & 0.1 & 0.1 & 0.1 \\ \hline \end{tabular} \end{table} \begin{table}[] \centering \caption{Hyperparameter configurations of UTHP.} \begin{tabular}{ccccccc}\hline Dataset & Synthetic & Retweets & MemeTrack & Financial & MIMIC-II & \begin{tabular}[c]{@{}c@{}}StackOverflow\end{tabular} \\\hline $D$ & 64 & 64 & 64 & 128 & 64 & 512 \\ $D_H$ & 256 & 256 & 256 & 2048 & 256 & 1024 \\ $D_{\rm{RNN}}$ & 128 & 128 & 128 & 128 & 0 & 128 \\ $D_Q=D_V$ & 16 & 16 & 16 & 64 & 16 & 512 \\ Heads of attention & 3 & 3 & 3 & 6 & 3 & 4 \\ Max\_n & 2 & 2 & 2 & 2 & 2 & 2 \\ Dropout & 0.1 & 0.1 & 0.1 & 0.1 & 0.1 & 0.1 \\ Size of convolution kernel & 3 & 3 & 3 & 3 & 3 & 3 \\ Stride of convolution kernel & 2 & 2 & 2 & 2 & 2 & 2 \\ Padding & 0 & 0 & 0 & 0 & 0 & 0 \\ Stride of the pooling module & 2 & 2 & 2 & 2 & 2 & 2 \\ Size of the pooling module & 2 & 2 & 2 & 2 & 2 & 2\\ \hline \end{tabular} \end{table} \begin{table}[] \centering \caption{The numbers of parameters of the THP and UTHP on different datasets.} \begin{tabular}{ccc}\hline Number of parameters & THP & UTHP \\\hline Synthetic & 245765 & 129494 \\ Retweet & 137795 & 46356 \\ MemeTrack & 1102216 & 1010777 \\ MIMIC-II & 151691 & 60252 \\ StackOverflow & 21022742 & 5281319 \\ Financial & 4343298 & 724627 \\\hline \end{tabular} \end{table} As we can see from the Table 12, although we introduce a CNN module in position-wise-feed-forward part which increases the additional parameters in UTHP, it still has less parameter than THP. The parameter number of the THP’s parameter is approximately 6 to 1.1 times of the UTHP’s one. The fewer number of event types in the dataset, the fewer parameters for UTHP compared to THP. Combined with the experimental results in subsection 4.3, our model uses fewer parameters to achieve better performance, which reflects the improvement of our model. \section{Conclusions and future works} In this paper, we come up with UTHP, a new neural point process model to analyze the asynchronous event sequence. UTHP combines the self-attention mechanism in transformer and the recurrence mechanism in RNN, this operation allows our model to organically integrate the advantages of RNN and transformer, moreover, in order to make UTHP to adaptively determine when to stop refining processes of hidden variables, we introduce the ACT mechanism to UTHP. Experimental results verify that our model performs better than the baselines overall with fewer model parameters, and we also discuss the impact of the existence of the additional RNN layer and the ACT mechanism in the ablation study. \section{Acknowledgment} Thanks for Hong-yuan Mei and Si-miao Zuo for their generous help in my research state, their help greatly improved our research.
{'timestamp': '2021-12-30T02:24:12', 'yymm': '2112', 'arxiv_id': '2112.14479', 'language': 'en', 'url': 'https://arxiv.org/abs/2112.14479'}
arxiv
\subsection{Terminology} In this section, we explain the different stages a vulnerability goes through in its lifecycle. Then, we define our threat levels for vulnerabilities using the different stages that a vulnerability goes through during its lifecycle. \subsection{Vulnerability Lifecycle} \label{sec:background2} A software \emph{vulnerability} is a weakness that allows unauthorized actions and/or access to be performed. These actions are typically used to break through the system and violate its security policies~\cite{liu2012software,shirey2000internet}. A \emph{vulnerability threat} is a potential danger to exploit a vulnerability in order to breach security and cause possible harm~\cite{shirey2000internet}. As shown in Figure~\ref{vuln_timeline}, typically, and with emphasis on vulnerabilities in the Node Package Manager ({npm}\xspace ecosystem), a vulnerability goes through a number of different stages~\cite{Reporting96}. \begin{itemize} \item \textbf{Introduction.} This is when the software vulnerability is first introduced into the code. At this stage, no one really knows about its existence, assuming that the introduction is not malicious. Hence, the potential threat of the vulnerability is quite low. \item \textbf{Discovery (report).} When a vulnerability is discovered, it must be reported to the npm security team. The npm team investigates to ensure that the reported vulnerability is legitimate. At this stage, only the security team and the reporter of the vulnerability know about its existence. The potential threat at this stage is still low. \item \textbf{Notification.} Once the reported vulnerability is confirmed, the security team triages the vulnerability and notifies the vulnerable package maintainers. At this stage, only the reporter, npm team, and package maintainers know about the vulnerability, hence its potential threat to be exploited remains low. \item \textbf{Publication without a known fix.} Once the package maintainers are notified, they have 45 days before npm publishes the vulnerability publicly. Alongside with publishing the vulnerability, the npm team may also publish a proof-of-concept showing how the vulnerability can be exploited. At this stage, the vulnerability is known publicly and its potential threat is high. \item \textbf{Publication with a fix.} Another (and more common) way that a vulnerability can be published is when a fix is provided by the package maintainers. If a fix is provided (before 45 days), then npm publishes the vulnerability along with the version of the package that fixes the vulnerability. At this stage, the potential threat is not as high as when a no fix is provided, but now the onus is on the application maintainers to make sure that they pull in the latest fixes, otherwise they are risking being exploited. \end{itemize} Typically, the vulnerability publish date is after the report and notification dates. It is important to note that although the aforementioned stages are generally sequential, we do see cases where {it is not}. For example, in some cases we see vulnerabilities with a fix date that precedes its reporting or publication date. The race between developers and attackers starts as soon as a vulnerability is discovered. We use the different stages of a vulnerability to examine the potential threat of software vulnerabilities next. \subsection{Threat Levels} \label{sec:ex} As shown earlier, the different stages that a vulnerability goes through significantly impact its threat. Hence, our study is based on the idea that vulnerabilities should be examined while taking their threat into consideration as the \textit{vulnerability timing} makes them hard to exploit. We use the various stages to ground our argument and define three specific threat levels: \begin{enumerate} \item \textbf{Low threat - before discovery (report).} Since very little (or nothing at all) is known about a vulnerability before it is found, i.e., vulnerabilities are hidden in the applications, we believe that its potential threats and chances of being exploited are very low. Hence, we classify all vulnerabilities at this stage as having \emph{low threat}. \item \textbf{Medium threat - after discovery \& before publication:} Once a vulnerability has been discovered, there is potential that others may also know about it. Moreover, since at this stage the public is still not aware of the vulnerability, the vulnerability might be exploited by people who know about it somehow and have the capability to exploit it. Hence, we classify vulnerabilities at this stage as having \emph{medium threat}. \item \textbf{High threat - after publication:} After publication this is the time when the chance of exploitability is highest. Of course, if a fix is provided, then the risk is lower, however, if the application does not update then it still faces a major risk of being exploited. If a fix is not provided, then all applications are at a very high risk of being exploited, hence, we classify all vulnerabilities at this stage as having \emph{high threat}. \end{enumerate} \begin{figure}[tb!] \centering \includegraphics[width=1\linewidth]{images/vuln_timeline_new} \caption[]{Classification of threats over the vulnerability lifecycle.} \label{vuln_timeline} \end{figure} \subsection{Data Collection} \label{subsec:data} Our study examines vulnerable dependencies in Node.js applications. We chose to focus on Javascript due to its wide popularity amongst the development community~\cite{StackOve70:online}. \\ \noindent\textbf{Packages vs. Applications.} The software community classifies JavaScript projects into two categories: \textit{1) packages}, also referred to as libraries, which are included in other applications using dependency management tools to help facilitate and speed up development. Packages are referred to as "dependencies" of an application. \textit{2) applications} are standalone software projects, which are distinct from libraries, where they are not distributed via a package manager and are typically applications for clients and end users rather than components to build upon. As mentioned before, the Node.js applications mainly state the packages they depend on (i.e., dependencies) in a file called package.json. To perform our study, we leverage two datasets: (1) Node.js applications that use {npm} to manage their dependencies, and (2) Security vulnerabilities that affect npm packages. To do so, we \textbf{(i)} obtain the Node.js applications from GitHub, \textbf{(ii)} extract their dependencies, and \textbf{(iii)} obtain the security vulnerabilities for npm packages from {npm} advisories~\cite{npmadvisories}. The dataset collection took place during May and June of 2019.\\ \noindent\textbf{(i) Applications Dataset.} To analyse a large number of open source JavaScript applications that depend on npm packages and obtain insights on their security vulnerabilities, we mine the GHTorrent dataset~\cite{GHtorrent} and extract information about all Node.js applications hosted on GitHub. The GHTorrent dataset contains a total of 7,863,361 JavaScript projects hosted on GitHub, of which 2,289,130 use npm as their package management platform (i.e., these projects contain a file called package.json). Moreover, since both Node.js \textit{packages} and \textit{applications} can use GitHub as their development repository, and our applications dataset should only contain Node.js \emph{applications}, we filter out the GitHub projects that are actually npm \emph{packages} by checking their GitHub URL on the {{npm}} registry. The main reason that we focused on applications and not packages is because packages become exploitable only when used and deployed in an application, i.e., packages do not reside on their own in production, they should be part of applications that make use of them. This filtering excludes 328,343 projects from our list of GitHub projects as they are identified as packages and not applications As shown in previous studies~\cite{kalliamvakou2014promises,kula2018developers}, some projects on GitHub are immature, hence, to make this study more reliable we refined the dataset using additional filtering criteria to eliminate such immature projects. In particular, we gather applications that satisfy all the following criteria: \begin{itemize} \item Non-forked applications, as we do not want to have duplicated project history to bias our analysis. \item Applications that depend upon more than two dependencies. \item Applications that have at least 100 commits by more than two contributors, which indicates a minimal level of commit activity. \item Applications that have had their creation date (first commit) before January 1st 2017. Since vulnerabilities take on median 3 years to be discovered~\cite{decan2018impact}, applications in our dataset need to have a development history long enough to have had a chance for their vulnerabilities to be discovered. \item Applications that have had their latest commit after January 1st 2017, as we want to analyze applications that had some level of development in the last 3 years. \end{itemize} After applying these refinement criteria, we end up with 6,673 Node.js applications that make use of npm packages. Table~\ref{statsApplications} shows descriptive statistics on the selected Node.js applications in our dataset. Overall, the applications in our dataset have a rich development history (a median of 213 commits made by 4 developers and 1,657 days of development lifespan) and make ample use of external dependencies (a median of 11 dependencies).\\ \noindent\textbf{(ii) Application Dependencies.} After obtaining the applications dataset, we want to extract the history of dependency changes of all applications. This is necessary to identify the exact dependency versions that would be installed by the application at any specific point-in-time. As mentioned in Section~\ref{sec:dependency}, Node.js applications specify their dependencies in the package.json file, which contains the dependency list, containing the dependent upon packages and their respective version constraints. Hence, we extract all changes that touched the package.json file and associate each commit hash and commit date to their respective package.json dependency list, creating a history of dependency changes for all applications. Note that these dependencies are not yet resolved, that is, we only have the version constraints (not the versions) for the dependencies of each application. \\ \begin{table}[tb!] \centering \caption{Statistics of the 6,673 studied Node.js applications. } \label{statsApplications} \begin{tabular}{l|r|r|r|r} \toprule \textbf{Metric} & \textbf{Min.} & \textbf{Median($\bar{x}$)} & \textbf{Mean($\mu$)} & \textbf{Max.} \\ \midrule \textbf{Commits} & 100 & 213 & 384.60 & 53,872 \\ \textbf{Dependencies} & 3 & 11 & 14.93 & 114 \\ \textbf{Developers} & 3 & 4 & 5.33 & 52 \\ \textbf{Lifespan (in days)} & 151 & 1,657 & 1,730.07 & 3,575 \\ \bottomrule \end{tabular} \end{table} \noindent\textbf{(iii) NPM Advisories Dataset.} To identify Node.js applications that depend on vulnerable packages, we need to collect information on npm vulnerable packages. We resort to the \textit{NPM advisories} registry to obtain the required information about all npm vulnerable packages~\cite{npmadvisories}. The npm advisories dataset is the official registry for npm vulnerability reports, which contains a number of JavaScript vulnerabilities, specific to the Node.js-platform packages. This dataset provides several kinds of information about vulnerable packages relevant to our study. Each report has the affected package name, the package versions affected by the vulnerability, and the versions in which the vulnerabiliy was fixed (safe versions). The report also contains both the vulnerability discovered (reported) time and published time, which we use in our approach for identifying and classifying vulnerabilities (Section~\ref{subsec:scanning}). Note that a vulnerable package could be affected by several vulnerabilities (i.e., a vulnerable package appears with different vulnerability reports due to different vulnerability types). Our initial dataset contains 654 security reports that cover 601 vulnerable packages. Following the criteria filtration process applied by Decan et al.~\cite{decan2018impact}, we removed 12 vulnerable packages of the type "Malicious Package", because they do not actually introduce vulnerable code. These vulnerabilities are packages with names close to popular packages (a.k.a. typo-squatting) in an attempt to deceive users at installing harmful packages. The 12 vulnerable packages account for 12 vulnerability reports. At the end of this filtering process, we are left with 642 security vulnerabilities reports affecting 589 distinct vulnerable packages. These packages have combined 26,462 distinct package versions of which 13,868 are affected by vulnerabilities from our report. Table~\ref{dataset} shows the summary statistics for vulnerability reports on npm packages. \begin{table}[tb!] \centering \caption{Descriptive statistics on the npm advisories dataset.} \label{dataset} \begin{tabular}{l|r} \toprule Vulnerability reports & 642 \\ Vulnerable packages & 589 \\ Versions of vulnerable packages & 26,462 \\ Affected versions by vulnerability & 13,868 \\ \bottomrule \end{tabular}% \vspace{-2mm} \end{table} \begin{figure*}[tb!] \centering \setlength{\abovecaptionskip}{5pt} \includegraphics[width=0.7\linewidth]{images/approach.pdf} \caption[]{Approach for identifying and classifying vulnerable dependencies in Node.js applications.} \label{classifyApproach} \end{figure*} \subsection{Identifying and Classifying Vulnerable Dependencies in Node.js Applications} \label{subsec:scanning} To classify the threat level of vulnerable dependencies at a specific point in the development history of a Node.js application, which we refer to as the \textit{analyzed snapshot time}, we leverage 3-step approach. Figure~\ref{classifyApproach} provides an overview of our approach, which we detail below: \noindent {\textbf{Step 1. Extract dependencies and resolve versions.}} The goal of this step is to extract applications dependencies and find the actual dependency version installed at the analyzed snapshot time. For each application, we extract the dependency list (with the versioning constraints) at that snapshot time from the history of dependency changes. After that, to find the actual version of each dependency at the analyzed snapshot, we utilize the \textit{semver} tool~\cite{semvernp91} that is used by npm to find the latest version that satisfies the versioning constraint, with an additional restriction that the satisfying version should have been released (in the npm registry) before the application snapshot time. For example, an application can specify a versioning constraint (``P:$>$1.0.0'') at the snapshot May 2016. Hence, the actual installed version is the latest version that is greater than 1.0.0 and also has been released in the npm registry before May 2016. This step allows us to find the installed version of the dependency at the analyzed snapshot time. \\ \noindent {\textbf{Step 2. Identify vulnerable dependency versions.}} After determining the resolved (and presumably installed) version at the analyzed snapshot time, we check whether the resolved version is vulnerably or not. To do so, we check the advisories dataset for the versions that were available at that snapshot point. If the resolved version is covered by the advisories dataset, we label it as a vulnerable dependency version. We skip the whole next step if the dependency version has not been mentioned in any advisory, i.e., the dependency version is not vulnerable. \\ \noindent {\textbf{Step 3. Identify threat levels of vulnerable versions.}} Once we identify the vulnerable dependency versions at the analyzed snapshot time, we classify each vulnerable dependency version using one of the threat levels we defined earlier (in Section~\ref{sec:ex}), i.e., we find out the threat level of each vulnerable dependency version. To do so, for each vulnerable version, we compare its vulnerability \textit{discovery (report)} and \textit{publication} time to the analyzed snapshot time. As we stated previously (in Section~\ref{sec:ex}), if the vulnerability publication time of the vulnerable dependency version is before the application's snapshot time then we mark the vulnerability as high threat vulnerability. If the vulnerability of the dependency was not published but only discovered (reported) before the application's snapshot time, then we mark it as medium. And finally, if it was neither published nor discovered (reported) before the analyzed snapshot time (i.e., no one knows about it at that snapshot time), then we mark it as low. In cases where more than one vulnerability affects the vulnerable dependency version, we resort to a weakest link approach (i.e., we label the vulnerable dependency version with the highest threat level). For example, if we find that the vulnerable version of the dependency is affected by two vulnerabilities -one having low threat and another as high threat, we label the vulnerable dependency version as high at that snapshot time. \subsection{Replication Package} To facilitate verification and advancement of research in the field, a replication package comprising the data used in our study along with the analyses used in our study is publicly available\footnote{http://doi.org/10.5281/zenodo.3837397}. \subsection{Security Migration Cost} \label{sec:cost} Developers of Node.js applications may use dynamic versioning constraints if they want to install the latest version of a dependency, allowing them to get the latest updates for security fixes of the package. In fact, npm adopts a semantic version scheme~\cite{semvernp91}, where package maintainers are encouraged to specify the extent of their updates in three different levels: 1) patch release, which indicates backward compatible bug fixes, 2) minor release, which indicates backwards compatible new features and 3) major release, which informs developers of backwards incompatible changes in the package release. While our study (RQ$_3$) showed that 90.76\% of high-threat vulnerabilities have a safe version available for application maintainers (at the snapshot 100\%), we manually inspected the fixed versions and the applications version constraints and found that in 43.07\% of the cases, the fix is only available in another major release. For instance, an application depends on P:1.0.0, and the fix patch was only released for a major version 2.0.0 and onwards. Hence, to benefit from a fix patch in such a case, developers are required to upgrade their dependencies at the risk of breaking their own code, since a new major release has breaking changes compared to the version the application depends on. This imposes significant migration costs, especially for large projects that depend on dozens of packages. Furthermore, this shows that using dynamic versioning at the level of patch and minor releases (as recommended by npm) does not completely prevent high threat level vulnerabilities for affecting Node.js applications. \vspace{0.1in} \subsection{Implications} \label{sec:imp} \textbf{Implications to researchers.} Several studies have addressed the problem of vulnerabilities in software libraries~\cite{decan2018impact,zapata2018towards}. Our study, however, complements previous studies by analyzing the risks of vulnerable dependencies in the Node.js applications, aggregating the vulnerability lifecycle through the threat level metric. Researchers can use our empirical evidence to better understand the risks Node.js applications face due to their high reliance on dependencies. Our results show that most vulnerable dependencies found in a application snapshot have a low risk of being exploited when considering the lifecycle of vulnerabilities and how applications update their dependencies. Our results also show that the time element is crucial to understanding the threat of vulnerable dependencies in applications. Hence, a major implication of our study for researchers is that not all vulnerabilities are equal, and should not be treated and analyzed as such. Research needs to account for more than the existence of vulnerabilities to draw more meaningful analyses regarding software security, particularly for applications in software ecosystems where the level of dependency continues to increase. Research can use our threat-level approach to provide a more refined picture when reporting the impact of vulnerabilities. Researchers can also reuse our approach to help them identify and classify vulnerable dependencies in the applications (in Section~\ref{subsec:scanning}). Furthermore, more studies across ecosystems are necessary to get a broader perspective on the threat level of vulnerability dependencies. npm is one of the largest ecosystems and since applications depend on an increasingly high number of packages~\cite{decan2018empirical}, Node.js applications may be subjected to higher risk of vulnerable dependencies. Further investigation could unveil if this pattern holds in other ecosystems. \\ \noindent \textbf{Implications to practitioners.} Our results revealed important takeaways for software practitioners. First, vulnerable dependencies are common, 67.93\% of the studied Node.js applications had at least one vulnerable dependency at the last studied snapshot. Practitioners need to be in constant alert to update their dependencies and tools that increase awareness of vulnerabilities, such as Dependabot~\cite{Dependab26:online} and \texttt{npm audit}~\cite{npmaudit59:online} are evermore crucial for the safety of software applications, especially because they warn developers as soon as the vulnerability becomes of a high threat level. Second, practitioners also need to account for the threat level of a vulnerability to have a more correct understanding of software vulnerabilities in software ecosystems. Our method of analysis can also be used by developers to identify packages that more often raise the threat level in their applications. Also, while vulnerabilities are widespread in open-source packages in the npm, in most cases package maintainers issue a fix patch for their vulnerability as soon as it becomes public, which is crucial to mitigate the chances of having a vulnerability exploited and cause potential harm to end-users and application maintainers. Third, our study showed that developers are in need of more tools that go beyond simply warning them of a published vulnerability. For example, they need tools to help them understand: 1) the costs of migrating to a safer version and whether it is possible to fix a vulnerability without breaking their code, 2) the frequency in which certain dependencies have become vulnerable in the past, in order to grab the threats of depending on such packages and better plan their project maintenance, 3) history of all vulnerable dependencies of their application in order to understand the frequency and the duration in which their application became at the risk of a high threat vulnerability in the past. Packages that do not update their code to address reported vulnerabilities incur in a high risk for applications that use them and should be avoided by critical applications. \section{Introduction} \label{sec:introduction} \input{introduction} \begin{figure*}[!t] \centering \end{figure*} \section{Classifying Vulnerabilities} \label{sec:background} \input{background} \section{NPM Dependency Management} \label{sec:dependency} \input{dependency} \section{Case Study Design} \label{sec:case_study_design} \input{design} \section{Case Study Results} \label{sec:results} \input{results} \section{Discussion} \label{sec:discussion} \input{discussion} \section{Related Work} \label{sec:related_work} \input{related_work} \section{Threats to Validity} \label{sec:threats} \input{threats} \section{Conclusion and Future Work} \label{sec:conclusion} \input{conclusion} \bibliographystyle{IEEEtran} \balance \subsection{Terminology} In this section, we explain the different stages a vulnerability goes through in its lifecycle. Then, we define our threat levels for vulnerabilities using the different stages that a vulnerability goes through during its lifecycle. \subsection{Vulnerability Lifecycle} \label{sec:background2} A software \emph{vulnerability} is a weakness that allows unauthorized actions and/or access to be performed. These actions are typically used to break through the system and violate its security policies~\cite{liu2012software,shirey2000internet}. A \emph{vulnerability threat} is a potential danger to exploit a vulnerability in order to breach security and cause possible harm~\cite{shirey2000internet}. As shown in Figure~\ref{vuln_timeline}, typically, and with emphasis on vulnerabilities in the Node Package Manager ({npm}\xspace ecosystem), a vulnerability goes through a number of different stages~\cite{Reporting96}. \begin{itemize} \item \textbf{Introduction.} This is when the software vulnerability is first introduced into the code. At this stage, no one really knows about its existence, assuming that the introduction is not malicious. Hence, the potential threat of the vulnerability is quite low. \item \textbf{Discovery (report).} When a vulnerability is discovered, it must be reported to the npm security team. The npm team investigates to ensure that the reported vulnerability is legitimate. At this stage, only the security team and the reporter of the vulnerability know about its existence. The potential threat at this stage is still low. \item \textbf{Notification.} Once the reported vulnerability is confirmed, the security team triages the vulnerability and notifies the vulnerable package maintainers. At this stage, only the reporter, npm team, and package maintainers know about the vulnerability, hence its potential threat to be exploited remains low. \item \textbf{Publication without a known fix.} Once the package maintainers are notified, they have 45 days before npm publishes the vulnerability publicly. Alongside with publishing the vulnerability, the npm team may also publish a proof-of-concept showing how the vulnerability can be exploited. At this stage, the vulnerability is known publicly and its potential threat is high. \item \textbf{Publication with a fix.} Another (and more common) way that a vulnerability can be published is when a fix is provided by the package maintainers. If a fix is provided (before 45 days), then npm publishes the vulnerability along with the version of the package that fixes the vulnerability. At this stage, the potential threat is not as high as when a no fix is provided, but now the onus is on the application maintainers to make sure that they pull in the latest fixes, otherwise they are risking being exploited. \end{itemize} Typically, the vulnerability publish date is after the report and notification dates. It is important to note that although the aforementioned stages are generally sequential, we do see cases where {it is not}. For example, in some cases we see vulnerabilities with a fix date that precedes its reporting or publication date. The race between developers and attackers starts as soon as a vulnerability is discovered. We use the different stages of a vulnerability to examine the potential threat of software vulnerabilities next. \subsection{Threat Levels} \label{sec:ex} As shown earlier, the different stages that a vulnerability goes through significantly impact its threat. Hence, our study is based on the idea that vulnerabilities should be examined while taking their threat into consideration as the \textit{vulnerability timing} makes them hard to exploit. We use the various stages to ground our argument and define three specific threat levels: \begin{enumerate} \item \textbf{Low threat - before discovery (report).} Since very little (or nothing at all) is known about a vulnerability before it is found, i.e., vulnerabilities are hidden in the applications, we believe that its potential threats and chances of being exploited are very low. Hence, we classify all vulnerabilities at this stage as having \emph{low threat}. \item \textbf{Medium threat - after discovery \& before publication:} Once a vulnerability has been discovered, there is potential that others may also know about it. Moreover, since at this stage the public is still not aware of the vulnerability, the vulnerability might be exploited by people who know about it somehow and have the capability to exploit it. Hence, we classify vulnerabilities at this stage as having \emph{medium threat}. \item \textbf{High threat - after publication:} After publication this is the time when the chance of exploitability is highest. Of course, if a fix is provided, then the risk is lower, however, if the application does not update then it still faces a major risk of being exploited. If a fix is not provided, then all applications are at a very high risk of being exploited, hence, we classify all vulnerabilities at this stage as having \emph{high threat}. \end{enumerate} \begin{figure}[tb!] \centering \includegraphics[width=1\linewidth]{images/vuln_timeline_new} \caption[]{Classification of threats over the vulnerability lifecycle.} \label{vuln_timeline} \end{figure} \subsection{Security Migration Cost} \label{sec:cost} Developers of Node.js applications may use dynamic versioning constraints if they want to install the latest version of a dependency, allowing them to get the latest updates for security fixes of the package. In fact, npm adopts a semantic version scheme~\cite{semvernp91}, where package maintainers are encouraged to specify the extent of their updates in three different levels: 1) patch release, which indicates backward compatible bug fixes, 2) minor release, which indicates backwards compatible new features and 3) major release, which informs developers of backwards incompatible changes in the package release. While our study (RQ$_3$) showed that 90.76\% of high-threat vulnerabilities have a safe version available for application maintainers (at the snapshot 100\%), we manually inspected the fixed versions and the applications version constraints and found that in 43.07\% of the cases, the fix is only available in another major release. For instance, an application depends on P:1.0.0, and the fix patch was only released for a major version 2.0.0 and onwards. Hence, to benefit from a fix patch in such a case, developers are required to upgrade their dependencies at the risk of breaking their own code, since a new major release has breaking changes compared to the version the application depends on. This imposes significant migration costs, especially for large projects that depend on dozens of packages. Furthermore, this shows that using dynamic versioning at the level of patch and minor releases (as recommended by npm) does not completely prevent high threat level vulnerabilities for affecting Node.js applications. \vspace{0.1in} \subsection{Implications} \label{sec:imp} \textbf{Implications to researchers.} Several studies have addressed the problem of vulnerabilities in software libraries~\cite{decan2018impact,zapata2018towards}. Our study, however, complements previous studies by analyzing the risks of vulnerable dependencies in the Node.js applications, aggregating the vulnerability lifecycle through the threat level metric. Researchers can use our empirical evidence to better understand the risks Node.js applications face due to their high reliance on dependencies. Our results show that most vulnerable dependencies found in a application snapshot have a low risk of being exploited when considering the lifecycle of vulnerabilities and how applications update their dependencies. Our results also show that the time element is crucial to understanding the threat of vulnerable dependencies in applications. Hence, a major implication of our study for researchers is that not all vulnerabilities are equal, and should not be treated and analyzed as such. Research needs to account for more than the existence of vulnerabilities to draw more meaningful analyses regarding software security, particularly for applications in software ecosystems where the level of dependency continues to increase. Research can use our threat-level approach to provide a more refined picture when reporting the impact of vulnerabilities. Researchers can also reuse our approach to help them identify and classify vulnerable dependencies in the applications (in Section~\ref{subsec:scanning}). Furthermore, more studies across ecosystems are necessary to get a broader perspective on the threat level of vulnerability dependencies. npm is one of the largest ecosystems and since applications depend on an increasingly high number of packages~\cite{decan2018empirical}, Node.js applications may be subjected to higher risk of vulnerable dependencies. Further investigation could unveil if this pattern holds in other ecosystems. \\ \noindent \textbf{Implications to practitioners.} Our results revealed important takeaways for software practitioners. First, vulnerable dependencies are common, 67.93\% of the studied Node.js applications had at least one vulnerable dependency at the last studied snapshot. Practitioners need to be in constant alert to update their dependencies and tools that increase awareness of vulnerabilities, such as Dependabot~\cite{Dependab26:online} and \texttt{npm audit}~\cite{npmaudit59:online} are evermore crucial for the safety of software applications, especially because they warn developers as soon as the vulnerability becomes of a high threat level. Second, practitioners also need to account for the threat level of a vulnerability to have a more correct understanding of software vulnerabilities in software ecosystems. Our method of analysis can also be used by developers to identify packages that more often raise the threat level in their applications. Also, while vulnerabilities are widespread in open-source packages in the npm, in most cases package maintainers issue a fix patch for their vulnerability as soon as it becomes public, which is crucial to mitigate the chances of having a vulnerability exploited and cause potential harm to end-users and application maintainers. Third, our study showed that developers are in need of more tools that go beyond simply warning them of a published vulnerability. For example, they need tools to help them understand: 1) the costs of migrating to a safer version and whether it is possible to fix a vulnerability without breaking their code, 2) the frequency in which certain dependencies have become vulnerable in the past, in order to grab the threats of depending on such packages and better plan their project maintenance, 3) history of all vulnerable dependencies of their application in order to understand the frequency and the duration in which their application became at the risk of a high threat vulnerability in the past. Packages that do not update their code to address reported vulnerabilities incur in a high risk for applications that use them and should be avoided by critical applications. \section{Introduction} \label{sec:introduction} \input{introduction} \begin{figure*}[!t] \centering \end{figure*} \section{Classifying Vulnerabilities} \label{sec:background} \input{background} \section{NPM Dependency Management} \label{sec:dependency} \input{dependency} \section{Case Study Design} \label{sec:case_study_design} \input{design} \section{Case Study Results} \label{sec:results} \input{results} \section{Discussion} \label{sec:discussion} \input{discussion} \section{Related Work} \label{sec:related_work} \input{related_work} \section{Threats to Validity} \label{sec:threats} \input{threats} \section{Conclusion and Future Work} \label{sec:conclusion} \input{conclusion} \bibliographystyle{IEEEtran} \balance \subsection*{\rqone} \label{sec:RQ1} {\textbf{Motivation}}: Prior work showed that a significant amount of application code comes from third party packages, and a non-negligible amount of these packages are affected by known security vulnerabilities~\cite{williams2012unfortunate}. However, we argue that not all vulnerabilities should be treated equally. Hence, in this RQ we would like to quantify how many of our studied applications have at least one vulnerable dependency and what the threat level of these vulnerable dependencies is. Answering this question will help us understand the real risk/threat of vulnerable packages on the software applications. \noindent {\textbf{Approach}}: In order to perform an unbiased analysis, we need to account for vulnerability discovery time. Prior work showed that vulnerabilities in npm take on median 3 years to be discovered and publicly announced~\cite{decan2018impact}. As a consequence, selecting snapshots of our applications in 2019 will paint an incomplete picture, as most vulnerabilities recently introduced in the package's code would remain hidden for a median of 3 years. Since we collected the advisories dataset in May/June 2019, we chose to evaluate our applications as of May 2016 (3 years prior), which ensures that at least half the dependency vulnerabilities introduced in the code are reported in the current advisories dataset. Then, we answer our RQ in two steps. First, we examine if the \textit{selected snapshot} of the application had at least one dependency that contains a vulnerability (irrespective of its threat level). Then, to determine the threat level of the vulnerable dependencies in the examined applications, we focus only on the set of applications that have at least one vulnerable dependency using the methodology described in Section~\ref{subsec:scanning}. In the second step, we quantify the number of vulnerable dependencies in the applications under each threat level. We first check the percentage of overall vulnerable dependencies in each application and illustrate their distribution using a Boxplot. We further analyze the distribution of these vulnerable dependencies across the threat levels and plot it using three Boxplots, one for each threat level. For example, an application could have 10\% of its dependencies as vulnerable at the analysed snapshot, and such percentage (i.e., 10\%) could be distributed across the threat levels as follows: 25\% of the vulnerable dependencies are classified as low threat, 60\% of them are classified as medium, and 15\% as high. \begin{figure}[tb!] \centering \includegraphics[width=1\linewidth,height=.85\linewidth] {images/RQ1_new.pdf} \caption{Boxplots showing the distributions of the percentage of overall vulnerable dependencies in the applications (left boxplot), and how these percentages are distributed across threat levels (right boxplot). N and M are the total number of dependencies and the total number of vulnerable dependencies, respectively. } \label{RQ1Perc} \end{figure} \noindent \textbf{Results}: Of the 6,673 studied applications \textbf{67.93\% (4533 applications) depend on at least one vulnerable dependency}. The affected applications contains a total of 10,154 vulnerable dependencies from 149 distinct vulnerable packages. The 149 packages comprises 23.21\% of the overall vulnerable packages in the npm advisories dataset. Figure~\ref{RQ1Perc} shows the percentage of vulnerable dependencies per application (left boxplot), and the distribution of vulnerable dependencies at different threat levels (right boxplot). It shows that, on median, 14.29\% of the dependencies in the affected application (i.e., applications with at least 1 vulnerable dependency) are vulnerable. Also, Figure~\ref{RQ1Perc} shows that such percentage of vulnerable dependencies (i.e., 14.29\%) is distributed as follows: \textbf{94.91\% of the vulnerable dependencies are classified as low threat vulnerabilities}, 2.06\% of them are classified as medium, and 3.03\% are classified as high. \vspace{0.08in} \begin{table}[h!] \centering \caption{Mann-Whitney Test (p-value) and Cliff's Delta (d) for the different threat levels.} \label{stattest} \begin{tabular}{l|r|r} \toprule \textbf{Threat Levels} & \textbf{\textit{p}-value} &\textbf{ Cliff's Delta \textit{{(d)}}} \\ \midrule Low vs. Medium & 2.2e-16 & 0.984 (large) \\ Low vs. High & 2.2e-16 & 0.970 (large) \\ Medium vs. High & 2.2e-16 & 0.335 (medium) \\ \bottomrule \end{tabular}% \end{table} \vspace{0.08in} To statistically verify our observation, we perform a one-sided non-parametric Mann-Whitney U test~\cite{mcknight2010mann} by comparing the distributions between the different threat levels. Table~\ref{stattest} shows the p-values and effect size values. We observe a statistically significant differences between (low and medium), (low and high), (medium and high), at p-value $<$ 0.05 for all comparisons. Furthermore, we observe, using Cliff's delta~\cite{cliff1993dominance}, a large effect size for the differences between low and medium, low and high. Also, we found a medium effect size for the difference between medium and high. This indicates that the differences between the different threat levels are statistically significant.\\ \begin{mdframed}[roundcorner=5pt,linewidth=0.5mm, linecolor=black] \lipsum[0] \textbf{\textit{Our findings show that 67.93\% of the examined applications depend on at least one vulnerable package. However, the vast majority (94.91\%) of these dependencies have low threat.} } \end{mdframed} \vspace{0.2in} \subsection*{\rqtwo} {\textbf{\\Motivation}}: Thus far, we have analyzed the vulnerability threats of a single snapshot of each application in our dataset. However, our findings may differ as the applications evolve. For example, a vulnerability with high threat on a given day could have had low threat the week before. \begin{figure*}[tb!] \centering \setlength{\abovecaptionskip}{10pt} \includegraphics[width=1\linewidth] {images/RQ2Evol3_new.pdf} \caption{Boxplots showing the percentage of overall vulnerable dependencies and their distribution in each threat level over the studied snapshots. N and M are the total number of dependencies and the total number of vulnerable dependencies, respectively.} \label{RQ2Evol} \end{figure*} Hence, in this RQ we would like to determine whether our results generalize to different historical snapshots in the application's development lifetime. Such an evolutionary examination allows us to discover whether the trend of the threat levels changes across different stages of an application's lifetime. \\ \noindent {\textbf{Approach}}: Since the different applications are of different lifespans, we want to find a measure that makes comparing them feasible. To do so, we use the number of commits as a way to divide the applications into different intervals. Since commit frequency and time between commits vary from one application to another, we normalize the applications by segmenting the lifetimes of each application into five equal intervals (each containing 20\% of an application's lifetime by {time in days}), take one snapshot at each interval, then analyze it. Although this might seem like a straightforward task, it poses some challenges, since we have a large applications dataset and the package.json file in them is updated significantly over the application's lifetime. For this analysis, we only consider the affected applications identified in RQ$_1$. The last snapshot (at 100\%) is the same snapshot that we analyzed in RQ$_1$ (i.e., May 2016). \begin{table}[tbh] \centering \caption{The percentage of vulnerable applications at different historical snapshots.} \label{DisT1} \begin{tabular}{l|r} \toprule \multirow{2}{*}{\textbf{Snapshot}} & \textbf{Vulnerable} \\ & \textbf{Applications} \\ \midrule \textbf{20\%} &{ 55.31\%} \\ \textbf{40\%} & 58.17\% \\ \textbf{60\%} & 60.87\% \\ \textbf{80\%} & 63.03\% \\ \textbf{100\%} & {67.93\%} \\ \bottomrule \end{tabular \end{table} \noindent {\textbf{Results}}: Table~\ref{DisT1} shows the percentage of applications that have at least one vulnerable dependency for the 5 analyzed snapshots across their lifetime. We observe that \textbf{the percentage of vulnerable applications steadily increases each snapshot} and varies between 55.31 - 67.93\% in the studied applications. Figure~\ref{RQ2Evol} illustrates the distributions of the percentage of vulnerable dependencies at each threat level over the studied snapshots. The total number of dependencies (N) and the total number of vulnerable dependencies (M) in the studied applications are shown at the bottom of Figure~\ref{RQ2Evol}. The raw numbers of the dependencies show that the total number of dependencies increases over time, and so does the raw number of vulnerable dependencies. From Figure~\ref{RQ2Evol}, we observe that the affected applications depend on vulnerable dependencies at an earlier stage (i.e., at 20\%) of their lifetime. However, we also observe that the trend observed in RQ1 remains the same, i.e., the overall percentage of vulnerable dependencies ranges between 14.29\% - 14.68\%. Also, the majority of the vulnerabilities have a low threat level, followed by high and medium threat. To sum up, our analysis shows that all trends observed in RQ$_1$ also hold at different stages of the applications, albeit the raw number of dependencies does increase.\\ \begin{mdframed}[roundcorner=5pt,linewidth=0.5mm, linecolor=black] \lipsum[0] \textbf{\textit{As applications evolve, the overall number of vulnerable dependencies is increasing, however, the median percentage of vulnerable dependencies remains mostly constant. Moreover, the majority of vulnerabilities they face remain as low threat vulnerabilities, as these applications evolve.}} \end{mdframed} \vspace{-0.2in} \subsection*{\rqthree} \textbf{Motivation}: In the previous research questions, we found that the majority of affected dependencies are impacted by low threat vulnerabilities, throughout applications development history. However, a sizeable number of projects depend on high threat dependencies, which are the most important. This means that those applications depend on vulnerable versions of dependencies even after the vulnerability reports have been discovered (reported)-and-published. In such cases, the \emph{developers of the applications could know} about the presence of the vulnerability in the dependency, and hence, {should} avoid using that vulnerable version, if a fix is available. Specifically, we want to know who is to blame - the package maintainers for not providing a version that fixes a known vulnerability - or the application maintainers for not keeping their applications up-to-date. Answering this will help us pinpoint the causes for high threat vulnerabilities in npm applications and develop further strategies to solve this problem. \noindent \textbf{Approach}: To perform our investigation and answer who is responsible for the high threat vulnerabilities in applications, we use the same method to determine high threat vulnerabilities as presented in the first two RQs. For each high threat vulnerable dependency, we check the availability of a safe version of the package for the vulnerability at the analyzed snapshot time. Depending on such availability our analysis has one of two outcomes: \begin{itemize} \item \textbf{Package-to-blame:} if at the analyzed snapshot, no safe version has been provided by the package maintainers for a publicly known vulnerability. As the publication of a vulnerability comes after a period of 45 days, we consider the package maintainers the responsible for the high threat vulnerability in applications. \item \textbf{Application-to-blame:} if there is already a released safe version of the vulnerable package but the application continues to rely on an (old) version with a publicly known vulnerability. Application developers should monitor their dependencies and update to releases without known vulnerabilities, hence, we consider the application maintainers as responsible for the high threat vulnerability. \end{itemize} \begin{table}[tb!] \centering \caption{The percentage of vulnerabilities caused by the lack of available fix patch (Package-to-blame) vs caused by the lack of dependencies update (Application-to-blame), over the applications snapshot.} \label{RQ2T1} \begin{tabular}{l|r|r} \toprule \textbf{Snapshot} & \textbf{Package-to-blame} & \textbf{Application-to-blame} \\ \midrule \textbf{20\%} & {12.06\%} & {87.94\%} \\ \textbf{40\%} & {9.52\%} & {90.48\%} \\ \textbf{60\%} & 11.91\% & {88.09\%} \\ \textbf{80\%} & {12.43\%} &{87.57\%} \\ \textbf{100\%} & \textbf{9.24\%} & \textbf{90.76\%} \\ \bottomrule \end{tabular}% \end{table} \noindent \textbf{Results}: Table~\ref{RQ2T1} shows the percentage of high threat vulnerabilities based on our responsibility analysis. From Table~\ref{RQ2T1}, we observe that \textbf{for high threat vulnerabilities, the application is to blame in 90.76\% of the cases} at the last snapshot (i.e., 100\%). That means that in 9 out of 10 cases the high threat vulnerability had an available fix, but the applications did not update their dependencies to receive the last fix patch. Note that this observation holds over all snapshots, with percentages of application-to-blame cases varying from 87.94\% to 90.76\%. Therefore, and perhaps counter-intuitively, high threat vulnerabilities do not exist because packages have unfixed vulnerabilities, rather the real cause is the fact that these applications fail to keep up or at least to inform themselves well enough about a given dependency version. Hence, a major implication of our study is that application developers need to take updates pushed from their dependencies seriously, or at least actively track their dependencies, since those can lead to very serious effects. It is important to note that we do not argue about the severity of the vulnerabilities, but rather their likelihood threat of being exploited. Hence, a low severity vulnerability can be very dangerous if everyone knows how to exploit it (high threat level according to our classification). The inverse is also true in that a high severity vulnerability can have a very low chance of being exploited if no one knows about its existence (low threat level).\\ \begin{mdframed}[roundcorner=5pt,linewidth=0.5mm, linecolor=black] \sloppy \lipsum[0] \textbf{\textit{{Our findings show that applications not updating their dependencies, are the main cause of high threat (more than 87\%) vulnerabilities.}} } \end{mdframed} \subsection{Data Collection} \label{subsec:data} Our study examines vulnerable dependencies in Node.js applications. We chose to focus on Javascript due to its wide popularity amongst the development community~\cite{StackOve70:online}. \\ \noindent\textbf{Packages vs. Applications.} The software community classifies JavaScript projects into two categories: \textit{1) packages}, also referred to as libraries, which are included in other applications using dependency management tools to help facilitate and speed up development. Packages are referred to as "dependencies" of an application. \textit{2) applications} are standalone software projects, which are distinct from libraries, where they are not distributed via a package manager and are typically applications for clients and end users rather than components to build upon. As mentioned before, the Node.js applications mainly state the packages they depend on (i.e., dependencies) in a file called package.json. To perform our study, we leverage two datasets: (1) Node.js applications that use {npm} to manage their dependencies, and (2) Security vulnerabilities that affect npm packages. To do so, we \textbf{(i)} obtain the Node.js applications from GitHub, \textbf{(ii)} extract their dependencies, and \textbf{(iii)} obtain the security vulnerabilities for npm packages from {npm} advisories~\cite{npmadvisories}. The dataset collection took place during May and June of 2019.\\ \noindent\textbf{(i) Applications Dataset.} To analyse a large number of open source JavaScript applications that depend on npm packages and obtain insights on their security vulnerabilities, we mine the GHTorrent dataset~\cite{GHtorrent} and extract information about all Node.js applications hosted on GitHub. The GHTorrent dataset contains a total of 7,863,361 JavaScript projects hosted on GitHub, of which 2,289,130 use npm as their package management platform (i.e., these projects contain a file called package.json). Moreover, since both Node.js \textit{packages} and \textit{applications} can use GitHub as their development repository, and our applications dataset should only contain Node.js \emph{applications}, we filter out the GitHub projects that are actually npm \emph{packages} by checking their GitHub URL on the {{npm}} registry. The main reason that we focused on applications and not packages is because packages become exploitable only when used and deployed in an application, i.e., packages do not reside on their own in production, they should be part of applications that make use of them. This filtering excludes 328,343 projects from our list of GitHub projects as they are identified as packages and not applications As shown in previous studies~\cite{kalliamvakou2014promises,kula2018developers}, some projects on GitHub are immature, hence, to make this study more reliable we refined the dataset using additional filtering criteria to eliminate such immature projects. In particular, we gather applications that satisfy all the following criteria: \begin{itemize} \item Non-forked applications, as we do not want to have duplicated project history to bias our analysis. \item Applications that depend upon more than two dependencies. \item Applications that have at least 100 commits by more than two contributors, which indicates a minimal level of commit activity. \item Applications that have had their creation date (first commit) before January 1st 2017. Since vulnerabilities take on median 3 years to be discovered~\cite{decan2018impact}, applications in our dataset need to have a development history long enough to have had a chance for their vulnerabilities to be discovered. \item Applications that have had their latest commit after January 1st 2017, as we want to analyze applications that had some level of development in the last 3 years. \end{itemize} After applying these refinement criteria, we end up with 6,673 Node.js applications that make use of npm packages. Table~\ref{statsApplications} shows descriptive statistics on the selected Node.js applications in our dataset. Overall, the applications in our dataset have a rich development history (a median of 213 commits made by 4 developers and 1,657 days of development lifespan) and make ample use of external dependencies (a median of 11 dependencies).\\ \noindent\textbf{(ii) Application Dependencies.} After obtaining the applications dataset, we want to extract the history of dependency changes of all applications. This is necessary to identify the exact dependency versions that would be installed by the application at any specific point-in-time. As mentioned in Section~\ref{sec:dependency}, Node.js applications specify their dependencies in the package.json file, which contains the dependency list, containing the dependent upon packages and their respective version constraints. Hence, we extract all changes that touched the package.json file and associate each commit hash and commit date to their respective package.json dependency list, creating a history of dependency changes for all applications. Note that these dependencies are not yet resolved, that is, we only have the version constraints (not the versions) for the dependencies of each application. \\ \begin{table}[tb!] \centering \caption{Statistics of the 6,673 studied Node.js applications. } \label{statsApplications} \begin{tabular}{l|r|r|r|r} \toprule \textbf{Metric} & \textbf{Min.} & \textbf{Median($\bar{x}$)} & \textbf{Mean($\mu$)} & \textbf{Max.} \\ \midrule \textbf{Commits} & 100 & 213 & 384.60 & 53,872 \\ \textbf{Dependencies} & 3 & 11 & 14.93 & 114 \\ \textbf{Developers} & 3 & 4 & 5.33 & 52 \\ \textbf{Lifespan (in days)} & 151 & 1,657 & 1,730.07 & 3,575 \\ \bottomrule \end{tabular} \end{table} \noindent\textbf{(iii) NPM Advisories Dataset.} To identify Node.js applications that depend on vulnerable packages, we need to collect information on npm vulnerable packages. We resort to the \textit{NPM advisories} registry to obtain the required information about all npm vulnerable packages~\cite{npmadvisories}. The npm advisories dataset is the official registry for npm vulnerability reports, which contains a number of JavaScript vulnerabilities, specific to the Node.js-platform packages. This dataset provides several kinds of information about vulnerable packages relevant to our study. Each report has the affected package name, the package versions affected by the vulnerability, and the versions in which the vulnerabiliy was fixed (safe versions). The report also contains both the vulnerability discovered (reported) time and published time, which we use in our approach for identifying and classifying vulnerabilities (Section~\ref{subsec:scanning}). Note that a vulnerable package could be affected by several vulnerabilities (i.e., a vulnerable package appears with different vulnerability reports due to different vulnerability types). Our initial dataset contains 654 security reports that cover 601 vulnerable packages. Following the criteria filtration process applied by Decan et al.~\cite{decan2018impact}, we removed 12 vulnerable packages of the type "Malicious Package", because they do not actually introduce vulnerable code. These vulnerabilities are packages with names close to popular packages (a.k.a. typo-squatting) in an attempt to deceive users at installing harmful packages. The 12 vulnerable packages account for 12 vulnerability reports. At the end of this filtering process, we are left with 642 security vulnerabilities reports affecting 589 distinct vulnerable packages. These packages have combined 26,462 distinct package versions of which 13,868 are affected by vulnerabilities from our report. Table~\ref{dataset} shows the summary statistics for vulnerability reports on npm packages. \begin{table}[tb!] \centering \caption{Descriptive statistics on the npm advisories dataset.} \label{dataset} \begin{tabular}{l|r} \toprule Vulnerability reports & 642 \\ Vulnerable packages & 589 \\ Versions of vulnerable packages & 26,462 \\ Affected versions by vulnerability & 13,868 \\ \bottomrule \end{tabular}% \vspace{-2mm} \end{table} \begin{figure*}[tb!] \centering \setlength{\abovecaptionskip}{5pt} \includegraphics[width=0.7\linewidth]{images/approach.pdf} \caption[]{Approach for identifying and classifying vulnerable dependencies in Node.js applications.} \label{classifyApproach} \end{figure*} \subsection{Identifying and Classifying Vulnerable Dependencies in Node.js Applications} \label{subsec:scanning} To classify the threat level of vulnerable dependencies at a specific point in the development history of a Node.js application, which we refer to as the \textit{analyzed snapshot time}, we leverage 3-step approach. Figure~\ref{classifyApproach} provides an overview of our approach, which we detail below: \noindent {\textbf{Step 1. Extract dependencies and resolve versions.}} The goal of this step is to extract applications dependencies and find the actual dependency version installed at the analyzed snapshot time. For each application, we extract the dependency list (with the versioning constraints) at that snapshot time from the history of dependency changes. After that, to find the actual version of each dependency at the analyzed snapshot, we utilize the \textit{semver} tool~\cite{semvernp91} that is used by npm to find the latest version that satisfies the versioning constraint, with an additional restriction that the satisfying version should have been released (in the npm registry) before the application snapshot time. For example, an application can specify a versioning constraint (``P:$>$1.0.0'') at the snapshot May 2016. Hence, the actual installed version is the latest version that is greater than 1.0.0 and also has been released in the npm registry before May 2016. This step allows us to find the installed version of the dependency at the analyzed snapshot time. \\ \noindent {\textbf{Step 2. Identify vulnerable dependency versions.}} After determining the resolved (and presumably installed) version at the analyzed snapshot time, we check whether the resolved version is vulnerably or not. To do so, we check the advisories dataset for the versions that were available at that snapshot point. If the resolved version is covered by the advisories dataset, we label it as a vulnerable dependency version. We skip the whole next step if the dependency version has not been mentioned in any advisory, i.e., the dependency version is not vulnerable. \\ \noindent {\textbf{Step 3. Identify threat levels of vulnerable versions.}} Once we identify the vulnerable dependency versions at the analyzed snapshot time, we classify each vulnerable dependency version using one of the threat levels we defined earlier (in Section~\ref{sec:ex}), i.e., we find out the threat level of each vulnerable dependency version. To do so, for each vulnerable version, we compare its vulnerability \textit{discovery (report)} and \textit{publication} time to the analyzed snapshot time. As we stated previously (in Section~\ref{sec:ex}), if the vulnerability publication time of the vulnerable dependency version is before the application's snapshot time then we mark the vulnerability as high threat vulnerability. If the vulnerability of the dependency was not published but only discovered (reported) before the application's snapshot time, then we mark it as medium. And finally, if it was neither published nor discovered (reported) before the analyzed snapshot time (i.e., no one knows about it at that snapshot time), then we mark it as low. In cases where more than one vulnerability affects the vulnerable dependency version, we resort to a weakest link approach (i.e., we label the vulnerable dependency version with the highest threat level). For example, if we find that the vulnerable version of the dependency is affected by two vulnerabilities -one having low threat and another as high threat, we label the vulnerable dependency version as high at that snapshot time. \subsection{Replication Package} To facilitate verification and advancement of research in the field, a replication package comprising the data used in our study along with the analyses used in our study is publicly available\footnote{http://doi.org/10.5281/zenodo.3837397}. \subsection{Software Ecosystems} A plethora of recent work focused on software ecosystems. Several works compare different ecosystems. For example, Decan et al.~\cite {decan2018empirical} empirically compared the evolution of 7 popular package ecosystem using different aspects, e.g., growth, changeability, resuability, and fragility. They observed that the number of packages in those ecosystems is growing over time, showing their increasing importance. Other work focused specifically on npm~\cite{fard2017javascript,kula2017impact, wittern2016look}. For example, Fard et al.~\cite{fard2017javascript} examined the evolution of dependencies within an npm project, and showed that there is a heavily interdependence, with the average number of dependencies being 6 and growing over time. Wittern et al.~\cite{wittern2016look} investigated the evolution of npm using metrics such as dependencies between packages, download count, and usage count in JavaScript applications. They found that packages in the npm ecosystem are steadily growing. Such amounts of packages make the spread and discovery of vulnerabilities much worse, given the heavy dependence on such packages and the potential security problems in those packages. Other studies pointed out the fragility of software ecosystems and provided insights on the challenges application developers face. For example, Bogart et al.~\cite{bogart2015breaks,bogart2016break} examined the Eclipse, CRAN, and npm ecosystems, focusing on what practices cause API breakages. They found that a main reason for breaking changes are the updates of a dependency. This finding may explain why application developers are hesitant to update and explain why we see high threat vulnerabilities impacting applications that do not update in time. Our study differs from the prior work since we focus on the threat level of dependency vulnerabilities in Node.js applications. Moreover, we examine how this threat level changes as applications evolve and examine the reason that high threat dependency vulnerabilities exist. That said, much of the aforementioned work motivated us to study npm and focus on examining vulnerabilities in application dependencies. \vspace{-0.05in} \subsection{Security Vulnerabilities in Dependencies/Packages} Several works in the literature studied vulnerabilities that come from dependencies~\cite{di2009life,pham2010detection,cox2015measuring,massacci2011after,derr2017keep}. For example, Di Penta et al.~\cite{di2009life} and Pham et al.~\cite{pham2010detection} conducted empirical studies to analyze the evolution of vulnerabilities in source code, and found that most vulnerabilities are recurring due to software code reuse or libraries (i.e., dependencies). Cox et al.~\cite{cox2015measuring} evaluated ``dependency freshness'' to understand the relationship between outdated dependencies and vulnerabilities using industry benchmarks, and found that vulnerabilities were four times as much likely to have existed in outdated systems than in updated systems. Relative studies by Massacci et al.~\cite{massacci2011after} and Derr et al.~\cite{derr2017keep} are in line with~\cite{cox2015measuring}. In general, they both reported that vulnerabilities appeared commonly in non-maintained code and old versions, and this could be fixed by just an update to a newer version. Our study complements these studies by examining the threat of these vulnerabilities in the dependent applications. More specifically, vulnerabilities that affect packages in ecosystems have been studied broadly~\cite{kula2018developers,pashchenko2018vulnerable}. For example, Kula et al.~\cite{kula2018developers} analyzed the Maven ecosystem on more than 4,000 GitHub projects that correspond to 850,000 library migrations, and found that projects were heavily dependent on these libraries, and most projects (i.e. 81.5\%) had outdated libraries. The study also mentioned (based on interviews conducted with developers) that developers do not update dependencies, and 69\% of the interviewed developers tend to be not aware of their vulnerable dependencies. Pashchenko et al.~\cite{pashchenko2018vulnerable} studied the vulnerability impact of 200 open-source Java libraries commonly used in SAP~\cite{SAPSoftw78} organisation, and found that 20\% of the vulnerable dependencies are not deployed, and hence, they are not exploitable in practice. Moreover, they found that the majority of the vulnerable dependencies (81\%) can be fixed by a simple upgrade to a newer safe version, suggesting that software development companies have to allocate their audit tools correctly. Other recent work focused on analyzing vulnerabilities in the npm ecosystem. For example, Hejderup’s~\cite{hejderup2015dependencies} analysed only 19 vulnerable packages and found that the number of vulnerabilities in them is growing over time. Similarly, Decan et al.~\cite{decan2018impact} analyzed the vulnerabilities in the npm ecosystem and found that the number of vulnerabilities is growing over time. Also, they reported that it takes a long time to discover vulnerabilities that affect npm packages. Our study complements this study by analyzing the risks of vulnerable dependencies in the Node.js applications (not addressed by the study~\cite{decan2018impact}), aggregating the vulnerability lifecycle through the threat level metric. A recent study by Zapata et al.~\cite{zapata2018towards} assessed the danger of having vulnerabilities in dependent libraries by analyzing function calls of the vulnerable functions. They manually analyzed 60 projects that depend on vulnerabilities, and found that 73.3\% of them were actually safe because they did not make use of the vulnerable functionality of their dependencies, showing that there is a considerable overestimation on previous reports. Our study identifies yet another source of overestimation by including a time-based analysis into a large and comprehensive set of \textit{applications} (i.e., 6,673 Node.js applications). Zimmermann et al.~\cite{zimmermann2019small} studied the security threat of the npm ecosystem dependencies by mainly analysing the maintainers role and responsibilities for vulnerable packages. They mainly observed that a very small number of maintainers' accounts (i.e., 20 accounts) could be used to inject malicious code into thousands of npm packages, a problem that has been increasing over time. Zerouali et al.~\cite{zerouali2019impact} studied npm vulnerable packages in Docker containers, and found that they are common in the containers, suggesting that Docker containers should keep their npm dependencies updated. To assess the impact of vulnerable dependencies in the dependent Java applications, Plate et al.~\cite{plate2015impact} proposed an approach that provides a fine-grained assessment of the vulnerabilities that affect dependencies in dependent Java applications. In particular, the approach first determines whether or not the application makes use of the library that is known to be vulnerable. Then, the approach tries to determine whether or not the application executes the fragment of the dependency where the vulnerable code is located. Furthermore, Ponta et al.~\cite{ponta2018beyond} built upon their previous approach in~\cite{plate2015impact} to generalize their vulnerability detection approach by using static and dynamic analysis to determine whether the vulnerable code in the library is reachable through the application call paths. Their proposed approach is implemented in a tool called, Vulas, which is an official software used by SAP to scan its Java code. Our study focuses on analyzing the threat of npm vulnerabilities in dependencies, which affected applications that rely on them. In many ways, our study complements the related work since, (1) instead of studying security vulnerabilities that exist in packages, we particularly focus on the threat of such vulnerable packages by real-world open source applications; (2) we provide a threat classification for software vulnerabilities based on their lifetime, and we use our classification and perform an empirical study on Node.js applications. \subsection{Software Ecosystems} A plethora of recent work focused on software ecosystems. Several works compare different ecosystems. For example, Decan et al.~\cite {decan2018empirical} empirically compared the evolution of 7 popular package ecosystem using different aspects, e.g., growth, changeability, resuability, and fragility. They observed that the number of packages in those ecosystems is growing over time, showing their increasing importance. Other work focused specifically on npm~\cite{fard2017javascript,kula2017impact, wittern2016look}. For example, Fard et al.~\cite{fard2017javascript} examined the evolution of dependencies within an npm project, and showed that there is a heavily interdependence, with the average number of dependencies being 6 and growing over time. Wittern et al.~\cite{wittern2016look} investigated the evolution of npm using metrics such as dependencies between packages, download count, and usage count in JavaScript applications. They found that packages in the npm ecosystem are steadily growing. Such amounts of packages make the spread and discovery of vulnerabilities much worse, given the heavy dependence on such packages and the potential security problems in those packages. Other studies pointed out the fragility of software ecosystems and provided insights on the challenges application developers face. For example, Bogart et al.~\cite{bogart2015breaks,bogart2016break} examined the Eclipse, CRAN, and npm ecosystems, focusing on what practices cause API breakages. They found that a main reason for breaking changes are the updates of a dependency. This finding may explain why application developers are hesitant to update and explain why we see high threat vulnerabilities impacting applications that do not update in time. Our study differs from the prior work since we focus on the threat level of dependency vulnerabilities in Node.js applications. Moreover, we examine how this threat level changes as applications evolve and examine the reason that high threat dependency vulnerabilities exist. That said, much of the aforementioned work motivated us to study npm and focus on examining vulnerabilities in application dependencies. \vspace{-0.05in} \subsection{Security Vulnerabilities in Dependencies/Packages} Several works in the literature studied vulnerabilities that come from dependencies~\cite{di2009life,pham2010detection,cox2015measuring,massacci2011after,derr2017keep}. For example, Di Penta et al.~\cite{di2009life} and Pham et al.~\cite{pham2010detection} conducted empirical studies to analyze the evolution of vulnerabilities in source code, and found that most vulnerabilities are recurring due to software code reuse or libraries (i.e., dependencies). Cox et al.~\cite{cox2015measuring} evaluated ``dependency freshness'' to understand the relationship between outdated dependencies and vulnerabilities using industry benchmarks, and found that vulnerabilities were four times as much likely to have existed in outdated systems than in updated systems. Relative studies by Massacci et al.~\cite{massacci2011after} and Derr et al.~\cite{derr2017keep} are in line with~\cite{cox2015measuring}. In general, they both reported that vulnerabilities appeared commonly in non-maintained code and old versions, and this could be fixed by just an update to a newer version. Our study complements these studies by examining the threat of these vulnerabilities in the dependent applications. More specifically, vulnerabilities that affect packages in ecosystems have been studied broadly~\cite{kula2018developers,pashchenko2018vulnerable}. For example, Kula et al.~\cite{kula2018developers} analyzed the Maven ecosystem on more than 4,000 GitHub projects that correspond to 850,000 library migrations, and found that projects were heavily dependent on these libraries, and most projects (i.e. 81.5\%) had outdated libraries. The study also mentioned (based on interviews conducted with developers) that developers do not update dependencies, and 69\% of the interviewed developers tend to be not aware of their vulnerable dependencies. Pashchenko et al.~\cite{pashchenko2018vulnerable} studied the vulnerability impact of 200 open-source Java libraries commonly used in SAP~\cite{SAPSoftw78} organisation, and found that 20\% of the vulnerable dependencies are not deployed, and hence, they are not exploitable in practice. Moreover, they found that the majority of the vulnerable dependencies (81\%) can be fixed by a simple upgrade to a newer safe version, suggesting that software development companies have to allocate their audit tools correctly. Other recent work focused on analyzing vulnerabilities in the npm ecosystem. For example, Hejderup’s~\cite{hejderup2015dependencies} analysed only 19 vulnerable packages and found that the number of vulnerabilities in them is growing over time. Similarly, Decan et al.~\cite{decan2018impact} analyzed the vulnerabilities in the npm ecosystem and found that the number of vulnerabilities is growing over time. Also, they reported that it takes a long time to discover vulnerabilities that affect npm packages. Our study complements this study by analyzing the risks of vulnerable dependencies in the Node.js applications (not addressed by the study~\cite{decan2018impact}), aggregating the vulnerability lifecycle through the threat level metric. A recent study by Zapata et al.~\cite{zapata2018towards} assessed the danger of having vulnerabilities in dependent libraries by analyzing function calls of the vulnerable functions. They manually analyzed 60 projects that depend on vulnerabilities, and found that 73.3\% of them were actually safe because they did not make use of the vulnerable functionality of their dependencies, showing that there is a considerable overestimation on previous reports. Our study identifies yet another source of overestimation by including a time-based analysis into a large and comprehensive set of \textit{applications} (i.e., 6,673 Node.js applications). Zimmermann et al.~\cite{zimmermann2019small} studied the security threat of the npm ecosystem dependencies by mainly analysing the maintainers role and responsibilities for vulnerable packages. They mainly observed that a very small number of maintainers' accounts (i.e., 20 accounts) could be used to inject malicious code into thousands of npm packages, a problem that has been increasing over time. Zerouali et al.~\cite{zerouali2019impact} studied npm vulnerable packages in Docker containers, and found that they are common in the containers, suggesting that Docker containers should keep their npm dependencies updated. To assess the impact of vulnerable dependencies in the dependent Java applications, Plate et al.~\cite{plate2015impact} proposed an approach that provides a fine-grained assessment of the vulnerabilities that affect dependencies in dependent Java applications. In particular, the approach first determines whether or not the application makes use of the library that is known to be vulnerable. Then, the approach tries to determine whether or not the application executes the fragment of the dependency where the vulnerable code is located. Furthermore, Ponta et al.~\cite{ponta2018beyond} built upon their previous approach in~\cite{plate2015impact} to generalize their vulnerability detection approach by using static and dynamic analysis to determine whether the vulnerable code in the library is reachable through the application call paths. Their proposed approach is implemented in a tool called, Vulas, which is an official software used by SAP to scan its Java code. Our study focuses on analyzing the threat of npm vulnerabilities in dependencies, which affected applications that rely on them. In many ways, our study complements the related work since, (1) instead of studying security vulnerabilities that exist in packages, we particularly focus on the threat of such vulnerable packages by real-world open source applications; (2) we provide a threat classification for software vulnerabilities based on their lifetime, and we use our classification and perform an empirical study on Node.js applications. \subsection*{\rqone} \label{sec:RQ1} {\textbf{Motivation}}: Prior work showed that a significant amount of application code comes from third party packages, and a non-negligible amount of these packages are affected by known security vulnerabilities~\cite{williams2012unfortunate}. However, we argue that not all vulnerabilities should be treated equally. Hence, in this RQ we would like to quantify how many of our studied applications have at least one vulnerable dependency and what the threat level of these vulnerable dependencies is. Answering this question will help us understand the real risk/threat of vulnerable packages on the software applications. \noindent {\textbf{Approach}}: In order to perform an unbiased analysis, we need to account for vulnerability discovery time. Prior work showed that vulnerabilities in npm take on median 3 years to be discovered and publicly announced~\cite{decan2018impact}. As a consequence, selecting snapshots of our applications in 2019 will paint an incomplete picture, as most vulnerabilities recently introduced in the package's code would remain hidden for a median of 3 years. Since we collected the advisories dataset in May/June 2019, we chose to evaluate our applications as of May 2016 (3 years prior), which ensures that at least half the dependency vulnerabilities introduced in the code are reported in the current advisories dataset. Then, we answer our RQ in two steps. First, we examine if the \textit{selected snapshot} of the application had at least one dependency that contains a vulnerability (irrespective of its threat level). Then, to determine the threat level of the vulnerable dependencies in the examined applications, we focus only on the set of applications that have at least one vulnerable dependency using the methodology described in Section~\ref{subsec:scanning}. In the second step, we quantify the number of vulnerable dependencies in the applications under each threat level. We first check the percentage of overall vulnerable dependencies in each application and illustrate their distribution using a Boxplot. We further analyze the distribution of these vulnerable dependencies across the threat levels and plot it using three Boxplots, one for each threat level. For example, an application could have 10\% of its dependencies as vulnerable at the analysed snapshot, and such percentage (i.e., 10\%) could be distributed across the threat levels as follows: 25\% of the vulnerable dependencies are classified as low threat, 60\% of them are classified as medium, and 15\% as high. \begin{figure}[tb!] \centering \includegraphics[width=1\linewidth,height=.85\linewidth] {images/RQ1_new.pdf} \caption{Boxplots showing the distributions of the percentage of overall vulnerable dependencies in the applications (left boxplot), and how these percentages are distributed across threat levels (right boxplot). N and M are the total number of dependencies and the total number of vulnerable dependencies, respectively. } \label{RQ1Perc} \end{figure} \noindent \textbf{Results}: Of the 6,673 studied applications \textbf{67.93\% (4533 applications) depend on at least one vulnerable dependency}. The affected applications contains a total of 10,154 vulnerable dependencies from 149 distinct vulnerable packages. The 149 packages comprises 23.21\% of the overall vulnerable packages in the npm advisories dataset. Figure~\ref{RQ1Perc} shows the percentage of vulnerable dependencies per application (left boxplot), and the distribution of vulnerable dependencies at different threat levels (right boxplot). It shows that, on median, 14.29\% of the dependencies in the affected application (i.e., applications with at least 1 vulnerable dependency) are vulnerable. Also, Figure~\ref{RQ1Perc} shows that such percentage of vulnerable dependencies (i.e., 14.29\%) is distributed as follows: \textbf{94.91\% of the vulnerable dependencies are classified as low threat vulnerabilities}, 2.06\% of them are classified as medium, and 3.03\% are classified as high. \vspace{0.08in} \begin{table}[h!] \centering \caption{Mann-Whitney Test (p-value) and Cliff's Delta (d) for the different threat levels.} \label{stattest} \begin{tabular}{l|r|r} \toprule \textbf{Threat Levels} & \textbf{\textit{p}-value} &\textbf{ Cliff's Delta \textit{{(d)}}} \\ \midrule Low vs. Medium & 2.2e-16 & 0.984 (large) \\ Low vs. High & 2.2e-16 & 0.970 (large) \\ Medium vs. High & 2.2e-16 & 0.335 (medium) \\ \bottomrule \end{tabular}% \end{table} \vspace{0.08in} To statistically verify our observation, we perform a one-sided non-parametric Mann-Whitney U test~\cite{mcknight2010mann} by comparing the distributions between the different threat levels. Table~\ref{stattest} shows the p-values and effect size values. We observe a statistically significant differences between (low and medium), (low and high), (medium and high), at p-value $<$ 0.05 for all comparisons. Furthermore, we observe, using Cliff's delta~\cite{cliff1993dominance}, a large effect size for the differences between low and medium, low and high. Also, we found a medium effect size for the difference between medium and high. This indicates that the differences between the different threat levels are statistically significant.\\ \begin{mdframed}[roundcorner=5pt,linewidth=0.5mm, linecolor=black] \lipsum[0] \textbf{\textit{Our findings show that 67.93\% of the examined applications depend on at least one vulnerable package. However, the vast majority (94.91\%) of these dependencies have low threat.} } \end{mdframed} \vspace{0.2in} \subsection*{\rqtwo} {\textbf{\\Motivation}}: Thus far, we have analyzed the vulnerability threats of a single snapshot of each application in our dataset. However, our findings may differ as the applications evolve. For example, a vulnerability with high threat on a given day could have had low threat the week before. \begin{figure*}[tb!] \centering \setlength{\abovecaptionskip}{10pt} \includegraphics[width=1\linewidth] {images/RQ2Evol3_new.pdf} \caption{Boxplots showing the percentage of overall vulnerable dependencies and their distribution in each threat level over the studied snapshots. N and M are the total number of dependencies and the total number of vulnerable dependencies, respectively.} \label{RQ2Evol} \end{figure*} Hence, in this RQ we would like to determine whether our results generalize to different historical snapshots in the application's development lifetime. Such an evolutionary examination allows us to discover whether the trend of the threat levels changes across different stages of an application's lifetime. \\ \noindent {\textbf{Approach}}: Since the different applications are of different lifespans, we want to find a measure that makes comparing them feasible. To do so, we use the number of commits as a way to divide the applications into different intervals. Since commit frequency and time between commits vary from one application to another, we normalize the applications by segmenting the lifetimes of each application into five equal intervals (each containing 20\% of an application's lifetime by {time in days}), take one snapshot at each interval, then analyze it. Although this might seem like a straightforward task, it poses some challenges, since we have a large applications dataset and the package.json file in them is updated significantly over the application's lifetime. For this analysis, we only consider the affected applications identified in RQ$_1$. The last snapshot (at 100\%) is the same snapshot that we analyzed in RQ$_1$ (i.e., May 2016). \begin{table}[tbh] \centering \caption{The percentage of vulnerable applications at different historical snapshots.} \label{DisT1} \begin{tabular}{l|r} \toprule \multirow{2}{*}{\textbf{Snapshot}} & \textbf{Vulnerable} \\ & \textbf{Applications} \\ \midrule \textbf{20\%} &{ 55.31\%} \\ \textbf{40\%} & 58.17\% \\ \textbf{60\%} & 60.87\% \\ \textbf{80\%} & 63.03\% \\ \textbf{100\%} & {67.93\%} \\ \bottomrule \end{tabular \end{table} \noindent {\textbf{Results}}: Table~\ref{DisT1} shows the percentage of applications that have at least one vulnerable dependency for the 5 analyzed snapshots across their lifetime. We observe that \textbf{the percentage of vulnerable applications steadily increases each snapshot} and varies between 55.31 - 67.93\% in the studied applications. Figure~\ref{RQ2Evol} illustrates the distributions of the percentage of vulnerable dependencies at each threat level over the studied snapshots. The total number of dependencies (N) and the total number of vulnerable dependencies (M) in the studied applications are shown at the bottom of Figure~\ref{RQ2Evol}. The raw numbers of the dependencies show that the total number of dependencies increases over time, and so does the raw number of vulnerable dependencies. From Figure~\ref{RQ2Evol}, we observe that the affected applications depend on vulnerable dependencies at an earlier stage (i.e., at 20\%) of their lifetime. However, we also observe that the trend observed in RQ1 remains the same, i.e., the overall percentage of vulnerable dependencies ranges between 14.29\% - 14.68\%. Also, the majority of the vulnerabilities have a low threat level, followed by high and medium threat. To sum up, our analysis shows that all trends observed in RQ$_1$ also hold at different stages of the applications, albeit the raw number of dependencies does increase.\\ \begin{mdframed}[roundcorner=5pt,linewidth=0.5mm, linecolor=black] \lipsum[0] \textbf{\textit{As applications evolve, the overall number of vulnerable dependencies is increasing, however, the median percentage of vulnerable dependencies remains mostly constant. Moreover, the majority of vulnerabilities they face remain as low threat vulnerabilities, as these applications evolve.}} \end{mdframed} \vspace{-0.2in} \subsection*{\rqthree} \textbf{Motivation}: In the previous research questions, we found that the majority of affected dependencies are impacted by low threat vulnerabilities, throughout applications development history. However, a sizeable number of projects depend on high threat dependencies, which are the most important. This means that those applications depend on vulnerable versions of dependencies even after the vulnerability reports have been discovered (reported)-and-published. In such cases, the \emph{developers of the applications could know} about the presence of the vulnerability in the dependency, and hence, {should} avoid using that vulnerable version, if a fix is available. Specifically, we want to know who is to blame - the package maintainers for not providing a version that fixes a known vulnerability - or the application maintainers for not keeping their applications up-to-date. Answering this will help us pinpoint the causes for high threat vulnerabilities in npm applications and develop further strategies to solve this problem. \noindent \textbf{Approach}: To perform our investigation and answer who is responsible for the high threat vulnerabilities in applications, we use the same method to determine high threat vulnerabilities as presented in the first two RQs. For each high threat vulnerable dependency, we check the availability of a safe version of the package for the vulnerability at the analyzed snapshot time. Depending on such availability our analysis has one of two outcomes: \begin{itemize} \item \textbf{Package-to-blame:} if at the analyzed snapshot, no safe version has been provided by the package maintainers for a publicly known vulnerability. As the publication of a vulnerability comes after a period of 45 days, we consider the package maintainers the responsible for the high threat vulnerability in applications. \item \textbf{Application-to-blame:} if there is already a released safe version of the vulnerable package but the application continues to rely on an (old) version with a publicly known vulnerability. Application developers should monitor their dependencies and update to releases without known vulnerabilities, hence, we consider the application maintainers as responsible for the high threat vulnerability. \end{itemize} \begin{table}[tb!] \centering \caption{The percentage of vulnerabilities caused by the lack of available fix patch (Package-to-blame) vs caused by the lack of dependencies update (Application-to-blame), over the applications snapshot.} \label{RQ2T1} \begin{tabular}{l|r|r} \toprule \textbf{Snapshot} & \textbf{Package-to-blame} & \textbf{Application-to-blame} \\ \midrule \textbf{20\%} & {12.06\%} & {87.94\%} \\ \textbf{40\%} & {9.52\%} & {90.48\%} \\ \textbf{60\%} & 11.91\% & {88.09\%} \\ \textbf{80\%} & {12.43\%} &{87.57\%} \\ \textbf{100\%} & \textbf{9.24\%} & \textbf{90.76\%} \\ \bottomrule \end{tabular}% \end{table} \noindent \textbf{Results}: Table~\ref{RQ2T1} shows the percentage of high threat vulnerabilities based on our responsibility analysis. From Table~\ref{RQ2T1}, we observe that \textbf{for high threat vulnerabilities, the application is to blame in 90.76\% of the cases} at the last snapshot (i.e., 100\%). That means that in 9 out of 10 cases the high threat vulnerability had an available fix, but the applications did not update their dependencies to receive the last fix patch. Note that this observation holds over all snapshots, with percentages of application-to-blame cases varying from 87.94\% to 90.76\%. Therefore, and perhaps counter-intuitively, high threat vulnerabilities do not exist because packages have unfixed vulnerabilities, rather the real cause is the fact that these applications fail to keep up or at least to inform themselves well enough about a given dependency version. Hence, a major implication of our study is that application developers need to take updates pushed from their dependencies seriously, or at least actively track their dependencies, since those can lead to very serious effects. It is important to note that we do not argue about the severity of the vulnerabilities, but rather their likelihood threat of being exploited. Hence, a low severity vulnerability can be very dangerous if everyone knows how to exploit it (high threat level according to our classification). The inverse is also true in that a high severity vulnerability can have a very low chance of being exploited if no one knows about its existence (low threat level).\\ \begin{mdframed}[roundcorner=5pt,linewidth=0.5mm, linecolor=black] \sloppy \lipsum[0] \textbf{\textit{{Our findings show that applications not updating their dependencies, are the main cause of high threat (more than 87\%) vulnerabilities.}} } \end{mdframed}
{'timestamp': '2020-09-22T02:01:21', 'yymm': '2009', 'arxiv_id': '2009.09019', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09019'}
arxiv
\section{Post- vs.\ pre-update synchronization} \nk{Say a few words about post versus pre-update synchronization for AISTATS. Perhaps omitting the naive one in this comparison would make sense.} \section{Conclusion} \label{sec:conclusion} We have shown that naive deployment of LinUCB in two-stage recommender systems may result in suboptimal performance, and close to linear regret in extreme cases. The suboptimality is due to the mismatch between both the embeddings used by the ranker and the nominators, and the gap between the amount of training data the ranker has seen compared to the nominators. Both of these issues are inherent to the setting in which two-stage recommenders are typically deployed in industry, and thus pose important barriers to achieving a good exploration-exploitation trade-off. We have proposed a simple modification of the LinUCB algorithm based on communication of inferred statistics between the ranker and the nominators. Our algorithm can be implemented with minimal computational overhead, and achieves superior empirical results compared to the naive two-stage LinUCB implementation. While focusing solely on LinUCB, we suspect the `deadlock' problem identified in \Cref{sect:motivating_example} is pertinent to any exploration algorithm which in part selects its actions based on the level of uncertainty about them (e.g., all `optimism in the face of uncertainty' type algorithms, \citealp{lattimore2020bandit}). Since the principles motivating \Cref{eq:kl_sync} do not hinge on LinUCB in particular, we hope these issues could also be addressed by communication of statistics from the ranker. This preprint is based on a workshop version of our work. We plan to publish an extended version with additional experiments on real-world data and extended discussion in the near future. \section{Introduction} \label{sec:intro} Contemporary recommender systems are tasked with finding a small number of relevant items among millions or billions of candidates, personalized for each of hundreds of thousands or millions of users and their always changing needs, all of which has to happen in order of milliseconds so as not to negatively impact webpage loading speeds. One of the most widely used solutions to the problem are \emph{two-stage recommender systems} \citep{borisyuk2016casmos,covington2016deep,eksombatchai2018pixie} in which (i)~a set of \emph{computationally efficient} nominators narrows down the search from millions to only hundreds of items, and (ii)~the \emph{slower but more accurate} ranker selects and reorders a few items which are eventually served to the user. For example, a nominator can use a two-tower architecture \citep{yi2019sampling} and focus on a narrower set of features, whereas the ranker would rely on a more powerful model and consider additional features extracted from, e.g., ratings, specialized user and item attributes, or the number and type of past interactions with given user \citep{covington2016deep,ma2020off}. Importantly, the nominators are often heterogeneous both in terms of the size and type of the items from which they select the candidate items, and the algorithm used to select candidates ranging from simple associative rules to recurrent neural networks \citep{chen2019top}.\jh{I'm pretty sure I'm missing citations throughout; please do not hold back from adding as many as you can.} We will focus on nominators which utilize statistical learning methods in the two-stage setup as in the paper most relevant to our work \citep{ma2020off}. \citet{ma2020off} study off-policy learning for two-stage recommender systems where the goal is learning a good recommendation policy from the typically abundant logged data. The main proposal of \citeauthor{ma2020off}\ is to modify the nominator training objective by adding importance weights based on the ranker's probability of recommending each item. With adjustments facilitating gradient descent optimization, the authors show significant empirical improvements not only compared to a system trained without importance weighting, but also relative to nominators importance weighted only based on the past \emph{nominator} policy (ignoring the presence of the ranker). These results thus demonstrate that local optima of individual components do not translate to optimality of the system as a whole. Naturally, we can ask whether there are other aspects of the recommendation problem where optimal solutions for a single-stage system result in suboptimal performance when deployed in a two-stage system. We answer this question affirmatively in the case of \emph{exploration} by which we mean the task of learning an optimal recommendation policy under uncertainty in a sample efficient way. An effective exploration strategy then needs to balance greedy actions based on past interactions with exploratory recommendations targetting items about which there is little or no information. While many strategies have been proposed in the literature, ranging from more conservative ones like Boltzmann exploration \citep{daw2006cortical,chen2019top} to more optimistic contextual bandit algorithms \citep{lattimore2020bandit}, we will restrict our discussion to the popular LinUCB algorithm \citep{auer2002using,dani2008stochastic,li2010contextual} and the associated contextual bandit recommendation setup. A similar setup has been explored by \citep{ma2020off} as it is rich enough to exhibit many of the salient properties encountered in the real world, while abstracting away some of the complexities involved in deployment of large scale recommendation systems. \textbf{Contributions:} We (i)~show that a mismatch of feature mappings (architecture) and the amount of data seen (regularization) between LinUCB ranker and nominators can result in large, even linear regret; (ii)~demonstrate said effects and their dependence on the level of mismatch empirically on a toy dataset; and (iii)~propose a simple algorithm based on synchronization of inferred statistics between the ranker and the nominators which addresses the issue. We demonstrate the efficacy of our algorithm on simulated data. \section{Experimental results} \label{sec:experiments} \def0.24{0.24} \begin{figure*} \centering \textbf{Noise level 0.1:} $\hat{\theta}_0 \sim \mathcal{N} (\theta_\star, 10^{-2})$\\ \hrulespace{1mm} \hspace{2cm}$\gamma = 1$ \hfill $\gamma = 10$ \hfill $\gamma = 25$ \hfill $\gamma = 50$ \hspace{1.3cm}\phantom{} \\ \includegraphics[width=0.24\textwidth] {klv2-pseudo_1-noise_1e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_10-noise_1e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_25-noise_1e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_50-noise_1e-01-post} \\ \textbf{Noise level 0.2:} $\hat{\theta}_0 \sim \mathcal{N} (\theta_\star, 5^{-2})$\\ \hrulespace{1mm} \hspace{2cm}$\gamma = 1$ \hfill $\gamma = 10$ \hfill $\gamma = 25$ \hfill $\gamma = 50$ \hspace{1.3cm}\phantom{} \\ \includegraphics[width=0.24\textwidth] {klv2-pseudo_1-noise_2e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_10-noise_2e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_25-noise_2e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_50-noise_2e-01-post} \caption{Naive vs.\ synced 2-stage recommendation.}\label{fig:linUCB_toy} \end{figure*} \section{Setup} \label{sec:setup} \begin{figure} \centering \includegraphics[width=0.7\columnwidth]{setup.png} \caption{The two-stage recommendation setup.} \label{fig:setup} \end{figure} We consider a scenario in which a single item is to be recommended in each of the $T$ rounds. The recommendation problem is modeled in a contextual bandit setup where the individual items correspond to arms $a \in A$ (we thus also refer to items as arms or actions). For the first stage, we assume a fixed number of $N \in \mathbb{N}$ \emph{nominators}, each of which has access only to a fixed non-empty subset of arms $A_n \subseteq A$. At every round $t \in [T]$, each nominator observes contexts $x_{t, a}$ for all $a \in A_n$, and selects a \emph{single} action $a_{t, n}$. The ranker then chooses a \emph{single} final recommendation among the ones nominated in the first stage $a_t \in \{ a_{t, 1}, \ldots a_{t, N} \}$ \emph{based on the corresponding contexts}.\jh{Maybe cite Singla et al.\ (LEARNING WITH LEARNING EXPERTS) and Aggarwall et al. (CORALL) and explain that this is the main distinction of our setup from theirs?!} Both the ranker and the nominators can ultimately be updated using the reward $r_t$ obtained by pulling arm $a_t$ as well as all the revealed contexts $x_{t, a}$. This two-stage recommendation process is illustrated in \Cref{fig:setup}. We restrict our attention to the stochastic linear bandit setting \citep{abe1999associative,lattimore2020bandit}, and the LinUCB algorithm \emph{with ellipsoidal confidence sets} for both the ranker and the nominators \citep{auer2002using,dani2008stochastic}. The linear contextual bandit setting assumes existence of a fixed embedding for each context $\phi(x_{t , a})$ such that \begin{equation} \mathbb{E} [ r_t \, | \, x_{t, a_t} , a_t ] = \langle \phi(x_{t, a_t}) , \theta_\star \rangle \end{equation} for all $x_{t, a}$, $a_t$, and a fixed $\theta_\star \in \mathbb{R}^{d}$. Since $\theta_\star$ is assumed unknown, a \emph{single-stage} LinUCB estimates it by ridge regression with regularization parameter $\lambda > 0$ \begin{align} \begin{split}\label{eq:blr_posterior_params} \Sigma_t &\coloneqq \Bigl[ \lambda\, I_{d} + \sum_{i = 1}^t \phi(x_{i, a_i}) \phi(x_{i, a_i})^\top\Bigr]^{-1} \, , \\ \hat{\theta}_t &\coloneqq \Sigma_t \sum_{i = 1}^t r_i\, \phi(x_{i, a_i}) \, . \end{split} \end{align} The actions are then selected according to \begin{align}\label{eq:action_selection} a_{t+1} &\in \argmax_{a \in A}\, \text{UCB}_{t+1} (a) \, , \end{align} where as in \citep[p.~239--241]{lattimore2020bandit} \begin{align*} \text{UCB}_{t+1} (a) &\coloneqq \langle \phi(x_{t, a}), \hat{\theta}_t \rangle + \sqrt{\beta_t}\, \| \phi(x_{t, a}) \|_{\Sigma_t} \, , \\ \sqrt{\beta_t} &\coloneqq \sqrt{\lambda} + \sqrt{ 2 \log t + d \log \left( \frac{d \lambda + t}{d \lambda} \right) } \, . \end{align*} LinUCB with such $\beta_t$ achieves near optimal regret \begin{align}\label{eq:regret_definition} \begin{aligned}[c] R_T &\coloneqq \mathbb{E} \left[ \sum_{t=1}^T r_{t,\star} - r_t \right] \\ &= \sum_{t=1}^T \langle \theta_\star , \phi(x_{t, a_{t, \star}}) - \mathbb{E} [\phi(x_{t, a_t})] \rangle \, , \end{aligned} \end{align} when the reward noise is sub-Gaussian \citep{dani2008stochastic,lattimore2020bandit}, where \begin{equation} a_{t, \star} \coloneqq \argmax_{a \in A} \langle \theta_\star , \phi (x_{t, a}) \rangle \, , \end{equation} $r_{t, \star}$ is the reward obtained by choosing $a_{t, \star}$, and the expectation is taken with respect to the randomness of the rewards and the policy (uniform tie breaking). Importantly for our later development, LinUCB can be interpreted in Bayesian terms in the following sense: the current mean and covariance estimates $\theta \sim \mathcal{N}(\hat{\theta}_t , \Sigma_t)$ correspond to the posterior distribution obtained by combining the prior $\mathcal{N}(0, \lambda^{-1} I_{d} )$ with the likelihood $r_{t , a} \sim \mathcal{N} (\langle \phi(x_{t, a}), \theta \rangle , 1)$. Since \begin{equation} \langle \phi(x_{t, a}), \theta \rangle \sim \mathcal{N} \bigl(\langle \phi(x_{t, a}), \hat{\theta}_{t-1} \rangle, \| \phi(x_{t, a}) \|_{\Sigma_{t-1}}\bigr)\, , \end{equation} the selection rule employed by LinUCB can be viewed as selecting the action with the highest posterior $\Phi (\sqrt{\beta_t})$-th quantile, where $\Phi$ is the cumulative distribution function (CDF) of the standard normal distribution. In other words, the maintained estimates define a \emph{confidence set} for the true parameter $\theta$, and LinUCB chooses the best action compatible with this set. As mentioned, we will assume that each of the nominators and the ranker use the LinUCB algorithm also in the two-stage setup.\footnote{While not in line with the usual heterogeneity of the nominator algorithms, we believe this setting captures much that is salient to the interaction between general simultaneously learning ranker and nominators. It also goes one step beyond the setup in \citep{ma2020off} by considering the existence of more than one nominator.} Since the nominators often need to rapidly sift through millions of items, we assume \emph{only} the ranker has access to the true but expensive to compute embeddings $\phi$, while each nominator $n \in [N]$ uses computationally cheaper embeddings $\phi_n(x) \in \mathbb{R}^{d_n}$. In the rest of this document, we use the term \emph{naive} two-stage LinUCB to refer to the algorithm where each nominator \emph{independently} maintains its own estimates $\hat{\theta}_{n,t}$, $\Sigma_{n,t}$ defined as in \Cref{eq:blr_posterior_params} with $\phi$ replaced by $\phi_n$, nominate actions analogously to \Cref{eq:action_selection}, and update their posterior \emph{only} with $r_t$ and $\phi_n (x_{t, a_t})$, where we recall $a_t$ need not equal $a_{t, n}$. Moreover, the ranker independently maintains its own estimates $\hat{\theta}$, $\Sigma_{t}$ used to select the item ultimately served to the user. In the next section, we will first show on a simple example that such independently maintained uncertainty estimates lead to suboptimal global performance. We then propose a solution based on synchronization of the upper bound estimates $\text{UCB}_t (a)$ used in \Cref{eq:action_selection} between the ranker and the nominators. \section{Coordinated exploration} \label{sec:algo} To understand when the \emph{naive} two-stage LinUCB implementation does not work, it is useful to know when it does. In particular, consider the case when all the nominators are allowed to use the \emph{same features} as the ranker $\phi_n = \phi$, and employ the \emph{same prior} $\mathcal{N} (0, \lambda_n^{-1} I_d)$ with $\lambda_n = \lambda$. It is not hard to see that in this case $\hat{\theta}_{n, t} = \hat{\theta}_t$ and $\Sigma_{n, t} = \Sigma_{t}$ for all $t \in [T]$, and thus each nominator selects the same action as would be selected by the ranker constrained to the same action pool $A_n$. Since $\max \{ c_1, \ldots, c_k \} = \max \{ \max \{ c_1 , \ldots , c_{k_1} \} , \ldots , \max \{ c_{k_{N - 1} + 1} , \ldots , c_k \} \}$ for any partition of $c_1, \ldots , c_k \in \mathbb{R}$, this then implies that the naive two-stage system behaves \emph{exactly} as a single-stage LinUCB with access to all actions would. Because we know single-stage LinUCB is close to optimal, the above implies that any potential increase in regret must come from either the already discussed mismatch of the embeddings inherent to two-stage systems, or mismatch of the prior. The latter is then most often caused by the ranker being deployed for much longer time and thus better trained. Such a scenario is common in many contemporary industrial practices \citep{covington2016deep,ma2020off}, and can be modelled in our setup by using a ranker prior with lower initial uncertainty then the nominators. As demonstrated next, naive two-stage LinUCB is poorly equipped to handle such discrepancies. \def0.24{0.24} \begin{figure*} \centering \textbf{Noise level $\sigma_{\theta_\star} = 0.1$:} $\hat{\theta}_0 \sim \mathcal{N} (\theta_\star, 10^{-2})$\\ \hrulespace{0.5mm} \vspace{1mm} \hspace{2cm}$\gamma = 1$ \hfill $\gamma = 10$ \hfill $\gamma = 25$ \hfill $\gamma = 50$ \hspace{1.3cm}\phantom{} \\ \includegraphics[width=0.24\textwidth] {klv2-pseudo_1-noise_1e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_10-noise_1e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_25-noise_1e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_50-noise_1e-01-post} \\ \textbf{Noise level $\sigma_{\theta_\star} = 0.2$:} $\hat{\theta}_0 \sim \mathcal{N} (\theta_\star, 5^{-2})$\\ \hrulespace{0.5mm} \vspace{1mm} \hspace{2cm}$\gamma = 1$ \hfill $\gamma = 10$ \hfill $\gamma = 25$ \hfill $\gamma = 50$ \hspace{1.3cm}\phantom{} \\ \includegraphics[width=0.24\textwidth] {klv2-pseudo_1-noise_2e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_10-noise_2e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_25-noise_2e-01-post} \hfill \includegraphics[width=0.24\textwidth] {klv2-pseudo_50-noise_2e-01-post} \caption{Naive vs.\ synchronized 2-stage recommendation. Setup described in \Cref{sect:motivating_example}. Expected regret and its 2-sigma confidence intervals were estimated over 400 runs. The level of pretraining of the ranker $\gamma$ has outsized effect on the naive but not the synchronized two-stage LinUCB, overcoming the `deadlock' effect.}\label{fig:linUCB_toy} \end{figure*} \begin{algorithm}[tbp] \caption{\label{alg:sync_linUCB}Two-stage {\color{SteelBlue}synchronized} LinUCB. Here $\phi_t \coloneqq \phi(a_t)$ and $\phi_{n, t} \coloneqq \phi(a_{n, t})$ for all $n, t$.} \footnotesize \textbf{Inputs:} $\hat{\theta}_0 \, , \Sigma_0 \, , (\beta_{t})_{t} \, ;\; \forall n \colon \hat{\theta}_{n , 0} \, , \Sigma_{n, 0} , (\beta_{n , t})_t$ \\ \For{$t=1,2,\ldots, T$}{ $\forall n \colon a_{n, t} \gets \argmax_{a \in A_n} \text{UCB}_{n, t} (a)$ \\ $a_t \gets \argmax_{a \in \{ a_{1, t}, \ldots , a_{N, t} \}} \text{UCB}_{t} (a)$ \\ $\Sigma_t^{-1} \gets \Sigma_{t-1}^{-1} + \phi_t \phi_t^\top$ \\ $\hat{\theta}_t \gets \Sigma_t \left(\Sigma_{t-1}^{-1} \hat{\theta}_{t-1} + r_t \phi_t\right)$ \\ \For{$n=1, 2, \ldots, N$} { $\Sigma_{n, t}^{-1} \gets \Sigma_{n, t-1}^{-1} + \phi_{n,t} \phi_{n, t}^\top$ \\ $\hat{\theta}_{n, t} \gets \Sigma_{n, t} \left(\Sigma_{n, t-1}^{-1} \hat{\theta}_{n, t-1} + r_t \phi_{n, t}\right)$ \\ {\color{SteelBlue} \uIf{$\| \phi_n (a_{n, t}) \|_{\Sigma_{n, t}} > \| \phi (a_{n, t}) \|_{\Sigma_{t}}$}{ $\hat{\theta}_{n, t} \gets \hat{\theta}_{n, t} + \frac{\langle\hat{\theta}_{t}, \phi_{t}\rangle - \langle \hat{\theta}_{n, t}, \phi_{n, t}\rangle}{\|\phi_{n, t}\|_{\Sigma_{n, t}}^2}\Sigma_{n, t}\phi_{n, t}$ \\ $\Sigma_{n, t}^{-1} \gets \Sigma_{n,t}^{-1} + \bigl( \frac{1}{\|\phi_t\|_{\Sigma_{t}}^{2}} - \frac{1}{\|\phi_{n, t}\|_{\Sigma_{n, t}}^{2}} \bigr) \phi_{n, t}\phi_{n, t}^{\top}$ } } } } \end{algorithm} \subsection{Motivating example}\label{sect:motivating_example} Consider a setting with \emph{only one} context, two nominators, three actions split between them as $A_1 = \{ a_1 \}$, $A_2 = \{ a_2, a_3 \}$, $\phi$ returning \emph{one-hot encodings} of the actions, and $\phi_n = \phi$ for all nominators. The expected rewards from $a_1$ to $a_3$ are $[1/2, 1/4, 3/4] = \theta_*$ (one-hot action encodings), and observed rewards are generated by adding i.i.d.\ Gaussian noise $\mathcal{N} (\theta_\star, 10^{-2} I_3)$. The ranker's parameters are initialized to $\hat{\theta}_0 \sim \mathcal{N} (\theta_\star, \sigma_{\theta_\star}^2 I_3)$, and $\Sigma_{0} = (\lambda + \gamma)^{-1} I_{3}$ where $\gamma$ represents how many more samples per action the ranker has seen at $t = 1$ compared to the nominators. For both nominators $n \in [2]$, we take $\hat{\theta} = 0$, and $\Sigma_{n, 0} = \lambda_n^{-1} I_{3}$ with regularization parameter (prior precision) $\lambda_n = \lambda = 10^{-3}$. To see what can go wrong in this scenario, consider the extreme case $\sigma_{\theta_\star}^2 = 0$ and $\gamma \gg 0$, i.e., the ranker has seen enough data to essentially recover the true parameter. Since $A_1 = \{ a_1 \}$, such a ranker always picks $a_3$ (the best action) when $a_{2, t} = a_3$, and $a_1$ otherwise. In the naive implementation, this results in a \emph{`deadlock'} where the second nominator's uncertainty about $a_2$ never decreases, leading it to mostly nominate $a_2$ over $a_3$, entailing \emph{linear} regret. While the extreme case may be rare in practice, \Cref{fig:linUCB_toy} shows the effect remains significant even when the ranker is not fully trained, i.e., $\sigma_{\theta_\star} > 0$, and $\gamma > 1$ but not overly large. \subsection{Synchronized two-stage LinUCB} The deadlock observed in the previous section is due to a lack of communication of uncertainty between the ranker and the nominators. Since the computational constraints inherent to the two-stage setup entail distinct embedding functions, the issue cannot be addressed by simply setting nominator parameters to those of the ranker. However, because action selection only depends on the estimated marginal quantiles of the \emph{rewards}, we can update the nominator's estimates based on the reward statistics computed by the ranker. We propose to \emph{synchronize} each nominator $n$ in the rounds where $\| \phi_n (a_{n, t}) \|_{\Sigma_{n, t}} > \| \phi (a_{n, t}) \|_{\Sigma_{t}}$, i.e., when the nominator is more uncertain about its selected action than the ranker (the cause of the `deadlock' in \Cref{sect:motivating_example}). In particular, we want to minimally adjust the nominator posterior so that it matches the ranker's mean and variance which fully determine $\text{UCB}_{n, t}(a_{n, t})$ (see \Cref{sec:setup}). Defining the minimality in terms of Kullback-Leibler (KL) divergence, this can be achieved by solving the constrained optimization problem: \begin{align}\label{eq:kl_sync} \min_{m, S} \quad & \text{KL}\left(\mathcal{N}\left(m, S\right)\;\middle \|\;\mathcal{N}\left(\hat{\theta}_{n, {t}}, \Sigma_{n, {t}}\right)\right) \\ \text{subject to} \quad &\langle m, \phi_{n} (a_{n, t}) \rangle = \langle \hat{\theta}_{t}, \phi (a_{n, t}) \rangle \, , \qquad\,\, {\color{gray}\text{\small(mean)}} \nonumber \\ &\|\phi_n (a_{n, t})\|_{S} = \|\phi (a_{n, t})\|_{\Sigma_{t}} \, , \quad {\color{gray}\text{\small(covariance)}} \nonumber \end{align} When synchronization is performed after the usual update, the solution to \Cref{eq:kl_sync} gives us \Cref{alg:sync_linUCB}. Note that the selected KL divergence penalizes overdispersion compared to the previous distribution, meaning the resulting replacement for $\mathcal{N}(\hat{\theta}_{n, {t}}, \Sigma_{n, {t}} )$ should not have more uncertainty. Furthermore, if we modify \Cref{alg:sync_linUCB} to perform the synchronization before the usual update---i.e., swap the black and blue lines within the inner-most for-loop and replace the if-condition by $\| \phi_n (a_{n, t}) \|_{\Sigma_{n, t-1}} > \| \phi (a_{n, t}) \|_{\Sigma_{t-1}}$---we arrive at an algorithm that only uses quantities already computed during selection of $a_{n, t}$ and $a_t$, minimizing the additional computation required; in experiments, both versions of the algorithm performed essentially the same, which we show in an example setting in \Cref{fig:post_vs_pre}. \nk{For a future version we should probably only show the compared lines (not naive) and make them somewhat transparent. Or perhaps even show absolute difference on log scale?} \begin{figure} \centering \includegraphics[width=0.8\columnwidth]{klv2-pseudo_50-noise_2e-01-full} \caption{Comparison of post- vs.\ pre-update synchronization for a noise level of $0.2$ and $\gamma = 50$. In this setting, the line for pre-update synchronization is barely visible, because it is covered by the line for post-update synchronization.} \label{fig:post_vs_pre} \end{figure} Finally, let us consider our synchronized two-stage LinUCB algorithm in the context of the motivating example from \Cref{sect:motivating_example}. Because we assumed $\phi = \phi_n$ are one-hot encodings of the actions, we see that the ranker variance for an action $j \in [3]$ at time $t$ is $\| \phi(a_j) \|_{\Sigma_t}^2 = (\lambda + \gamma + n_{tj})^{-1}$ where $n_{tj}$ is the number of times the ranker selected $a_j$. The \emph{first} time a nominator select $a_j$, its variance before the round update will be $\| \phi_n(a_j) \|_{\Sigma_{n, t}}^2 = (\lambda + n_{tj})^{-1}$.\footnote{Since we allow the pools $A_n$ to be overlapping, $n_{tj}$ could generally be greater than zero here. This is not the case for the example from \Cref{sect:motivating_example} though.} Inspecting the synchronization update for $\Sigma_{n, t}^{-1}$ in blue (\Cref{alg:sync_linUCB}), the new value for the $(jj)$\textsuperscript{th} entry of $\Sigma_{n, t}^{-1}$ amounts to \begin{align*} \underbrace{\lambda + n_{tj}}_{\Sigma_{n, t}^{-1}} + \underbrace{\lambda + \gamma + n_{tj}}_{ \| \phi(a_j) \|_{\Sigma_t}^{-2} } - \underbrace{(\lambda + n_{tj})}_{ \| \phi_n(a_j) \|_{\Sigma_{n, t}}^{-2} } = \| \phi(a_j) \|_{\Sigma_t}^2 \, , \end{align*} while the other variances will remain as in $\Sigma_{n, t}$ at time $t$. Since an analogous claim holds for the mean $\hat{\theta}_{n, t}$, we conclude the synchronization update ensures the posteriors of the ranker and the nominators match after each nominator \emph{selected} (but not necessarily seen \emph{recommended}) each $a \in A_n$ exactly once. Because the posteriors never diverge after they are fully matched, our algorithm starts behaving like single-stage LinUCB from thereon, which we know is near optimal for the task. This is confirmed in \Cref{fig:linUCB_toy} where the more pretrained the ranker is (higher $\gamma$), the better the synchronized and the worse the naive LinUCB do. \subsubsection*{\bibname}} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{hyperref} \usepackage{url} \usepackage{amsfonts,amssymb,amsthm,amsmath} \usepackage{nicefrac} \usepackage{microtype} \usepackage[dvipsnames]{xcolor} \usepackage{graphicx} \usepackage{bm} \usepackage[inline]{enumitem} \usepackage[noend]{algorithm2e} \usepackage{tikz} \usetikzlibrary{decorations.pathmorphing,decorations.shapes} \usepackage{etoolbox} \usepackage{mathtools} \usepackage[disable]{todonotes} \usepackage{cleveref} \input{macros} \graphicspath{{./fig/}} \setitemize{leftmargin=*} \setlist{nosep} \begin{document} \runningauthor{Hron, Krauth, Jordan, Kilbertus} \twocolumn[ \aistatstitle{Exploration in two-stage recommender systems} \aistatsauthor{Jiri Hron${}^{1,*}$, Karl Krauth${}^{2,*}$, Michael I.~Jordan${}^2$, Niki Kilbertus${}^{1,3}$} \aistatsaddress{${}^1$University of Cambridge, ${}^2$UC Berkeley, ${}^3$Max Planck Institute for Intelligent Systems } ] \begin{abstract} \input{content/00abstract} \end{abstract} \input{content/01intro} \input{content/02setup} \input{content/03algo} \input{content/05conclusion}
{'timestamp': '2020-09-21T02:18:13', 'yymm': '2009', 'arxiv_id': '2009.08956', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08956'}
arxiv
\section{Introduction} \if2 1 \vspace{-10pt} \else \fi \subsection{Industrial Wireless Control} Wireless \gls{iiot} in the next generation of industrial control systems require communications with sub-ms, extreme low latency and ``cable-like" ultra-high reliability. For a large-scale network of sensor and actuator devices in factory automation applications, different wireless transmission schemes have recently been proposed to exploit spatial and multi-user diversity gain in the network. The challenge in this new paradigm of wireless communication is that the design requires guaranteed service to all, including the \emph{weakest} user, as opposed to the classic paradigm of network design that targets average performance. Traditionally, such industrial automation requirements are realized on the factory floor through wired communications e.g., using fieldbus and Ethernet based solutions. The wired solutions, however, are considered to be cumbersome and expensive in many applications. Moreover, the future industrial automation targets a highly flexible and dynamic environment of production stations that support robotic mobility to be able to seamlessly re-arrange according to production requirements \cite{Cena:2008,Bennis:2018,Harish:6G2020}. As a result, there is an increased desire to replace wired communication systems for factory automation with wireless alternatives to reduce bulk as well as installation and maintenance costs \cite{Gungor:2009}. This calls for innovative solutions in constrast to existing wireless technologies that are designed for delay tolerant consumer solutions, making them unsuited for industrial automation \cite{weiner2014design}. In the era beyond the \gls{5g} mobile networks, \gls{urllc} is promised to deliver such demanding requirements using the advanced physical layer technologies, including communications in \gls{mmwave} and \gls{uwb} spectrum access \cite{Gilberto:2018,mazgula2020ultra}, accompanied by the improvements in network architecture in bringing the cloud close to the edge to reduce latency, and using machine learning for a fast and reliable prediction of channels and traffic~\cite{Bennis:2020arxiv}. \if2 1 \vspace{-10pt} \else \fi \subsection{Prior Work} \if2 1 \vspace{-5pt} \else \fi To fulfill the requirements of ultra-high reliability within a stringent latency constraint, different diversity techniques are suggested in the literature. Time and frequency diversity techniques \cite{zand2012wireless} as well as spatial diversity and multi-user cooperation \cite{swamy2015cow} can reduce the required reliability-achieving \gls{snr}. For example, the importance of multi-antenna receive diversity in improving reliability and coverage was pointed out in \cite{brahmi2015gc}. In low-latency industrial automation applications, the cycle time is shorter than the fading channel coherence time, which rules out viability of \gls{arq}-based time diversity techniques~\cite{Khosravirad:2017}. In \cite{swamy2015cow}, it is shown that relying solely on frequency diversity to achieve $10^{-9}$ error rate requires impractically high \gls{snr} values in realistic channel conditions. It is further shown that multi-user diversity, even in low or moderate \gls{snr} regime, can achieve ultra-reliability. Incidentally, increasing transmit diversity by engaging multiple transmitting \glspl{ap}, similar to \gls{comp} technology \cite{randa:2012}, is also not a straightforward path to reliability. In fact, in the absence of \gls{csi} at the transmitter, transmit diversity falls dramatically short of achieving high reliability as discussed in \cite{Rebal:2018}. The study in \cite{Rebal:2018} further shows that by using \gls{csi} to adapt transmission rate at the transmitter, the inherent multi-user diversity gain of a large size network can be exploited to achieve high reliability. To that point, the cooperative transmission in \cite{swamy2015cow} attempts to exploit the full potential of wireless network by enabling cooperative device-to-device relaying to improve reliability. The focus of \cite{swamy2015cow} is to devise transmission schemes that do not require transmitter \gls{csi}. Such \gls{csi}-agnostic schemes are not able to take the differences in the instantaneous channel conditions into account, resulting in a sub-optimal and conservative choice of transmission rate determined by the worst user's conditions, and loss of spectral efficiency. On the other hand, in a multi-user wireless network, the overhead for acquiring \gls{csi} can grow large as the size of the network grows. The works in \cite{8259329} and \cite{Rebal:2018} study the impact of such overhead. Particularly, \cite{8259329} considers the overhead of \gls{csi} acquisition when communicating with small packets, thus characterizing the error performance under the finite block length regime. System-level simulations for multi-user networks under \gls{urllc} requirements is highly time-consuming and complex. We acknowledge that several works in the literature have addressed and dealt with those complexities, including \cite{Klaus:2018system,7247339}, and have provided insightful conclusions for system design of cellular networks with extreme reliability requirements. \if2 1 \vspace{-10pt} \else \fi \subsection{Exploiting Diversity ``On-demand''} \if2 1 \vspace{-5pt} \else \fi Spatial diversity transmission, as the most dependable source of achieving high reliability when communicating over fading channels, is a viable solution for reliability that may be achieved by using multiple transmission points or antennas. In low cost deployments, however, it is desirable to have a small number of spatially distributed, simple \glspl{ap} with limited number of antennas. Spatial diversity transmission, however, needs to also exploit multi-user diversity stemming from the fact that several users with different channel conditions are part of the communication system. On the other hand, cooperative relaying among users (as proposed in \cite{swamy2015cow}) essentially also achieves spatial diversity through multi-user diversity. The core question this paper tries to answer is \emph{how to use channel awareness at the transmitter to efficiently allocate radio and cooperation resources, and to exploit diversity according to the instantaneous needs of the users}. We introduce a transmission protocol that is capable of identifying users' channel strength and allows for exploiting different sources of diversity, \emph{on demand}. We propose to adapt the transmission rate for users with strong channel from the \glspl{ap} according to their channel, while exploiting cooperative diversity for the remaining users with weak channel. This introduces a robust way of deploying the \emph{emergency} resources of network cooperation, only for the devices that absolutely need them. We study the improvements offered by this protocol on the operating spectral efficiency and the minimum required \gls{snr} for reliability. In high \gls{snr}, this impacts the slope of the outage probability curve and improves diversity order by deploying network-device cooperation for the poor links. Meanwhile, it brings better multiplexing gain by smartly exploiting the difference in channel conditions. \if2 1 \vspace{-15pt} \else \fi \subsection{Channel Estimation in Wireless Networks} \if2 1 \vspace{-5pt} \else \fi We assume a general transmission framework where data is accompanied with proper amount of pilot signal in all transmissions \cite{hassibi03}. The estimated channel at a receiving node can then be reported back to the transmitting node, e.g. in form of \gls{cqi}. With an adequate frequency of \gls{cqi} updates, transmitter can improve resource utilization efficiency by adapting the transmission attributes to the channel. In fact, such an approach is widely adopted in multi-user cellular technologies such as the \gls{lte} and \gls{nr}. More interestingly, by assuming channel reciprocity in \gls{tdd} transmission mode for the industrial wireless control problem of our interest with isochronous traffic pattern in the \gls{dl} and the \gls{ul} directions, \gls{cqi} acquisition requires no feedback exchange between the nodes. Instead, \gls{cqi} can be estimated when the node performs channel estimation while in receiving mode and can be used when the node switches to transmit mode. In this paper, we adopt this assumption and present a new transmission protocol that utilizes channel state information to best exploit sources of diversity in the wireless network. \if2 1 \vspace{-15pt} \else \fi \subsection{Contributions} \if2 1 \vspace{-5pt} \else \fi The objective of this paper is to design an ultra-reliable transmission scheme for extreme low-latency applications which uses minimal control signaling for scheduling. To this end, we aim to exploit full spatial and multi-user diversity potential of the network in favor of system reliability and spectral efficiency. Our contributions are summarized as follows. \if2 1 \vspace{-5pt} \else \fi \begin{itemize} \item We identify and analyze different sources of diversity gain for ultra-reliable wireless communications in an industrial wireless control network. A network with multiple fully-connected \glspl{ap} is assumed where the \glspl{ap} coordinate their transmissions similar to \gls{comp}. We formulate the achievable multi-user and multi-antenna diversity gain in the low-latency regime, and propose a new scheme for exploiting those in favor of reliability and efficiency. \item A new ultra-reliable transmission scheme dubbed \gls{andcoop} that exploits different sources of diversity in the network is introduced. The proposed scheme uses the approximate knowledge of \gls{csi} to categorizes the devices into two groups, namely, group of devices with \emph{strong} instantaneous channel, and the group of devices with \emph{weak} channel. The two groups are then scheduled in separate scheduling phases: first, each of the strong devices receives its \gls{dl} message with a unique transmission rate that is adapted to its instantaneous channel state; next, the second group of devices are scheduled with a fixed rate through two-hop cooperative transmission where all the devices in both groups can potentially contribute in as \gls{df} relays. \item Reliability performance of the proposed transmission scheme is analytically formulated, in order to characterize the system outage probability. The analysis is then extended to diversity-multiplexing trade-off, where closed-form formulations for the achievable diversity order are derived. We further formulate the optimization problem of allotting time between the two scheduling phases and provide numerical solutions to the optimization problem. \item Comprehensive and detailed system-level simulations are reported to identify guidelines for optimal system design. The proposed protocol is compared against the existing transmission protocols in the literature. The numerical analysis demonstrates significant concurrent improvement in spectral efficiency (approximately 0.5 \gls{bpcu} per \gls{ap} antenna) and reliability. Alternatively, under fixed spectral efficiency setup, the proposed algorithm acheives the desired reliability at significantly smaller transmit power (around 15 dB improvement compared to the existing schemes), while utilizing around $40\%$ less relay nodes' energy, which in turn reduces the interference footprint. Moreover, the impact of \gls{csi} estimation error is carefully studied, suggesting that the proposed \gls{andcoop} transmission scheme consistently reduces the impact of such error on system reliability, thanks to the strategy of grouping devices according to channel quality. We identify significant potential in cost reduction for the future private industrial wireless control network, thanks to the improved operation efficiency using the proposed \gls{andcoop} scheme. \end{itemize} \if2 1 \vspace{-15pt} \else \fi \subsection{Organization of the Paper} \if2 1 \vspace{-5pt} \else \fi The sequence of this paper is as follows: in \secref{Sec:ProblemSetup} we present the problem description and the assumed network setup; further, we provide motivations for designing a new ultra-reliable transmission scheme; in \secref{Sec:Model} the proposed channel-aware \gls{urllc} solution is presented and analyzed for outage probability and diversity order; \secref{Sec:Results} presents and discusses the numerical analysis of the proposed scheme; and finally, \secref{Sec:Conclusion} covers the concluding remarks. \section{Problem Setup} \label{Sec:ProblemSetup} \begin{figure}[t] \begin{center} \psfrag{u}[c][c][0.59]{wireless link} \psfrag{v}[c][c][0.59]{wired link} \psfrag{x}[c][c][0.59]{wireless connected} \psfrag{w}[c][c][0.59]{devices} \psfrag{y}[c][c][0.59]{access points} \psfrag{z}[c][c][0.59]{controller} \includegraphics[width=0.8\columnwidth,keepaspectratio]{topology.eps} \caption{Wireless network model for industrial wireless control. Wireless devices with \emph{weak} channel conditions (highlighted) are identified for a two-hop communication.} \label{Fig:Model} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} In this section, we first describe the communications system model of interest and highlight the main system assumptions we use in our analysis. Then, we discuss exploiting diversity gain a multi-user wireless network under the paradigm of ultra-reliable communications to motivate our design target in exploiting full diversity potential of the network for industrial wireless control. \if2 1 \vspace{-10pt} \else \fi \subsection{System Model} \paragraph*{Network} $N$ devices are scattered on a factory floor and are wirelessly connected with the controller \glspl{ap}. \figref{Fig:Model} illustrates the considered network where a controller is wired to $M$ fully synchronized \glspl{ap}. This paper considers a \gls{comp} setting where all \glspl{ap} are synchronized and they coordinate their transmission attributes for transmission to every device. All the communicating nodes have a single antenna for transmission and reception. Every device expects an independent $B$ bytes of data to be delivered every $T$ seconds over a bandwidth of $W$ Hertz. We use $\eta = \frac{N B}{T W}$, measured in \gls{bpcu}, to denote the overall spectral efficiency of the system. Let $\mathscr{A} = \set{1,2,\dots,M}$ denote the set of \glspl{ap}, where $M = \card{\mathscr{A}}$ is the number of \glspl{ap}. Similarly, let $\mathscr{D} = \set{1,2,\dots,N}$ be the set of device IDs where $N = \card{\mathscr{D}}$. Throughout the paper, we reserve the letter $R$ to denote transmit rate measured in \gls{bps}. \paragraph*{Channel dynamics} Wireless channels linking every \gls{ap}-device and device-device pair are assumed to undergo independent frequency-flat Rayleigh fading. We note that this assumption is adopted for analytical tractability, although measurement campaigns for industrial environments show frequency-selectivity over wide bandwidth \cite{nist1951,rapp91}. We assume a setting where each time-cycle experiences a constant channel which fades independently from one cycle to the next. Let $\ha{i}{j}$ and $\ra{i}{j}$ denote the channel fade random variable and the average received \gls{snr} (which includes the effect of path loss and is averaged with respect to fading distribution) of the transmission from \gls{ap} $i$ to device $j$, where $i \in \mathscr{A}$ and $j \in \mathscr{D}$. We use $\ga{i}{j} = \ra{i}{j}|\ha{i}{j}|^2$ to denote the instantaneous received \gls{snr}. Similarly, let $\hd{k}{j}$, $\rd{k}{j}$ and $\gd{k}{j}$ denote the same variables for the link from device $k$ to device $j$, where $k, j \in \mathscr{D}$. Note that $\ra{i}{j} = P_a / (W \cdot \sigma_0)$ and $\rd{k}{j} = P_d / (W \cdot \sigma_0)$, where $P_a$ and $P_d$ denote the transmit power of an access point and a device, respectively, and $\sigma_{\tr{o}}$ denotes \gls{psd} of the \gls{awgn}. \paragraph*{Outage model} A device is said to be in outage if the transmission rate $R$ exceeds the instantaneous channel capacity, and is considered successful otherwise. We assume distributed space-time coding that collects spatial diversity through summation of the received signal powers from all transmitters. Therefore, with $\mathscr{C}_j$ denoting the set of nodes cooperatively transmitting with rate $R$ to node $j$ over bandwidth $W$, the transmission fails if \begin{align}\label{Eq:linkoutage} W \log \left( 1 + \sum_{i \in \mathscr{A} \cap \mathscr{C}_j}\ga{i}{j} + \sum_{k \in \mathscr{D} \cap \mathscr{C}_j}\gd{k}{j} \right) < R. \end{align} The expression in \eqref{Eq:linkoutage} implicitly assumes long block-length transmission. While admittedly, the transmission of small packets in line with what is typically expected in \gls{urllc} scenarios and also suitable for the block-fading model challenges the assumption that the packets are long enough for \eqref{Eq:linkoutage}, we note that the impact of such assumptions can be further evaluated by adopting the finite block-length regime outage models \cite{PolyanskiyFBL:2010}. More importantly, the recent findings in \cite{6802432} suggest that in a fading channel, the effect of outage dominates the effect of short block-length, so the outage capacity is in fact a fair substitute for the finite block-length fundamental limits. For this reason, the rest of this paper focuses on the outage model in \eqref{Eq:linkoutage}. Similar to the previous works in \cite{Rebal:2018TCOM,swamy2015cow,Khosravirad:vtc2019}, we analyze \emph{system outage probability} as the key performance metric, denoted by $\mathbb{P}_\tr{\tiny{out}}(.)$ and defined as the probability that at least one device fails to decode its own message at the end of time-cycle $T$. This is a more appropriate measure for reliability of communication in an industrial wireless control setup compared to e.g., average outage probability across devices. The argument is that the industrial wireless control system may only continue its operation when all devices follow the controller instructions, and the system fails if at least one devices fails. Note that $\mathbb{P}_\tr{\tiny{out}}(.)$ is a function of the channel random variables, as well as the parameters of the system. Moreover, such definition complies with the joint definition of reliability and latency requirements in the context of \gls{urllc}. In essence, a \gls{urllc} system satisfies its requirements only if it can guarantee the desired reliability level \emph{within} the desired latency budget \cite{3gpp38913}. Therefore, in this work, instead of the statistics of the experience delay, we are interested in the outage probability within a constrained latency of $T$ seconds. \paragraph*{Diversity-multiplexing} It is widely accepted that the end goal of \gls{urllc} systems is to increase reliability, and therefore, the system outage probability curve is the natural benchmark for performance evaluation. However, the true performance of such system can only be evaluated if data rate is monitored alongside the reliability. Thanks to the choice of \emph{system outage probability} (described above) to represent error rate in the system model, the diversity gain can be captured as the slope at which the error rate decays in the high \gls{snr} regime. Moreover, we define the multiplexing gain $r$ as the ratio at which the payload size per device $B$ increases with transmit power $P_t$ in log scale, i.e., $B \propto r \log P_t$. Thus, the dual benefits can be captured by the diversity-multiplexing tradeoff in the high \gls{snr} regime, where similar to \cite{Zhao:2007diversity,Tse2003divmux}, we say that a diversity gain $d(r)$ is achieved at multiplexing gain $r$, if $\eta = r \log P_t$ and, \begin{align}\label{Eq:dive_order_def} d(r) = - \lim_{P_t \rightarrow \infty} \frac{\log \mathbb{P}_\tr{\tiny{out}}(r \log P_t)}{\log P_t}, \end{align} thus capturing the tradeoff between data rate increase (i.e., $r$) and diversity order, in high \gls{snr}. \input{table.tex} \paragraph*{Channel estimation} We assume instantaneous \gls{csi} of the \gls{ap}-device pairs are present at the controller in the form of link strength $\ga{i}{j}$'s, which doesn't require the knowledge of channel phase. This can be for instance provided by frequent transmission of uplink pilot sequences by the devices similar to \gls{srs} in \gls{lte}. Each \gls{ap} estimates its channel from all the devices, using those pilot sequences. The \gls{csi} will be used to identify groups of devices with \emph{strong} and \emph{weak} channel conditions and to adapt the transmission rate for the former group. The variance of channel estimation error can be arbitrarily minimized by increasing the number of pilot sequences and transmit power of the pilots \cite{hassibi03,yoo06,Rebal:2018}. Assuming that the channel \gls{snr}, $\rho$, is known, we use $\hat{h}$ and $\hat{g}$ to denote the estimated channel fade and estimated \gls{snr}, respectively. We further use $L$ to denote the length of the pilot training sequence for each device, with duration of $T_P = L \cdot T_S$ seconds over orthogonal time-frequency resources, where $T_S = 1/W$ is the symbol period. The total overhead cost of pilot transmission then equals to $N \cdot T_P$, and is paid out of the time budget $T$, leaving $T_D = T - N\cdot T_P$ seconds for data transmission. Using recursive \gls{mmse} channel estimation \cite{hassibi03,yoo06}, the true Rayleigh fade $h$ can be written as $h=\hat{h}+\epsilon$, where $\epsilon\sim\mathcal{CN}(0,\sigma_e(L))$, $\hat{h}\sim\mathcal{CN}(0,1-\sigma_e(L))$, and \begin{align}\label{eq_mmse} \sigma_e(L)=\frac{1}{1+L\cdot\rho}. \end{align} With respect to channel estimation, and for completeness of the investigation, we adopt two scenarios in this paper; namely, genie-aided \gls{pcsi}, i.e., where fade is perfectly estimated as $\hat{h}=h$, at the cost of zero pilot overhead $L = 0$, leaving $T_D = T$; and the case of \gls{icsi}, where channel estimation error is a function of the pilot training sequence length $L$ based on \eqref{eq_mmse}, resulting in $T_D = T - N \cdot L \cdot T_S$. \paragraph*{Notations} Throughout the paper, we use the notations listed in \tabref{table:notation}. \if2 1 \vspace{-10pt} \else \fi \subsection{On the Role of Multi-User Diversity in Low-Latency Regime} In a \emph{large} network with multiple users, each fading independently, there is likely to be a user whose channel is near its peak, at any time. This can be utilized to maximize the long term total throughput by use of \gls{csi} feedback and always serving the user with the strongest channel \cite{Knopp:1995,Grossglauser:2002} hence, exploiting \emph{multi-user diversity} gain. Similarly, for a given spectral efficiency, the per-user reliability of transmission can be maximized by choosing the user with strongest channel at any time. Therefore, with loose latency requirement, multi-user diversity gain is a natural source of reliability and efficiency. However, in low-latency regime, where tolerated latency is smaller or equal to the channel coherence time, it is likely to have one or few users whose channels are poor, at any time. It is therefore challenging to exploit multi-user diversity while guaranteeing timely reliability to multiple users with asymmetric channel statistics. To further analyze the diversity gain in low-latency regime, let's assume the network setup described earlier in this section with $M = 1$, where all the channel gain $\ga{i}{j}$'s are perfectly known and thus, the controller can precisely determine the achievable rate $\aR_{j}$ for device $j$, and the \gls{ap} targets an average spectral efficiency of $\frac{N B}{T W}$ in each time cycle $T$, with equal packet size for every scheduled device. Let's consider the case where the scheduler has the complete freedom to choose any nonempty subset of the $N$ devices in each time cycle. We model the average latency based on $K$, the number of users that are scheduled within a given time cycle. The average experienced latency by a device to be scheduled can be shown to be $\frac{(N+K)}{2K}T$\footnote{Derived by averaging across all devices, knowing that the first $K$ devices experience latency of $T$, while the last $K$ devices to be scheduled in a round experience latency of $NT/K$.}. For example under round-robin scheduling, by scheduling all devices in every time cycle $T$, i.e., $K = N$, the average latency is $T$, and by scheduling only one device in each time cycle the average latency is increased to $\frac{(N+1)}{2}T$. The scheduler is thus rewarded with reduced average latency, for scheduling every additional device out of the $N$. The cost of scheduling an additional device is going to be a loss in the collected multi-user diversity order. The following proposition addresses the trade-off between average latency and the collected multi-user diversity gain, assuming \gls{iid} Rayleigh fading on every link. \if2 1 \vspace{-5pt} \else \fi \begin{proposition} \label{Prop:motiv1} The maximum diversity order exploited at zero multiplexing point by the scheduler described above for scheduling exactly $K$ users in each time cycle is $N - K + 1$ for the case of $M=1$, and $M(N-K+1)$ for general $M$. \end{proposition} \if2 1 \vspace{-10pt} \else \fi \begin{proof} See \appref{App:motiv}. \end{proof} In other words, with strict latency requirements, i.e., all the $N$ devices must be scheduled over one coherence time, which is the case for an industrial wireless control network as described earlier in this section, then the system experiences diversity order of $1$ (for the case of M=1), meaning that no multi-user diversity gain is exploited. On the other hand, the maximum multi-user diversity order of $N$, is only exploited when the latency requirement is maximally loose and the controller gets to schedule the best device in each time cycle. Midway, the controller can trade off latency with diversity order by transmitting to $K \leq N$ devices over each coherence time, thus gaining the diversity order of $N - K + 1$. In fact, as we see in the \secref{Sec:Model}, the transmission protocol proposed in this paper benefits from such trade-off in exploiting the multi-user diversity gain by scheduling a subset of the devices with the highest channel strengths. For the remaining devices, the protocol seeks for the gain of cooperation among nodes, which is the topic of the following discussion. \if2 1 \begin{figure*}[t] \begin{center} \begin{subfigure}{.25\textwidth} \begin{center} \begin{psfrags} \psfrag{xlabel}[c][c][0.6]{X (m)} \psfrag{ylabel}[c][c][0.6]{Y (m)} \psfrag{title}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel2}[c][c][0.6]{X (m)} \psfrag{ylabel2}[c][c][0.6]{Y (m)} \psfrag{title2}[c][c][0.6]{coverage map} \includegraphics[width=0.6\columnwidth,keepaspectratio]{snr_map_1hop.eps} \end{psfrags} \caption{Coverage of single-hop transmission.} \label{fig:coverage_1h} \end{center} \end{subfigure}% \begin{subfigure}{.55\textwidth} \begin{subfigure}{.45\textwidth} \begin{center} \begin{psfrags} \psfrag{xlabel}[c][c][0.6]{X (m)} \psfrag{ylabel}[c][c][0.6]{Y (m)} \psfrag{title}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel2}[c][c][0.6]{X (m)} \psfrag{ylabel2}[c][c][0.6]{Y (m)} \psfrag{title2}[c][c][0.6]{coverage map} \psfrag{xlabel3}[c][c][0.6]{X (m)} \psfrag{ylabel3}[c][c][0.6]{Y (m)} \psfrag{title3}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel4}[c][c][0.6]{X (m)} \psfrag{ylabel4}[c][c][0.6]{Y (m)} \psfrag{title4}[c][c][0.6]{coverage map} \includegraphics[width=.6\columnwidth,keepaspectratio]{snr_map_2hop_2.eps} \end{psfrags} \end{center} \end{subfigure}% \begin{subfigure}{.45\textwidth} \begin{center} \begin{psfrags} \psfrag{xlabel1}[c][c][0.6]{X (m)} \psfrag{ylabel1}[c][c][0.6]{Y (m)} \psfrag{title1}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel2}[c][c][0.6]{X (m)} \psfrag{ylabel2}[c][c][0.6]{Y (m)} \psfrag{title2}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel3}[c][c][0.6]{X (m)} \psfrag{ylabel3}[c][c][0.6]{Y (m)} \psfrag{title3}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel4}[c][c][0.6]{X (m)} \psfrag{ylabel4}[c][c][0.6]{Y (m)} \psfrag{title4}[c][c][0.6]{coverage map} \includegraphics[width=.6\columnwidth,keepaspectratio]{snr_map_2hop_1.eps} \end{psfrags} \end{center} \end{subfigure}% \caption{Coverage of two-hop transmission with cooperative relaying.} \label{fig:coverage_2h} \end{subfigure}% \end{center} \vspace{-15pt} \caption{Map of \gls{snr} and coverage of $10^{-9}$ outage probability for spectral efficiency of 1 \gls{bpcu}, in an area of $100\times100$ $m^2$, in presence of a blockage (cyan color wall); the bright point in the center locates the \gls{ap} while the rest of the bright points locate the relay devices; (a) \gls{ap} with 4 antennas in the center provides $95.5\%$ when transmitting over the full time cycle $T$, i.e., transmission rate of 1 \gls{bpcu}; (b) on the left, $87.95\%$ coverage from an \gls{ap} with 4 antennas at transmission rate of 2 \gls{bpcu}, over first $T/2$ duration; on the right, $72.1\%$ coverage using three single antenna relay devices at transmission rate of 2 \gls{bpcu}, over the second $T/2$ duration; $100\%$ combined coverage of the two phases.} \label{fig:coverage_map} \if2 1 \vspace{-20pt} \else \vspace{-10pt} \fi \end{figure*} \else \begin{figure*}[t] \begin{center} \begin{subfigure}{.35\textwidth} \begin{center} \begin{psfrags} \psfrag{xlabel}[c][c][0.6]{X (m)} \psfrag{ylabel}[c][c][0.6]{Y (m)} \psfrag{title}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel2}[c][c][0.6]{X (m)} \psfrag{ylabel2}[c][c][0.6]{Y (m)} \psfrag{title2}[c][c][0.6]{coverage map} \includegraphics[width=0.6\columnwidth,keepaspectratio]{snr_map_1hop.eps} \end{psfrags} \caption{Coverage of single-hop transmission.} \label{fig:coverage_1h} \end{center} \end{subfigure}% \begin{subfigure}{.6\textwidth} \begin{subfigure}{.5\textwidth} \begin{center} \begin{psfrags} \psfrag{xlabel}[c][c][0.6]{X (m)} \psfrag{ylabel}[c][c][0.6]{Y (m)} \psfrag{title}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel2}[c][c][0.6]{X (m)} \psfrag{ylabel2}[c][c][0.6]{Y (m)} \psfrag{title2}[c][c][0.6]{coverage map} \psfrag{xlabel3}[c][c][0.6]{X (m)} \psfrag{ylabel3}[c][c][0.6]{Y (m)} \psfrag{title3}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel4}[c][c][0.6]{X (m)} \psfrag{ylabel4}[c][c][0.6]{Y (m)} \psfrag{title4}[c][c][0.6]{coverage map} \includegraphics[width=.7\columnwidth,keepaspectratio]{snr_map_2hop_2.eps} \end{psfrags} \end{center} \end{subfigure}% \begin{subfigure}{.5\textwidth} \begin{center} \begin{psfrags} \psfrag{xlabel1}[c][c][0.6]{X (m)} \psfrag{ylabel1}[c][c][0.6]{Y (m)} \psfrag{title1}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel2}[c][c][0.6]{X (m)} \psfrag{ylabel2}[c][c][0.6]{Y (m)} \psfrag{title2}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel3}[c][c][0.6]{X (m)} \psfrag{ylabel3}[c][c][0.6]{Y (m)} \psfrag{title3}[c][c][0.6]{\gls{snr} (dB)} \psfrag{xlabel4}[c][c][0.6]{X (m)} \psfrag{ylabel4}[c][c][0.6]{Y (m)} \psfrag{title4}[c][c][0.6]{coverage map} \includegraphics[width=.7\columnwidth,keepaspectratio]{snr_map_2hop_1.eps} \end{psfrags} \end{center} \end{subfigure}% \caption{Coverage of two-hop transmission with cooperative relaying.} \label{fig:coverage_2h} \end{subfigure}% \end{center} \caption{Map of \gls{snr} and coverage of $10^{-9}$ outage probability for spectral efficiency of 1 \gls{bpcu}, in an area of $100\times100$ $m^2$, in presence of a blockage (cyan color wall); the bright point in the center locates the \gls{ap} while the rest of the bright points locate the relay devices; (a) \gls{ap} with 4 antennas in the center provides $95.5\%$ when transmitting over the full time cycle $T$, i.e., transmission rate of 1 \gls{bpcu}; (b) on the left, $87.95\%$ coverage from an \gls{ap} with 4 antennas at transmission rate of 2 \gls{bpcu}, over first $T/2$ duration; on the right, $72.1\%$ coverage using three single antenna relay devices at transmission rate of 2 \gls{bpcu}, over the second $T/2$ duration; $100\%$ combined coverage of the two phases.} \label{fig:coverage_map} \if2 1 \vspace{-20pt} \else \vspace{-10pt} \fi \end{figure*} \fi \if2 1 \vspace{-10pt} \else \fi \subsection{Motivation for Multi-Hop Transmission} Cooperative relaying has been studied recently in several works as an enabler of \gls{urllc}, e.g., see \cite{swamy2015cow,swamy:2018relsel,Arvin:2019,Kaiming:2019ratespliting}, leveraging on the spatial diversity gain from engaging multiple relay devices, which increases robustness to fading variations. The focus of the design in cooperative relaying scheme in \cite{swamy2015cow} has been to mitigate the effect of small-scale fading. Such approach is highly beneficial in absence of \gls{mimo} techniques. However, with increasing deployment of massive \gls{mimo}, in practice, those benefits can be largely undermined. Particularly, cellular communication technologies typically rely on channel hardening effect of \gls{mimo} to mitigate the effect of small-scale fading \cite{Hochwald2004channelhardening}. Nevertheless, multi-hop relaying has historically been considered as a means of extending coverage in various wireless technologies, such as \gls{wimax}, \gls{lte}, and recenlty in \gls{5g} \gls{nr}, e.g., see \cite{kim2008relaycoverage,Gui2018relaycoverage,Lang2009relaycoverage,DawidKoziol:2017,3gpp22866}. The coverage problem caused by static or mobile blockages is in fact a challenging issue in industrial environments. Blockage can generally impede the link \gls{snr} by obstructing the \gls{los}. More significantly, when blockage size is several times larger than the electromagnetic wavelength, the diffraction around the obstacle becomes weaker, making the impact of blockage stronger. Consequently, blockages becomes a more severe challenge in higher frequencies, or the so called \gls{mmwave} \cite{5262296}. Moreover, the dynamic nature of factory floor with large number of static and moving objects makes it difficult to provide every time/everywhere wireless link availability. This further motivates the use of cooperative relaying to deal with temporary and/or zonal loss of coverage. To this point, the example in \figref{fig:coverage_map} illustrates the \gls{snr} and coverage of $10^{-9}$ outage probability for spectral efficiency of 1 \gls{bpcu} over an area of $100\times100$ $m^2$. A simple static blockage is positioned on the right side of the area. First, in \figref{fig:coverage_1h}, it is shown that using the total time budget $T$ (i.e., transmitting at 1 \gls{bpcu}), direct transmission by the \gls{ap} with 4 antennas provides $95.5\%$ coverage. This means that only around $95.5\%$ of the points over the area can achieve the required target outage probability of $10^{-9}$ with a single-hop transmission. Then, in \figref{fig:coverage_2h}, the time budget $T$ is divided by two, and the transmission is done twice at the doubled rate of 2 \gls{bpcu}. Therefore, the coverage of the direct transmission from access point reduces to $87.95\%$ (left hand side of \figref{fig:coverage_2h}), due to the increase in transmission rate. However, in the second $T/2$ portion of the time, three devices randomly positioned around the blockage, and each having a single transmit antenna, relay the transmission from the \gls{ap}. The relaying phase at 2 \gls{bpcu}, also provides a complementary coverage of $72.1\%$, mostly around the area affected by the blockage. But more interestingly, the overall coverage of the two phases reaches the desirable $100\%$. Knowing that the blockage affects the coverage around the right hand side of the square area, such coverage enhancement from two-hop relaying can in practice be directed towards devices in the same area. This in fact increases the efficiency of ultra-reliable communications, by deploying the cooperative relaying in an \emph{on-demand} fashion, only for the devices with coverage issues. Improving coverage for \gls{iiot} applications can alternatively be done by densification of the \glspl{ap}. However, over-provisioning is not efficient in terms of the cost of the network deployment. It should be noted that the intention of the example in \figref{fig:coverage_map} is not to claim that two-hop cooperative relaying is always better than single-hop transmission. In fact, as we will discuss in the following sections, with a smart and dynamic algorithm to use the cooperative relaying gain in an \emph{on-demand} manner, the overall spectral efficiency can be improved compared to the case where all the devices are served with two-hop transmission. \if2 1 \vspace{-10pt} \else \fi \section{Proposed Channel-Aware Transmission Protocol} \label{Sec:Model} In this section we first introduce the proposed transmission protocol. Then outage and diversity order analysis of the protocol are presented. \if2 1 \vspace{-10pt} \else \fi \subsection{Transmission Protocol} \label{Sec:transmissionprotocol} The total \gls{dl} transmission time $T_D$ is divided into two parts, using a partitioning factor $0 \leq \beta \leq 1$, where $\Toh = \beta T_D$ is used for rate-adaptive single-hop transmission of independent messages to devices with strong instantaneous channel to the controller \glspl{ap} in a \gls{tdma} fashion. The remaining $\Tth = (1-\beta)T_D$ is used for two-hop cooperative transmission phase to the rest of the devices, where the messages of all remaining devices are aggregated and transmitted in two hops. In addition, the controller acquires the knowledge of $\gha{i}{j}$'s for the \gls{ap}-device pairs via channel estimation using pilots of length $L$. Based on this, devices are put in an order according to the instantaneous transmission rate that they can receive at from the \glspl{ap}. The achievable transmission rate for device $j$, $\aR_{j}$, can be computed using \eqref{Eq:linkoutage}. The controller estimates the achievable rate, using \begin{align}\label{Eq:achievablerate} \ahR_{j} = W \log \left( 1 + \sum_{i \in \mathscr{A}}\gha{i}{j} \right). \end{align} Note that, for \gls{icsi}, i.e., $\sigma_{e} > 0$, $\prob{\ahR_{j} > \aR_{j}} = 0.5$. In other words, regardless of the channel estimation precision, the estimated transmission rate is above the achievable rate $50\%$ of the time. To curb the impact of channel estimation error in case of \gls{icsi}, we use a rate back-off parameter $0 \leq \theta \leq 1$ to adjust the transmission rate to $\theta \cdot \ahR$. The following definition denotes the largest subset of the devices that the controller can accommodate with single-hop transmission over time $\tau$. \begin{align}\label{Eq:strongdevices} \pmb{S}(\tau, \{\gha{i}{j} \}) = \; \underset{\mathscr{S}}{\arg} \; \max_{\mathscr{S} \subset \mathscr{D}} \; \; & \card{\mathscr{S}} \\ \nonumber \text{subject to} & \sum_{j \in \mathscr{S}} \frac{1}{\theta \cdot \ahR_{j}} \leq \frac{\tau}{B}, \\ & \ahR_{k} \leq \ahR_{j}, \; \forall k \in \mathscr{D} \setminus \mathscr{S}, \forall j \in \mathscr{S} \nonumber \end{align} Let $\mathscr{D}_{1\text{h}}$, where $\mathscr{D}_{1\text{h}} \subset \mathscr{D}$, and $\mathscr{D}_{2\text{h}} = \mathscr{D} \setminus \mathscr{D}_{1\text{h}}$ denote the random set of the \emph{strong} and \emph{weak} devices, respectively. Let $K_{1\text{h}} = \card{\mathscr{D}_{1\text{h}}}$ and $K_{2\text{h}} = \card{\mathscr{D}_{2\text{h}}}$ be the discrete random variables of size of those sets, which follows $K_{1\text{h}} + K_{2\text{h}} = N$. Let $\Roh{j} = \theta \cdot \ahR_{j}$ denote the transmission rate for device $j \in \mathscr{D}_{1\text{h}}$. We assume that $\beta$ is known by all the nodes in the network. Therefore, upon generating the set $\mathscr{D}_{1\text{h}}$ for a given realization of the channels, the controller sends the set of indexes in $\mathscr{D}_{1\text{h}}$ and the transmission rates $\Roh{j}$, over a control channel to the strong devices. Such information is necessary for the devices to be able to follow the scheduling order of transmission in the single-hop phase. The devices in $\mathscr{D}_{2\text{h}}$ are then scheduled over a two-hop transmission over the remaining $\Tth$, where their messages are aggregated, and $\alpha \cdot \Tth$ and $(1-\alpha)\cdot \Tth$ are used for broadcasting and relaying the aggregated messages respectively, with $0 \leq \alpha \leq 1$. In \figref{fig:scheduling} the time scheduling of the proposed \gls{andcoop} transmission protocol is illustrated\footnote{Note that the time dimension is chosen in here as an example. In practice the division of the time-frequency resources between the single-hop and two-hop phases of the protocol can be in either the time domain, frequency domain, or both.}. In the following the proposed \gls{andcoop} transmission protocol is summarized. We assume that the controller has the knowledge of the appropriate $\beta$ and $\alpha$ design parameters, which are acquired off-line and are shared with the devices (we discuss the optimization of those parameters in the following subsection). A summary of the proposed algorithm in each time cycle is as follows: \begin{enumerate} \item Using the knowledge of \gls{ap}-device \gls{csi}, the controller finds the set of devices, $\mathscr{D}_{1\text{h}}$, that will be scheduled over single-hop rate-adaptive transmission. This is done according to $\mathscr{D}_{1\text{h}} = \pmb{S}(\Toh, \{\gha{i}{j} \})$ in \eqref{Eq:strongdevices}, while $\Toh = \beta \cdot T$. \item The controller adapts transmission rate for each device in $\mathscr{D}_{1\text{h}}$ according to their instantaneous channel by setting $\Roh{j} = \theta \cdot \ahR$, thus allocating $B/\Roh{j}$ seconds of the total time for transmission to device $j$. The controller \glspl{ap} will then perform \gls{comp} transmission of the message for each node $j \in \mathscr{D}_{1\text{h}}$ with the adapted rate in a \gls{tdma} fashion. \item \label{step-b} All the $B$-bit messages intended for devices in $\mathscr{D}_{2\text{h}} = \mathscr{D} \setminus \mathscr{D}_{1\text{h}}$ are aggregated together. The controller \glspl{ap} jointly broadcast the aggregated message at rate $\Rth{b} = \frac{B K_{2\text{h}}}{\alpha \Tth}$, over the first $\alpha$ portion of $\Tth$ time\footnote{In practice, the messages can be concatenated before encoding which will potentially increase coding gain and reduce number of decoding attempts for relay devices.}. \item \label{step-receive} All devices in $\mathscr{D}$ attempt decoding the broadcast message from previous step. The successful devices to decode will act as relays. \item The \glspl{ap} broadcast the message from step~\ref{step-b} at rate $\Rth{r} = \frac{B K_{2\text{h}}}{(1-\alpha) \Tth}$. The relay devices from step~\ref{step-receive} re-encode with the same code rate, and cooperate as simultaneous relays. \end{enumerate} \begin{figure}[t] \begin{center} \psfrag{a}[c][c][0.59]{$\Toh = \beta \cdot T$} \psfrag{b}[c][c][0.59]{$\alpha \cdot \Tth$} \psfrag{c}[c][c][0.59]{$(1-\alpha)\cdot \Tth$} \psfrag{t}[c][c][0.59]{$T$} \psfrag{u}[c][c][0.59]{$\ldots$} \psfrag{v}[c][c][0.59]{$\Rth{r} = \frac{B K_{2\text{h}}}{(1-\alpha) \Tth}$} \psfrag{w}[c][c][0.59]{$\Rth{b} = \frac{B K_{2\text{h}}}{\alpha \Tth}$} \psfrag{x}[c][c][0.59]{$\Roh{j_{1}}$} \psfrag{s}[c][c][0.59]{$\Roh{j_{2}}$} \psfrag{z}[c][c][0.59]{$\Roh{j_{K_{1\text{h}}}}$} \includegraphics[width=0.8\columnwidth,keepaspectratio]{scheduling.eps} \caption{Time scheduling illustrated for the proposed scheme. The transmission rate for each scheduled time slot is identified, assuming $j_1, j_2, \ldots, j_{K_{1\text{h}}} \in \mathscr{D}_{1\text{h}}$. For the devices in $\mathscr{D}_{2\text{h}}$, the aggregated message is first broadcast with rate $\Rth{b}$ and then relayed with rate $\Rth{r}$.} \label{fig:scheduling} \end{center} \if2 1 \vspace{-30pt} \else \fi \end{figure} \if2 1 \vspace{-10pt} \else \fi \subsection{A Note on Optimization of the Design} The proposed transmission protocol can be optimized based on the design parameters $L$, $\beta$ and $\theta$, to achieve the minimum $\mathbb{P}_\tr{\tiny{out}}$. We perform numerical optimization in two scenarios of \gls{pcsi} and \gls{icsi}. Note that in \gls{pcsi} scenario, we fix $L = 0$ and $\theta = 1$, only optimizing with respect to $\beta$, for given transmit power and spectral efficiency. To this end, we fix the value of the time division parameter $\beta$ for all realizations of the channel. Therefore, we are able to numerically optimize $\beta$ for a given setup by running the simulation for all values of $\beta$ from a finite set of real numbers uniformly chosen from the $[0, 1]$ interval to derive $\hat{\beta} = \underset{\beta}{\arg \min} \mathbb{P}_\tr{\tiny{out}}(\beta)$. Optimization of the \gls{icsi} scenario with exhaustive search across $L$, $\beta$ and $\theta$, is computationally costly. However, as we will show in the next section, parameter $L$ can be fixed with marginal effect on the outage, which can significantly reduces the search for the optimal $L$ , $\beta$ and $\theta$. Parameter $\alpha$ is used to partition the time $\Tth$ between broadcast and relaying hops of the two-hop cooperative transmission. Increasing $\alpha$ results in smaller $\Rth{b}$ which increases chances of decoding for all nodes and results in larger expected number of relay nodes for the second hop. In turn, it will increase $\Rth{r}$ and decrease chance of decoding in the second hop. We note that the optimization of $\alpha$ is not a trivial problem however, following the observation in \cite{swamy2015cow}, the average reliability gain from optimizing $\alpha$ with respect to $\alpha = 0.5$ can be marginal, therefore, in the numerical analysis that will follow, we fix $\alpha = 0.5$. \if2 1 \vspace{-10pt} \else \fi \subsection{Outage Analysis} We analyze \emph{system outage probability} of the proposed system, denoted by $\mathbb{P}_\tr{\tiny{out}}$ and defined as the average probability that at least one device fails to decode its own message at the end of time-cycle $T$. Let $P_{1h}(\mathscr{D}_{1\text{h}})$ and $P_{2h}(\mathscr{D}_{2\text{h}})$ denote the probability of outage for at least one device in, respectively, the adaptive-rate single-hop phase and the two-hop cooperative phase of the transmission protocol. \paragraph*{Single-hop rate-adaptive transmission} Conditioned on \gls{csi}, we have \begin{align}\label{Eq:outage-1hop-icsi} P_{1h}(\mathscr{D}_{1\text{h}} | \{ \hha{i}{j} \}) =\prob{ \exists j \in \mathscr{D}_{1\text{h}}, \theta \cdot \ahR > \aR }, \end{align} where expectation is over channel gains. For the case of \gls{icsi} with channel estimation error, the outage probability in \eqref{Eq:outage-1hop-icsi} is non-zero as also discussed in \cite[Sec. III-A]{Rebal:2018TCOM}. Characterization of $P_{1h}$ is not analytically tractable. However, when $\beta = 1$, i.e., all the devices are scheduled with single-hop transmission, outage probability is equivalent to the probability of \emph{time overflow}, i.e., the chance that $\Toh$ is too short given the channel gains to successfully accommodate all the packets. In this case, analytical bounds on the outage probability can be found in \cite{Rebal:2018TCOM}, where it is shown that in practical ranges of \gls{snr}, as cell load $N \times B$ grows, the chance of time overflow increases above \gls{urllc} target outage probability and dominates system outage regardless of the precision of channel estimation. For the case of \gls{pcsi}, when $\beta < 1$, all the devices in $\mathscr{D}_{1\text{h}}$ pass the success condition in \eqref{Eq:linkoutage}, resulting in $P_{1h}(\mathscr{D}_{1\text{h}} | \{ \ha{i}{j} \}) = 0$. Therefore, the following is valid for \gls{pcsi} scenario. \begin{align}\label{Eq:outage-1hop} P_{1h}(\mathscr{D}_{1\text{h}} | \{ \ha{i}{j} \}) = \left\{\begin{matrix} 0 & 0 \leq \beta <1 \\ \prob{\sum_{j \in \mathscr{D}} \frac{1}{\aR_j} > \frac{ \Toh}{B}} & \beta = 1. \end{matrix}\right. \end{align} \paragraph*{Two-hop cooperative transmission} Conditioned on \gls{csi}, the outage probability of the two-hop phase is given by \begin{align} P_{2h}(\mathscr{D}_{2\text{h}} \mid \{ \hha{i}{j} \}) = \prob{ \exists j \in \mathscr{D}_{2\text{h}} \setminus \mathscr{R} : \sum_{k \in \mathscr{R}}\gd{k}{j} < \zeta }, \nonumbe \end{align} where $\zeta = 2^{\Rth{r}/W} -\sum_{i \in \mathscr{A}}\ga{i}{j} -1$, and $\mathscr{R}$ is the set of relay devices, defined as \begin{align} \mathscr{R} = \{j \in \mathscr{D}: \Rth{b} \leq \aR_{j} \}. \end{align} \if2 2 \begin{figure*}[b] \normalsize \hrulefill \begin{align}\label{Eq:Ptwohop} P_{2h}\left(\mathscr{D} \right) = \sum_{\substack{ \forall \mathscr{S} \subset \mathscr{D} }} & \prob{\forall j \in \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} \bigg) \geq \Rth{b} } \cdot \prob{\forall j \in \mathscr{D} \setminus \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} \bigg) < \Rth{b} } \\ & \cdot \left( 1 - \prob{\forall j \in \mathscr{D} \setminus \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} + \sum_{k \in \mathscr{S}}\gd{k}{j} \bigg) \geq \Rth{r} \; \middle| \; \forall j \in \mathscr{D} \setminus \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} \bigg) < \Rth{b} } \right) \nonumber \end{align} \end{figure*} Although, averaging $P_{2h}(\mathscr{D}_{2\text{h}} \mid \{ \ga{i}{j} \})$ over channel gains is not analytically tractable, for the purpose of analyzing the diversity order gain of the transmission protocol, we are interested in the outage probability when all devices are served in the two-hop cooperative phase. An expression for $P_{2h}$, conditioned on $K_{2\text{h}} = N$ can be written as follows in \eqref{Eq:Ptwohop} at the bottom of the page. \else Although, averaging $P_{2h}(\mathscr{D}_{2\text{h}} \mid \{ \ga{i}{j} \})$ over channel gains is not analytically tractable, for the purpose of analyzing the diversity order gain of the transmission protocol, we are interested in the outage probability when all devices are served in the two-hop cooperative phase. An expression for $P_{2h}$, conditioned on $K_{2\text{h}} = N$ can be written as follows in \eqref{Eq:Ptwohop}. \fontsize{9}{11}\selectfont \begin{align}\label{Eq:Ptwohop} P_{2h}\left(\mathscr{D} \right) = \sum_{\substack{ \forall \mathscr{S} \subset \mathscr{D} }} & \prob{\forall j \in \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} \bigg) \geq \Rth{b} } \cdot \prob{\forall j \in \mathscr{D} \setminus \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} \bigg) < \Rth{b} } \\ & \cdot \left( 1 - \prob{\forall j \in \mathscr{D} \setminus \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} + \sum_{k \in \mathscr{S}}\gd{k}{j} \bigg) \geq \Rth{r} \; \middle| \; \forall j \in \mathscr{D} \setminus \mathscr{S} : \; W \log \bigg( 1 + \sum_{i \in \mathscr{A}}\ga{i}{j} \bigg) < \Rth{b} } \right) \nonumber \end{align} \normalsize \fi For a practical wireless network in which the channel fading distribution depends on path-loss and shadowing, the evaluation of \eqref{Eq:Ptwohop} is challenging. Simplification of \eqref{Eq:Ptwohop} can be obtained in the following special case. Let's assume a setup with fixed nominal \gls{snr} $\rho$ on all \gls{ap}-device and device-device links with \gls{iid} small-scale fading $h$. In such a scenario, using \eqref{Eq:linkoutage}, the probability of decoding failure with $m$ cooperating transmitters at rate $R$ is as follows. \begin{align}\label{Eq:pfail} \Pm{m,R} = \prob{W \log\Big( 1 + \rho \sum_{l = 1}^{m}|h_l|^2 \Big) < R}, \end{align} where $h_l \sim CN(0,1)$, are \gls{iid} random variables. Therefore, $\sum_{l = 1}^{m}|h_l|^2$ has the Erlang distribution and $p^m$ can be computed as \cite{Laneman:2003} \begin{align} \Pm{m,R} = \gamma\left( m,\frac{\omega}{P_t} \right), \end{align} where $\gamma(x,y) = \int_{0}^{y} t^{x-1} e^{-t} dt$ is the incomplete Gamma function. Moreover, $\omega = W \cdot \sigma_0 \cdot (2^{R/W} - 1)$ and $\sigma_0$ denotes \gls{psd} of the \gls{awgn} and $P_t$ denotes the transmit power at each transmitting node. In such simplified scenario, as similarly suggested in \cite{swamy2015cow}, \eqref{Eq:Ptwohop} can be reformulated as follows. \if2 1 \begin{align}\label{Eq:Ptwohop-4} P_{2h}\left(\mathscr{D} \right) = \sum_{n = 0}^{N-1}\left( q_{b}^{M}\right)^{(N-n)} \left(1-q_{b}^M \right)^{n} \binom{N}{n} \left(1 - \left( 1 - {q_{r}^{(M+n)}} \right)^{(N-n)} \right), \end{align} \else \begin{align}\label{Eq:Ptwohop-4} &P_{2h}\left(\mathscr{D} \right) = \\ &\sum_{n = 0}^{N-1}\left( q_{b}^{M}\right)^{(N-n)} \left(1-q_{b}^M \right)^{n} \binom{N}{n} \left(1 - \left( 1 - {q_{r}^{(M+n)}} \right)^{(N-n)} \right), \nonumber \end{align} \fi where $q_{b}^M = \Pm{M,\Rth{b}}$ and \begin{align}\label{Eq:qr} q_{r}^{(M+n)} = \min \{1, \Pm{M+n,\Rth{r}} / \Pm{M,\Rth{b}} \}, \end{align} is the conditional failure probability of a device in relaying hop given \if2 1 \else that \fi it failed in broadcast hop. \if2 1 \vspace{-10pt} \else \fi \subsection{Diversity-Multiplexing Tradeoff Analysis} \label{Sec:DMT} In this section, we analyze the diversity-multiplexing trade-off of the proposed scheme for the case of \gls{pcsi}, assuming independent Rayleigh distributed fading for all links, using the definition in \eqref{Eq:dive_order_def}. First, note that when transmit power goes to $\infty$, the achievable transmission rate from \eqref{Eq:achievablerate} also approaches $\infty$, resulting in $ \mathscr{D}_{1\text{h}} = \mathscr{D}$, when $0 < \beta \leq 1$. Therefore, unless $\beta = 0$, all the devices are scheduled in the single-hop rate-adaptive phase. For that reason, we analyze the diversity-multiplexing tradeoff for two extreme cases of $\beta = 1$ and $\beta = 0$, respectively, when all the devices are scheduled in single-hop rate-adaptive phase and, when all the devices are scheduled in two-hop cooperative phase. This also provides lower bounds for the diversity-multiplexing tradeoff of the proposed \gls{andcoop} scheme. \begin{proposition} \label{Prop:1h} When all the devices are scheduled in single-hop rate-adaptive phase, the diversity order of the considered system at zero multiplexing is given by \begin{align} \label{Eq:div_order_1hop} d_\textit{single-hop}(0) = M. \end{align} \end{proposition} \begin{proof} See \appref{App:A}. \end{proof} Moreover, following the proof in \appref{App:A}, upper and lower bounds of the diversity-multiplexing tradeoff are readily derived as follows for the case where all the devices are scheduled over single-hop transmission. \begin{align}\label{Eq:divmux_1hop} M (1-r) \leq d_\textit{single-hop}(r) \leq M (1-\frac{r}{N}). \end{align} For the case when all the devices are scheduled in two-hop cooperative phase (i.e., the OccupyCoW protocol in \cite{swamy2015cow}), the following proposition presents the diversity-multiplexing tradeoff for the general case of $0 < \alpha <1$, when $M>1$. \if2 1 \vspace{-10pt} \else \fi \begin{proposition} \label{Prop:2h} When all the devices are scheduled in two-hop cooperative phase, the diversity-multiplexing tradeoff is given by \begin{align}\label{Eq:DMT-2hop} d_\textit{two-hop}(r) = (M+N-1)\left( 1- \frac{r}{1-\alpha} \right), \end{align} where at zero multiplexing gain it yields \begin{align} \label{Eq:div_orde_2hop} d_\textit{two-hop}(0) = M+N-1. \end{align} \end{proposition} \begin{proof} See \appref{Proof_prop_2h}. \end{proof} Intuitively, diversity order $M + N -1$, i.e., the slope of outage probability curve in high \gls{snr}, corresponds to the case when all the $M$ \glspl{ap} cooperate with $N-1$ strongest devices to transmit to the weakest device. It is an interesting observation from \eqref{Eq:DMT-2hop} that the tradeoff between diversity order $d$ and multiplexing gain $r$ in high \gls{snr} is controlled by the inverse of $1- \alpha$. In other words, the duration of the relaying phase, which directly affects the outage probability for the weakest devices, controls the diversity multiplexing tradeoff in high \gls{snr}. Therefore, for a given multiplexing gain $r$, the maximum diversity is achieved when $\alpha$ is the minimum allowed value for \eqref{Eq:DMT-2hop} to be non-negative, i.e., $0 < \alpha \leq 1-r$. Since $\alpha$ cannot be zero in \eqref{Eq:DMT-2hop}, the following upper bound is valid for the two-hop transmission for $r > 0$. \begin{align} \label{Eq:div_orde_2hop_up} d_\textit{two-hop}(r) < (M+N-1) ( 1- r ). \end{align} This upper bound is depicted by the dashed green line in \figref{fig:div_mux_tradeoff}. For the case of $\alpha = \frac{1}{2}$, which is the exercised design in \cite{Arvin:2019,swamy2015cow,Kaiming:2019ratespliting}, the diversity-multiplexing tradeoff in \eqref{Eq:DMT-2hop} becomes \begin{align}\label{Eq:2hop_divmux_half} d_\textit{two-hop}(r)|_{\alpha=1/2} = (M+N-1) ( 1- 0.5 \cdot r ) \end{align} As also depicted in \figref{fig:div_mux_tradeoff}, in such case the maximum achievable multiplexing gain is $r = 0.5$, intuitively corresponding to the fact that each message is transmitted twice with the same rate, once in broadcast phase and once more in the relaying phase. It is clear that the two-hop operation in \eqref{Eq:2hop_divmux_half} is spectrally inefficient, due to the fact that at very low system outage probability the gain from cooperative relaying is small, thus only a small percentage of the devices will benefit from relaying. On the other hand, the single-hop transmission from \propref{Prop:1h} can achieve higher multiplexing gain than \eqref{Eq:2hop_divmux_half}. This further suggests that it is best to capture the relaying benefit only for that small percentage of the devices that experience a \emph{weak} channel to the \glspl{ap}, while enjoying the high rate single-hop transmission to the devices with \emph{strong} channel, which in turn increases the overall spectral efficiency. Moreover, note that since by design the outage probability of the proposed \gls{andcoop} scheme is upper bounded by that of the two extremes studied in \propref{Prop:1h} and \propref{Prop:2h}, then from \eqref{Eq:dive_order_def} we readily have $d_\textit{single-hop}(r) \leq d_\textit{\gls{andcoop}}(r)$ and $d_\textit{two-hop}(r) \leq d_\textit{\gls{andcoop}}(r)$ for given $\alpha$ and $r$. \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{multiplexing gain, $r$} \psfrag{ylabel}[c][c][0.9]{diversity order, $d(r)$} \psfrag{x1}[lc][lc][0.59]{\propref{Prop:andcoop}} \psfrag{XXXXXXXXXx1}[lc][lc][0.59]{two-hop; up} \psfrag{x2}[lc][lc][0.59]{two-hop; $\alpha = \frac{1}{2}$} \psfrag{x3}[lc][lc][0.59]{single-hop; low} \psfrag{x4}[lc][lc][0.59]{single-hop; up} \psfrag{y1}[rc][rc][0.59]{$M$} \psfrag{ye}[rc][rc][0.59]{$M+N-1$} \psfrag{xe}[rc][rc][0.59]{$\frac{N}{N+1}$} \if2 1 \includegraphics[width=.32\columnwidth,keepaspectratio]{div_mux_tradeoff.eps} \else \includegraphics[width=0.82\columnwidth,keepaspectratio]{div_mux_tradeoff.eps} \fi \caption{Diversity-multiplexing tradeoff.} \label{fig:div_mux_tradeoff} \end{center} \if2 1 \vspace{-30pt} \else \fi \end{figure} \section{Numerical Results} \label{Sec:Results} This section presents numerical results from simulating \gls{dl} operation of the network described in \secref{Sec:ProblemSetup}, where $M$ single-antenna \glspl{ap} and $N$ single-antenna devices are randomly distributed across the factory area. To this end, we start by analyzing the performance with the assumption of \gls{pcsi}, to focus on system parameter designs. Then, we extend the analysis to the case of \gls{icsi}, and study the impact of \gls{csi} estimation error on the performance indicators. The plots presented throughout this section are generated using a system-level simulation, where we adopt the parameters summarized in \tabref{Tab:Parameters} (except in cases where stated otherwise). Path loss exponents are determined using the factory and open-plan building channel model in \cite{rapp91}. The probability that a link is \gls{los} is derived based on the distance of the communicating nodes, $\nu$, using the following function. \begin{align} p_{\text{L}}(\nu) = a + \indic{\nu \leq b}\,\frac{1-a}{b^2}\,(\nu-b)^2, \end{align} where $a$ is a fixed probability mass, and $b$ is the cutoff above which the probability of a link being \gls{los} becomes fixed to $a$. The link is therefore \gls{nlos} with probability of $1-p_{\text{L}}(\nu)$. The cycle duration, number of devices, data per device and bandwidth are given values similar to those in \cite{swamy2015cow} and \cite{weiner2014design}. With respect to the optimization of $\beta$, the following schemes are studied in this section. \begin{itemize} \item $\beta = \hat{\beta}$: This represents our proposed \gls{andcoop} scheme, where an optimal $\hat{\beta}$ portion of the total time is allocated for rate-adaptive single-hop transmission to a subset of the devices with the highest instantaneous channel quality. The remaining $1 - \hat{\beta}$ portion of the time is then used for two-hop transmission to the remaining devices. \item $\beta = 1$, ideal rate adaptation: This transmission scheme mimics the typical transmission in cellular technologies, such as \gls{lte}, where, the transmission rate for each user is adapted to the instantaneous channel quality. \item $\beta = 0$, two-hop transmission: This is a special case of our proposed scheme, where the total time resources is allocated to the two-hop transmission towards all the users. The scheme was originally proposed in \cite{swamy2015cow} and is known as the OccupyCoW protocol. \end{itemize} \input{table2.tex} \if2 1 \vspace{-10pt} \else \fi \subsection{Performance Analysis with Perfect \gls{csi}} Let's start by assuming that the controller has perfect knowledge of the channel gains for all the \gls{ap}-device links. We emphasize that in the present work, the \gls{csi} is solely used for the purpose of transmission rate adaptation, meaning that the channel coefficient phase is not collected nor utilized. This differentiates our work from \gls{csi}-based distributed multi-antenna systems, such as in \cite{alonzo2020urllc}, which rely on coherent joint transmission and beam-forming at the transmitter. This further relaxes the assumption of tight synchronization among antennas for distributed cooperative transmission. \if2 1 \begin{figure*}[t] \centering \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{spectral efficiency, $\eta$ (\gls{bpcu})} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_id_rate.eps} \caption{System outage probability against spectral efficiency at $P_a = P_d = 23$ dBm.} \label{fig:comp_id_rate} \end{center} \end{minipage}\qquad \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{number of weak devices, $K_{2\text{h}}$} \psfrag{ylabel}[c][c][0.9]{cumulative distribution function} \psfrag{XXX1}[lc][lc][0.59]{$M = 1$} \psfrag{x2}[lc][lc][0.59]{$M = 2$} \psfrag{x3}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{weak_node_stats_id.eps} \caption{Statistics of $K_{2\text{h}}$ with $N = 50$, $P_a = P_d = 23$ dBm at $\mathbb{P}_\tr{\tiny{out}} = 10^{-5}$ points of \figref{fig:comp_id_rate}.}\label{fig:weak_node_stats_id} \end{center} \end{minipage} \if2 1 \vspace{-35pt} \else \fi \end{figure*} \fi \if2 2 \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{spectral efficiency, $\eta$ (\gls{bpcu})} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_id_rate.eps} \caption{System outage probability against spectral efficiency at $P_a = P_d = 23$ dBm.} \label{fig:comp_id_rate} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \paragraph*{Proposed scheme improves spectral efficiency} In \figref{fig:comp_id_rate}, system outage probability is shown against spectral efficiency $\eta$, derived as $\eta = \frac{N B}{T W}$. The proposed \gls{andcoop} scheme with optimized time division of $\beta = \hat{\beta}$, improves spectral efficiency by at least 0.5 \gls{bpcu} when $M = 1$ \gls{ap} is deployed. The gain is higher when a larger number of \glspl{ap} are deployed. Namely, with $M = 2$ and $M = 3$, more than 1 and 1.5 \gls{bpcu} increase in spectral efficiency is achieved with respect to the case of $\beta = 0$, i.e., when only two-hop cooperative transmission is deployed. \if2 2 \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{number of weak devices, $K_{2\text{h}}$} \psfrag{ylabel}[c][c][0.9]{cumulative distribution function} \psfrag{XXX1}[lc][lc][0.59]{$M = 1$} \psfrag{x2}[lc][lc][0.59]{$M = 2$} \psfrag{x3}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{weak_node_stats_id.eps} \caption{Statistics of $K_{2\text{h}}$ with $N = 50$, $P_a = P_d = 23$ dBm at $\mathbb{P}_\tr{\tiny{out}} = 10^{-5}$ points of \figref{fig:comp_id_rate}.} \label{fig:weak_node_stats_id} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi The gain in spectral efficiency is thanks to transmitting packets to \emph{strong} devices with high rate in the single-hop phase, allowing the two-hop phase to accommodate the \emph{weak} devices reliably at even large packet sizes. This way, the robustness of rate-adaptation to increase in load is combined together with the robustness of OccupyCoW to fading, providing an improved reliability at a higher spectral efficiency. \figref{fig:weak_node_stats_id} shows the \gls{cdf} of the number of weak devices scheduled with two-hop transmission by the proposed \gls{andcoop} scheme with optimized $\beta$. The statistics are collected for the points in \figref{fig:comp_id_rate} where the proposed \gls{andcoop} achieves $\mathbb{P}_\tr{\tiny{out}} = 10^{-5}$. Interestingly, the average number of users scheduled with two-hop transmission is just below 13, 7 and 3 respectively for the case of 1, 2 and 3 \glspl{ap}. \if2 2 \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{transmit power (dBm)} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_id_power.eps} \caption{System outage probability against transmit power, $P_a = P_d$, for $B = 50$ bytes per device.} \label{fig:comp_id_power} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \paragraph*{Ultra-reliability at lower transmit power} By fully exploiting the diversity gain in the network, the proposed \gls{andcoop} scheme relaxes the need for high \gls{snr} to achieve ultra-reliability. As it is shown in \figref{fig:comp_id_power}, system outage probability of $\mathbb{P}_\tr{\tiny{out}} = 10^{-5}$, the required transmit power of the proposed scheme reduces by a few dB compared to the OccupyCoW protocol. Such transmit power gap, when compared against the case of single-hop with ideal rate adaptation, can grow to tens of dB. Aside from improving the overall energy efficiency of the system, operating at a lower transmit power can also reduce the interference generated by the cell towards neighbouring cells, in case of a multi-cell operation, as also studied in \cite{Arvin:2019}. Moreover, the proposed \gls{andcoop} can naturally reduce the average relaying time per relay device, by reducing the overall duration of the relaying phase. The combined effect is a significant reduction in the average consumed energy in the relaying phase across devices, as depicted in \figref{fig:relay_power_consumption_stats_id_jules}. The curves suggest $30\%$ to $40\%$ reduction in average relaying energy consumption in all cases. \if2 2 \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{average transmit energy per device ($\mu$J)} \psfrag{ylabel}[c][c][0.9]{cumulative distribution function} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x3}[lc][lc][0.59]{$\beta = 0$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{relay_power_consumption_stats_id_jules.eps} \caption{Statistics of average consumed energy per device for relaying with $N = 50$, $B = 50$ bytes at $\mathbb{P}_\tr{\tiny{out}} = 10^{-5}$ points of \figref{fig:comp_id_power}.} \label{fig:relay_power_consumption_stats_id_jules} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \if2 1 \begin{figure*} \centering \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{transmit power (dBm)} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_id_power.eps} \caption{System outage probability against transmit power, $P_a = P_d$, for $B = 50$ bytes per device.} \label{fig:comp_id_power} \end{center} \end{minipage}\qquad \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{average transmit energy per device ($\mu$J)} \psfrag{ylabel}[c][c][0.9]{cumulative distribution function} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x3}[lc][lc][0.59]{$\beta = 0$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{relay_power_consumption_stats_id_jules.eps} \caption{Statistics of average consumed energy per device for relaying with $N = 50$, $B = 50$ bytes at $\mathbb{P}_\tr{\tiny{out}} = 10^{-5}$ points of \figref{fig:comp_id_power}.} \label{fig:relay_power_consumption_stats_id_jules} \end{center} \end{minipage} \if2 1 \vspace{-35pt} \else \fi \end{figure*} \fi \if2 2 \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{ylabel}[c][c][0.9]{empirical outage exponent} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{div_order_snr.eps} \caption{Empirical diversity order in finite \gls{snr} against system outage probability for $B = 50$ bytes per device.} \label{fig:div_order} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \paragraph*{Quick reach to the maximum diversity gain} We study the empirical outage exponent of the proposed transmission scheme in \figref{fig:div_order}. For that purpose, we adopt a simulation setup where all links exhibit a single nominal average \gls{snr} value, i.e., removing the effect of large-scale fading in channel gain. The system outage probability is then simulated across a finite range of link \gls{snr}. As depicted in \figref{fig:div_order}, with optimal $\beta = \hat{\beta}$, the proposed protocol reaches quickly to the maximum achievable diversity order of $M+N-1$ at $M = 3$, confirming the derivation in \eqref{Eq:div_orde_2hop}. This is thanks to collecting the multi-user diversity gain at its best, by rate-adaptive scheduling of the devices with strong channel condition, while exploiting the spatial diversity gain from cooperative relaying towards the devices with poor channel condition. Interestingly, with $\beta = 1$, the gain from multi-user diversity can initially increase the outage exponent. By increasing \gls{snr}, where all devices will naturally be scheduled with the same transmission rate, the diversity order approaches to $M$, as was also suggested by the derivation in \eqref{Eq:div_order_1hop}. \if2 2 \begin{figure}[t] \begin{center} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{xlabel}[c][c][0.9]{number of devices, $N$} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_id_outage_population_pwr_14.eps} \caption{System outage probability against number of devices, $N$, for $P_a = P_d = 14$ dBm and $B = 50$ bytes per device.} \label{fig:comp_id_outage_population_pwr_14} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \if2 1 \begin{figure*} \centering \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{ylabel}[c][c][0.9]{empirical outage exponent} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 2$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{div_order_snr.eps} \caption{Empirical diversity order in finite \gls{snr} against system outage probability for $B = 50$ bytes per device.} \label{fig:div_order} \end{center} \end{minipage}\qquad \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{xlabel}[c][c][0.9]{number of devices, $N$} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{$\beta = 1$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x5}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_id_outage_population_pwr_14.eps} \caption{System outage probability against number of devices, $N$, for $P_a = P_d = 14$ dBm and $B = 50$ bytes per device.} \label{fig:comp_id_outage_population_pwr_14} \end{center} \end{minipage} \if2 1 \vspace{-35pt} \else \fi \end{figure*} \fi \paragraph*{Improved scalability with network size} In practical industrial networks, the number of devices connected to the same controller can become largely dynamic. Therefore, it is crucial for the transmission protocol to be able to scale with the network size, up or down, without depriving it of reliability. To that end, in \figref{fig:comp_id_outage_population_pwr_14} the system outage probability of the three transmission schemes are tested against a range of network sizes, i.e., the number of devices in the network, $N$. We fixed the packet size for each device to $B = 50$ bytes to imitate the realistic conditions. The system outage probability for the case of single-hop transmission with ideal rate adaptation increases, almost linearly, by increasing the network size. This is an expected outcome since the system is unable to gain from the increase in number of devices (maximum diversity order or $M$, as proposed in \eqref{Eq:div_order_1hop}). Thus, increasing the number of devices, merely translates into a higher likelihood of scheduling time-overflow. On the contrary, the proposed \gls{andcoop} protocol and the OccupyCoW protocol can benefit from the increase in network device. In fact, by increasing the network size, the potential cooperative diversity gain also increases, which in turn reduces the system outage probability. Meanwhile, by increasing the network size, the average transmission rate increases too, which has an opposite effect on outage probability. Therefore, for those two schemes, we observe a turning point for system outage probability. Overall, the proposed \gls{andcoop} can guarantee $\mathbb{P}_\tr{\tiny{out}} \leq 10^{-5}$ for $N \leq 180$ with $M = 3$ \glspl{ap} in this example. For the OccupyCoW scheme this reduces to only $2<N\leq 120$. It should be noted that at $N = 1$, the proposed scheme is equivalent to single-hop transmission since the total resources are allotted to the single device. Moreover, the overall scheduling overhead also increases with the number of devices increasing. However, since a fixed packet size per device is assumed in this analysis, by introducing a fixed scheduling overhead per device, the trend of the curves in \figref{fig:comp_id_outage_population_pwr_14} and the above conclusions will remain intact. \if2 1 \vspace{-10pt} \else \fi \subsection{Effect of Imperfect \gls{csi}} As discussed earlier in \secref{Sec:transmissionprotocol}, due to the inevitable \gls{csi} estimation error, the transmitter must use a back-off parameter $0 < \theta \leq 1$ to adjust the transmission rate that is adapted to the \gls{icsi}. Moreover, the effect of \gls{icsi} is only on the single-hop rate-adaptive transmission phase. The two-hop phase, thanks to the fixed-rate transmission, encounters no impact from the \gls{icsi}. Numerical optimization in presence of \gls{csi} error is a demanding task which requires exhaustive search for the optimal operating point across three parameters $L$, $\beta$ and $\theta$. Therefore, it is crucial to understand the impact that each of those parameters have on the performance in order to reduce the optimization complexity. \if2 1 \begin{figure*} \centering \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{number of pilot symbols per device, $L$} \psfrag{ylabel}[c][c][0.9]{system outage probability, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXXXx1}[lc][lc][0.59]{best case} \includegraphics[width=0.95\columnwidth,keepaspectratio]{T1_fixed_tradeoff.eps} \caption{System outage probability of the proposed \gls{andcoop} for different $\theta$ values. We fixed $P_a = P_d = 14$ dBm, $M = 1$, $N = 50$, $B = 50$ bytes and $\beta = 0.1$.} \label{fig:T1_tradeoff} \end{center} \end{minipage}\qquad \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{number of pilot symbols per device, $L$} \psfrag{ylabel}[c][c][0.9]{system outage probability, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXXXx1}[lc][lc][0.59]{best case} \includegraphics[width=0.95\columnwidth,keepaspectratio]{Rbo_fixed_tradeoff.eps} \caption{System outage probability of the proposed \gls{andcoop} for different $\beta$ values. We fixed $P_a = P_d = 14$ dBm, $M = 1$, $N = 50$, $B = 50$ bytes and $\theta = 0.6$.} \label{fig:Rbo_tradeoff} \end{center} \end{minipage} \if2 1 \vspace{-35pt} \else \fi \end{figure*} \fi \if2 2 \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{number of pilot symbols per device, $L$} \psfrag{ylabel}[c][c][0.9]{system outage probability, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXXXx1}[lc][lc][0.59]{best case} \includegraphics[width=0.95\columnwidth,keepaspectratio]{T1_fixed_tradeoff.eps} \caption{System outage probability of the proposed \gls{andcoop} for different $\theta$ values. We fixed $P_a = P_d = 14$ dBm, $M = 1$, $N = 50$, $B = 50$ bytes and $\beta = 0.1$.} \label{fig:T1_tradeoff} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \begin{figure}[t] \begin{center} \psfrag{xlabel}[c][c][0.9]{number of pilot symbols per device, $L$} \psfrag{ylabel}[c][c][0.9]{system outage probability, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{XXXXx1}[lc][lc][0.59]{best case} \includegraphics[width=0.95\columnwidth,keepaspectratio]{Rbo_fixed_tradeoff.eps} \caption{System outage probability of the proposed \gls{andcoop} for different $\beta$ values. We fixed $P_a = Pd = 14$ dBm, $M = 1$, $N = 50$, $B = 50$ bytes and $\theta = 0.6$.} \label{fig:Rbo_tradeoff} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \paragraph*{Fixing a small number of pilot symbols per device} To reduce the complexity of the exhaustive numerical optimization we restrict each of the three parameters $L$, $\beta$ and $\theta$, to a finite set of values. Then, for each triple, we simulate the system outage probability. The curves depicted against parameter $L$ in \figref{fig:T1_tradeoff}, show the course of system outage probability across different values of $\theta$ when we fixed $\beta = 0.1$. Similarly, in \figref{fig:Rbo_tradeoff}, system outage probability is depicted for different $\beta$ values while fixing $\theta = 0.6$. The best case system outage probability in both those figures, represents the minimum outage probability that is attainable at a given $L$ while optimizing against $\beta$ and $\theta$. The following observations are given. \begin{itemize} \item By increasing $L$, channel estimation error decreases, which in turn lowers the impact of $\theta$ on system outage probability for fixed $\beta$. \item By optimization across different values of $\beta$ and $\theta$, it becomes evident that system outage probability is within a small margin of the optimal value, across a wide range of $L$. In this example, choosing $2 \leq L \leq 30$, system outage probability remains roughly unchanged. \end{itemize} From those observations, to simplify the optimization process we propose to fix $L = 10$ and optimize only across $\beta$ and $\theta$. \if2 2 \begin{figure}[t] \begin{center} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{xlabel}[c][c][0.9]{transmit power (dBm)} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{\gls{icsi}} \psfrag{XXX4}[lc][lc][0.59]{\gls{pcsi}} \psfrag{XXX5}[lc][lc][0.59]{$M = 1$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_power_outage_reVSid.eps} \caption{Comparison of outage probability between \gls{icsi} and \gls{pcsi} for $N = 50$, $B = 50$ bytes per device and $L = 10$.} \label{fig:comp_power_outage_reVSid} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \if2 1 \begin{figure*} \centering \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{ylabel}[c][c][0.9]{probability of system outage, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{xlabel}[c][c][0.9]{transmit power (dBm)} \psfrag{XXX1}[lc][lc][0.59]{$\beta = \hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\beta = 0$} \psfrag{x3}[lc][lc][0.59]{\gls{icsi}} \psfrag{XXX4}[lc][lc][0.59]{\gls{pcsi}} \psfrag{XXX5}[lc][lc][0.59]{$M = 1$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{comp_power_outage_reVSid.eps} \caption{Comparison of outage probability between \gls{icsi} and \gls{pcsi} for $N = 50$, $B = 50$ bytes per device and $L = 10$.} \label{fig:comp_power_outage_reVSid} \end{center} \end{minipage}\qquad \begin{minipage}[b]{.47\textwidth} \begin{center} \psfrag{xlabel}[c][c][0.9]{system outage probability, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{ylabel}[c][c][0.9]{} \psfrag{X1}[lc][lc][0.59]{$\hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\hat{\theta}$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{opt_beta_rbo_re.eps} \caption{The optimal values $\hat{\beta}$ and $\hat{\theta}$ for \gls{icsi}, where $N = 50$, $B = 50$ bytes per device and $L = 10$.} \label{fig:opt_beta_rbo_re} \end{center} \end{minipage} \if2 1 \vspace{-35pt} \else \fi \end{figure*} \fi \paragraph*{Impact of channel estimation error is marginal} For fixed number of pilot symbols per device $L = 10$, we examine the performance degradation of the proposed \gls{andcoop} from \gls{icsi} with respect to the case of \gls{pcsi} under similar setup as in \figref{fig:comp_id_power}. As shown, for both cases of $M = 1$ and $M = 3$, in presence of \gls{icsi} the proposed scheme with $\beta = \hat{\beta}$ operates within a small 1-2 dB gap from the case of \gls{pcsi}. On the other hand, the gap for the case of single-hop rate-adaptive transmission can become very large, e.g., $~15$ dB for the case of $M = 3$. Such large \gls{snr} gap owes to high channel estimation error of the devices with poor channel quality during rate adaptation for single-hop transmission. Our proposed \gls{andcoop} circumvents that by identifying those devices and scheduling them over fixed-rate two-hop transmission. \if2 2 \begin{figure}[h] \begin{center} \psfrag{xlabel}[c][c][0.9]{system outage probability, $\mathbb{P}_\tr{\tiny{out}}$} \psfrag{ylabel}[c][c][0.9]{} \psfrag{X1}[lc][lc][0.59]{$\hat{\beta}$} \psfrag{x2}[lc][lc][0.59]{$\hat{\theta}$} \psfrag{XXX4}[lc][lc][0.59]{$M = 1$} \psfrag{x6}[lc][lc][0.59]{$M = 3$} \includegraphics[width=0.95\columnwidth,keepaspectratio]{opt_beta_rbo_re.eps} \caption{The optimal values $\hat{\beta}$ and $\hat{\theta}$ for \gls{icsi}, where $N = 50$, $B = 50$ bytes per device and $L = 10$.} \label{fig:opt_beta_rbo_re} \end{center} \if2 1 \vspace{-35pt} \else \fi \end{figure} \fi \paragraph*{Optimal value for $\beta$ and $\theta$ for fixed $L$} In \figref{fig:opt_beta_rbo_re}, the optimal values $\hat{\beta}$ and $\hat{\theta}$ are reported for fixed $L = 10$. Those values were used in \figref{fig:comp_power_outage_reVSid} for the proposed \gls{andcoop} in case of \gls{icsi}. It is evident that with a larger number of \gls{ap} antennas, on average a larger number of devices are scheduled with single-hop transmission (i.e., larger $\hat{\beta}$). Moreover, the optimal rate adjustment factor $\hat{\theta}$ is smaller, when the number of \gls{ap} antennas is smaller. As could be expected, both $\hat{\beta}$ and $\hat{\theta}$ have a non-increasing trend with system outage probability decreasing. This parallels our design analogy for ultra-reliable communication, where only the devices with strong channel conditions should undergo rate-adaptive transmission (i.e., smaller $\hat{\beta}$), and for those, a more conservative transmission rate adjustment factor is necessary (i.e., smaller $\hat{\theta}$). \section{Conclusion} \label{Sec:Conclusion} We proposed a channel-aware \gls{urllc} transmission protocol for industrial wireless control where a controller communicates with several devices in the \gls{dl}. The proposed transmission protocol uses the knowledge of instantaneous channel conditions of \gls{ap}-device links to identify devices with \emph{strong} and \emph{weak} channel conditions. The strong devices are served with a single-hop rate-adaptive transmission where the rate is adapted to the instantaneous channel. With this approach, multi-user diversity gain is exploited and frequency resources are efficiently utilized. Meanwhile, the weak devices enjoy a two-hop cooperative communication in which transmission rate is fixed and all the nodes in the network cooperate in relaying. We analyzed the system outage probability and the diversity order under the proposed transmission protocol. Through numerical analysis we derived optimal time division between the two sets of \emph{strong} and \emph{weak} devices and showed that such optimization can improve spectral efficiency by more than 0.5, 1 and 1.5 \gls{bpcu}, when the controller is equipped with 1, 2 and 3 \gls{ap} antennas, respectively. Moreover, we observed that the proposed \gls{andcoop} transmission protocol can effectively reduce the required transmit power for reliable industrial wireless control, improve the scalability with respect to network size, and marginalize the impact of channel estimation error on outage probability. The improvements are thanks to the instantaneous awareness to channel conditions that allows to exploit different sources of diversity gain in the network. As the continuation of this work in future, we will look into evaluating the performance of the proposed transmission protocol considering spatio-temporal correlation of shadowing caused by blockages. Further, we will study the use of dedicated full-duplex relay nodes in the proposed transmission protocol. \input{app.tex} \bibliographystyle{IEEEtran} \section{} \subsection{Proof of Proposition 1} \label{App:motiv} The achievable rate $\aR_{j}$ for device $j$ is given as \if2 1 \fontsize{9}{11}\selectfont \begin{align} \aR_{j} = W \log \left( 1 + \sum_{i \in \mathscr{A}} \ga{i}{j} \right), \end{align} \normalsize \else \begin{align} \aR_{j} = W \log \left( 1 + \sum_{i \in \mathscr{A}} \ga{i}{j} \right), \end{align} \fi measured in \gls{bps}. Then, the random time duration $\tau_j$, in seconds, required for successful transmission to device $j$ is equal to $\tau_j = \frac{B'}{\aR_{j}}$, where $B' = \frac{N}{K}B$ is the adjusted packet size per scheduled device for a given $K$. Note that $\aR_{j}$'s are \gls{iid} random variables which result in \gls{iid} $\tau_j$'s. The transmission from source to $K$ arbitrarily chosen devices is then \emph{successful} if the sum of $\tau_j$'s for those $K$ devices is not larger than $T$. Without loss of generality, let's assume $\tau_1 \leq \tau_2 \leq \ldots \leq \tau_N$, meaning that $\aR_1 \geq \aR_2 \geq \ldots \geq \aR_N$, where $\aR_j$'s form \emph{order statistics} drawn from \gls{cdf} $\cdf_{\aR}$. For the sake of better reliability (i.e., maximum diversity gain), the scheduler chooses the $K$ devices with best channels to transmit to, where $K \in \{1, 2, \ldots, N\}$. Thus, the probability of transmission error is equivalent to the probability of \emph{time overflow} given as \if2 1 \fontsize{9}{11}\selectfont \begin{align} \mathbb{P}_\tr{\tiny{out}} = \prob{ \sum_{j = 1}^{K} \tau_j \geq T} = \prob{ \sum_{j = 1}^{K} \frac{1}{\aR_{j}} \geq \frac{K T}{N B}}. \label{Eq:Pout-k-best} \end{align} \normalsize \else \begin{align}\nonumber \mathbb{P}_\tr{\tiny{out}} & = \prob{ \sum_{j = 1}^{K} \tau_j \geq T} \\ & = \prob{ \sum_{j = 1}^{K} \frac{1}{\aR_{j}} \geq \frac{K T}{N B}}. \label{Eq:Pout-k-best} \end{align} \fi The diversity gain $d$ from \eqref{Eq:dive_order_def} can be derived for the case of \gls{iid} Rayleigh fading for all links and fixed average \gls{snr} of $\rho$ over all links, as follows. First, note that \if2 1 \fontsize{9}{11}\selectfont \begin{align} \prob{ \frac{1}{\aR_{j}} \geq \frac{1}{R}} \overset{(a)}{=} \sum_{k = N - j + 1}^{N} \binom{N}{k} \cdf_{\aR}(R)^{k} \left(1 - \cdf_{\aR}(R) \right)^{N-k} \overset{(b)}{=} \sum_{k = N - j + 1}^{N} \binom{N}{k} \Pm{M,R}^{k} \left(1 - \Pm{M,R} \right)^{N-k}, \end{align} \normalsize \else \begin{align} \prob{ \frac{1}{\aR_{j}} \geq \frac{1}{R}} & \overset{(a)}{=} \sum_{k = N - j + 1}^{N} \binom{N}{k} \cdf_{\aR}(R)^{k} \left(1 - \cdf_{\aR}(R) \right)^{N-k} \\ \nonumber & \overset{(b)}{=} \sum_{k = N - j + 1}^{N} \binom{N}{k} \Pm{M,R}^{k} \left(1 - \Pm{M,R} \right)^{N-k}, \end{align} \fi where $(a)$ follows from the \gls{cdf} of the $N - j + 1$th order statistics \cite[Chapter~6]{Mittelhammer99} and $(b)$ follows from \eqref{Eq:pfail}. Using the approximations $\Pm{m,R} \approx (\frac{\omega}{P_t})^m$ and $\left( 1 - \Pm{m,R} \right) \approx 1$ for $\frac{\omega}{P_t} \rightarrow 0$ \cite{Laneman:2003}, the following holds for any bounded real value $R$. \if2 1 \fontsize{9}{11}\selectfont \begin{align} d_j = - \lim_{P_t \rightarrow \infty} \frac{\log \prob{ \frac{1}{\aR_{j}} \geq \frac{1}{R}}}{\log P_t} = - \lim_{P_t \rightarrow \infty} \frac{\log \sum_{k = N - j + 1}^{N} \binom{N}{k} (\frac{\omega}{P_t})^{k \cdot M} } {\log P_t} = M (N - j + 1) \label{Eq:div-best-j} \end{align} \normalsize \else \begin{align}\nonumber d_j & = - \lim_{P_t \rightarrow \infty} \frac{\log \prob{ \frac{1}{\aR_{j}} \geq \frac{1}{R}}}{\log P_t} \\ \nonumber & = - \lim_{P_t \rightarrow \infty} \frac{\log \sum_{k = N - j + 1}^{N} \binom{N}{k} (\frac{\omega}{P_t})^{k \cdot M} } {\log P_t} \\ & = M (N - j + 1) \label{Eq:div-best-j} \end{align} \fi For the case where $K = 1$ device with the best channels is transmitted to, the diversity gain follows from \eqref{Eq:div-best-j} as \begin{align} d = M N. \end{align} For $K > 1$, the maximum diversity gain follows from the choice of $K$ devices with best channels where the probability of outage $\mathbb{P}_\tr{\tiny{out}}$ from \eqref{Eq:Pout-k-best} is bounded as follows \if2 1 \fontsize{9}{11}\selectfont \begin{align}\nonumber \prob{ \frac{1}{\aR_{K}} \geq \frac{K T}{N B}} \leq \prob{ \sum_{j = 1}^{K} \frac{1}{\aR_{j}} \geq \frac{K T}{N B}} \leq \prob{ \frac{1}{\aR_{K}} \geq \frac{T}{N B}}. \end{align} \normalsize \else \begin{align}\nonumber \prob{ \frac{1}{\aR_{K}} \geq \frac{K T}{N B}} \leq \prob{ \sum_{j = 1}^{K} \frac{1}{\aR_{j}} \geq \frac{K T}{N B}} \leq \prob{ \frac{1}{\aR_{K}} \geq \frac{T}{N B}}. \end{align} \fi Therefore, the diversity order of $\mathbb{P}_\tr{\tiny{out}}$ is bounded on both sides by $M(N - K + 1)$ according to \eqref{Eq:div-best-j}, which concludes \if2 1 \fontsize{9}{11}\selectfont \begin{align} d = M (N - K + 1). \end{align} \normalsize \else \begin{align} d = M (N - K + 1). \end{align} \fi \if2 1 \vspace{-15pt} \fi \if2 1 \def \scaletemp {0.55} \else \def \scaletemp {1} \fi \subsection{Proof of Proposition 2} \label{App:A} Although a closed form of outage probability in \eqref{Eq:outage-1hop} is not available, the outage probability $\mathbb{P}_\tr{\tiny{out}} = P_{1h}(\Toh)$ is bounded as follows. \if2 1 \fontsize{9}{11}\selectfont \begin{align}\label{Eq:bounds} \resizebox{\scaletemp\columnwidth}{!}{$1 - \left(1 - \Pm{M,\frac{B}{\Toh}}\right)^N \leq \mathbb{P}_\tr{\tiny{out}} \leq 1 - \left(1 - \Pm{M,\frac{N B}{\Toh}}\right)^N$} \end{align} \normalsize \else \begin{align}\label{Eq:bounds} \resizebox{\scaletemp\columnwidth}{!}{$1 - \left(1 - \Pm{M,\frac{B}{\Toh}}\right)^N \leq \mathbb{P}_\tr{\tiny{out}} \leq 1 - \left(1 - \Pm{M,\frac{N B}{\Toh}}\right)^N$} \end{align} \fi The upper bound in \eqref{Eq:bounds} is realized by dividing the time $\Toh$ equally among the devices, while the lower bound is realized by allotting the time $\Toh$ to every device. Therefore, denoting the diversity order of the upper and the lower bounds in \eqref{Eq:bounds}, respectively, by $d_\text{\tiny{upper}}$ and $d_\text{\tiny{lower}}$, it can be concluded from \eqref{Eq:dive_order_def} that \begin{align}\label{Eq:bounds_d} d_\text{\tiny{upper}} \leq d \leq d_\text{\tiny{lower}}. \end{align} Using the approximation $\Pm{m,R} \approx (\frac{\omega}{P_t})^m$ for $\frac{\omega}{P_t} \rightarrow 0$ \cite{Laneman:2003}, the following holds for any bounded real value $R$. \if2 1 \fontsize{9}{11}\selectfont \begin{align}\nonumber - \lim_{P_t \rightarrow \infty} \frac{\log 1 - \left(1 - \Pm{M,R} \right)^N}{\log P_t} = - \lim_{P_t \rightarrow \infty} \frac{\log N (\frac{\omega}{P_t})^M}{\log P_t} = M \end{align} \normalsize \else \begin{align}\nonumber - \lim_{P_t \rightarrow \infty} \frac{\log 1 - \left(1 - \Pm{M,R} \right)^N}{\log P_t} = - \lim_{P_t \rightarrow \infty} \frac{\log N (\frac{\omega}{P_t})^M}{\log P_t} = M \end{align} \fi Therefore, we have $d_\text{\tiny{upper}} = d_\text{\tiny{lower}} = M$, which according to \eqref{Eq:bounds_d} yields \eqref{Eq:div_order_1hop}. \subsection{Proof of Proposition 3} \label{Proof_prop_2h} We start from the probability of outage $\mathbb{P}_\tr{\tiny{out}} = P_{2h}(\mathscr{D})$ in \eqref{Eq:Ptwohop-4}. First note that for $P_t \rightarrow \infty$, where $n>0$ we have \if2 1 \fontsize{9}{11}\selectfont \begin{align}\label{Eq:qr-prop} \frac{\Pm{M+n,\Rth{r}} }{ \Pm{M,\Rth{b}} } = \frac{ \left( \frac{\omega_{2\text{h},r}}{P_t} \right)^{M+n}}{\left( \frac{\omega_{2\text{h},b}}{P_t} \right)^M }, \end{align} \normalsize \else \begin{align}\label{Eq:qr-prop} \frac{\Pm{M+n,\Rth{r}} }{ \Pm{M,\Rth{b}} } = \frac{ \left( \frac{\omega_{2\text{h},r}}{P_t} \right)^{M+n}}{\left( \frac{\omega_{2\text{h},b}}{P_t} \right)^M }, \end{align} \fi where $\omega_{2\text{h},b} = W \cdot \sigma_0 \cdot (2^{\Rth{b}/W} - 1)$, and $\omega_{2\text{h},r} = W \cdot \sigma_0 \cdot (2^{\Rth{r}/W} - 1)$, and \if2 1 \fontsize{9}{11}\selectfont \begin{align} \Rth{b} & = \frac{NB}{\alpha T} = \frac{W r \log P_t}{\alpha}, \\ \Rth{r} & = \frac{NB} { (1-\alpha) T} = \frac{W r \log P_t}{1- \alpha}. \end{align} \normalsize \else \begin{align} \Rth{b} & = \frac{NB}{\alpha T} = \frac{W r \log P_t}{\alpha}, \\ \Rth{r} & = \frac{NB} { (1-\alpha) T} = \frac{W r \log P_t}{1- \alpha}. \end{align} \fi For the case where $n = 0$ and $\alpha \geq 0.5$, we have $q_{r}^{(M+n)} = 1$. Otherwise, $q_{r}^{(M+n)}$ is derived using \eqref{Eq:qr-prop}. Therefore, in the limit of $P_t \rightarrow \infty$, we use the following approximation, \if2 1 \fontsize{9}{11}\selectfont \begin{align}\label{Eq:a-qr-approx} 1 - \left( 1 - {q_{r}^{(M+n)}} \right)^{(N-n)} \approx \left\{\begin{matrix} 1 & n = 0 \; \& \; \alpha \geq \frac{1}{2} \\ (N-n) q_{r}^{(M+n)} & \tr{otherwise} \end{matrix}\right. \end{align} \normalsize \else \begin{align}\label{Eq:a-qr-approx} 1 - \left( 1 - {q_{r}^{(M+n)}} \right)^{(N-n)} \approx \left\{\begin{matrix} 1 & n = 0 \; \& \; \alpha \geq \frac{1}{2} \\ (N-n) q_{r}^{(M+n)} & \tr{otherwise} \end{matrix}\right. \end{align} \fi We further use the approximation $\left(1-q_{b}^M \right)^{n} \approx 1$ in high \gls{snr}. Thus, we obtain \if2 1 \fontsize{9}{11}\selectfont \begin{align}\label{Eq:two-hop-approx-outage-div} \mathbb{P}_\tr{\tiny{out}} & \approx \sum_{n = 0}^{N-1}\left( q_{b}^{M}\right)^{(N-n)} \binom{N}{n} \left( 1 - \left( 1 - {q_{r}^{(M+n)}} \right)^{(N-n)} \right). \end{align} \normalsize \else \begin{align}\label{Eq:two-hop-approx-outage-div} \mathbb{P}_\tr{\tiny{out}} & \approx \sum_{n = 0}^{N-1}\left( q_{b}^{M}\right)^{(N-n)} \binom{N}{n} \left( 1 - \left( 1 - {q_{r}^{(M+n)}} \right)^{(N-n)} \right). \end{align} \fi Using the approximation in \eqref{Eq:a-qr-approx} it easily follows that for $M > 1$, the slowest term in \eqref{Eq:two-hop-approx-outage-div} approaching zero as $P_t \rightarrow \infty$ is the term of $n = N - 1$. Therefore, we use this term to approximate $\mathbb{P}_\tr{\tiny{out}}$, where substituting in \eqref{Eq:dive_order_def} yields \eqref{Eq:DMT-2hop}. \end{appendix}
{'timestamp': '2020-09-22T02:00:07', 'yymm': '2009', 'arxiv_id': '2009.08975', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08975'}
arxiv
\section{Introduction} The quality of automatic speech recognition and machine translation of texts is constantly increasing. It leads to an opportunity to connect these two components and use them for spoken language translation (SLT). The output of the SLT system can be delivered to users either as speech or text. In simultaneous SLT, where the output has to be delivered during the speech with as low delay as possible, there is a trade-off between latency and quality. With textual output, it is possible to present users with early, partial translation hypotheses in low latency, and correct them later by final, more accurate updates, after the system receives more context for disambiguation, or after a secondary big model produces its translation. Rewriting brings another challenge, the stability of output. If the updates are too frequent, the user is unable to read the text. The problem of unstable output could be solved by using big space for showing subtitles. The unstable, flickering output would appear only at the end, allowing the user to easily ignore the flickering part and read only the stabilized part of the output. However, in many situations, the space for subtitles is restricted. For example, if the users have to follow the speaker and slides at the same time, they lack mental capacity for searching for the stabilized part of translations. It is, therefore, necessary to put the subtitles and slides on the same screen, restricting the subtitling area to a small window. In this paper, we propose an algorithm for presenting SLT subtitles in limited space, a way for estimating the overall usability of simultaneous SLT subtitling in a limited area, and an improved translation latency measure for SLT comparison. \hidelong{\cref{pipeline} describes the properties of SLT for use with our subtitler. \cref{subtitler} details the main new component for presenting a text stream as readable subtitles. \cref{empirical} proposes the estimation of the usability of the subtitling of multiple realistic SLT systems. We conclude the paper in \cref{conclusion}. } \section{Re-Translating Spoken Language Translation} \label{pipeline} Our subtitler solves the problem of presentation of SLT output with a re-translating early hypothesis, similarly to \perscite{niehues2016inter,arivazhagan2019retranslation,Arivazhagan2020RetranslationVS}. Although it can also present the subtitles from the automatic speech recognition (ASR) that re-estimates the early hypothesis, or generally any audio-to-text processor, we limit ourselves only SLT in this paper for brevity. \hidelong{\subsection{Stable and Unstable Segments}} \hidelong{ SLT systems output a potentially infinite stream of segments containing the beginning and final timestamps of an interval from the source audio, and the translated text in the interval. We assume that the segments can be marked as \emph{stable} and \emph{unstable}, depending on whether the system has the possibility to change them or not. This is a realistic assumption because the ASR and SLT systems usually process a limited window of the source audio. Whenever a part of source audio exceeds this window, the corresponding output becomes stable. } \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{brief-subtitler.pdf} \caption{Illustration of speech translation subtitling in two subsequent inputs from SLT. The input arrives as a sequence of quadruples: segment beginning time, segment end time, stable/unstable flag, text. The rectangles indicate the content of the subtitling area of one line.} \label{fig:illustration} \end{figure*} \begin{figure} \centering \includegraphics[width=0.4\textwidth]{diagram.pdf} \caption{Subtitler processing of the inputs in \cref{fig:illustration} with different timings. In the left one, Input 2 changes the word ``Es'', which has been read by the user and scrolled away and causes a reset of a window start. In the right one, the word ``Es'' is changed in the window on the current display.} \label{fig:diagrams} \end{figure} \hideXXX{ \subsection{Sentence-Level MT for On-line Translation} \XXX{R1: You go into a lengthy explanation and then say that actual implementation is part of future work.} With all the messages aligned to sentence boundaries, we can use off-the-shelf MT systems. Most of these systems expect to translate individual sentences, so it does not cause any further harm if we indeed send them the input sentence by sentence. However, it is essential to know that this can be only a temporary solution. Many sentences crucially depend on the context of the previous ones, and ignoring this context will lead to translation errors. An ideal MT system for our use-case would still process individual sentences, but it would be trained with the context from previous sentences. The API of this system should expect not only the new input sentence but also a representation of the previous sentences, e.g., a context vector. The new sentence would be translated taking this context vector into account, and an updated context vector would be returned along with the translation. \XXX{R2: unproven hypothesis} The actual implementation of such an approach is our planned future work. Another essential feature of an ideal system would be the \emph{stability} of translation candidates for partial sentences. As mentioned above, we feed not only complete sentences to the system but also the \emph{incoming} ones. If some new words appended to a previous version of the incoming sentence lead MT to word reordering, the presentation of such translation would ``flicker'', making the output impossible to follow. While there are already strategies to reducing this problem, e.g., wait-$k$ policy \parcite{Ma2018STACLST}, an ultimate solution may not be possible for some language pairs without an extended delay to receive all critical elements of the sentence. In this paper, we experiment with open-source MT solution Marian \parcite{mariannmt}, which still does not have this improved stability. \XXX{R2: unproven hypothesis} Empirical results of our solution presented in \cref{empirical} can only get better when adopting a stable MT system. } \section{Subtitler} \label{subtitler} This section presents the design and algorithm of ``subtitler''. The subtitler is a cache on a stream of input messages aiming to satisfy the following conflicting needs: \begin{itemize}[nosep] \item The output should be presented with the lowest possible delay to achieve the effect of simultaneous translation as much as possible. \item The flickering of the partial outputs is partially desired because it highlights the simultaneity of the translation and comforts the user in knowing that the system is not stuck. \item The flickering should be minimized. If some output was presented at a position of the screen, it should keep the position until it is outdated. \item The user must have enough time to read the message. \item Only a predefined space of $w$ (width) characters and $h$ (height) lines are available. \end{itemize} Given an input stream of stable and unstable segments as described above, the subtitler emits a stream of ``subtitle windows''. On every update, the former window is replaced by a new one. The basic operation of subtitler is depicted in \cref{fig:illustration,fig:diagrams}. The elements of subtitler are a buffer of input segments, a presentation window, and two independent processing threads. The buffer is an ordered list of segments. The presentation window is organized as a list of text lines of the required width and count. The count corresponds to the height of subtitling window plus one, to allow scrolling-up the top line after displaying it for minimum reading time. This line view is regenerated whenever needed from the current starting position of the window in the buffer, wrapping words into lines. The \emph{input thread} receives the input stream and updates the buffer. It replaces outdated segments with their new versions, extends the buffer, and removes old unnecessary segments. If an update happens within or before the current position of the presentation window, the \emph{output thread} is notified for a forced update. Independently, the \emph{output thread} updates the position of the presentation window in the buffer, obeying the following timeouts and triggers: \begin{itemize}[nosep] \item On forced updates, the output thread detects if any content changed before the beginning of the already presented window, which would cause a \emph{reset}. In that case, the window position on the window buffer has to be moved back, and the content for the user can no longer be presented incrementally. Instead, the beginning of the first line in the window shows a newer version of an old sentence that has already scrolled away. \item If the first line of the presentation window has not been changed for a minimum reading time and if there is any input to present in the extra line of the window, the window is ``scrolled'' by one line, i.e., the first line is discarded, the window starting position within the buffer is updated, and the extra line is shown as the last line of the window. \item If the whole presentation window has not been changed for a long time, e.g., 5 or 20 seconds, it is blanked by emitting empty lines. \end{itemize} \subsection{Timing Parameters} The subtitler requires two timing parameters. A line of subtitles is displayed to a user for a ``minimum reading time'' before it can be scrolled away. If no input arrives for a ``blank time'', the subtitling window blanks to indicate it and to prevent the user from reading the last message unnecessarily. We suggest adopting the minimum reading time parameter from the standards for subtitling films and videos (e.g., \inparcite{fotios}), before standards for simultaneous SLT subtitling will be established. \perscite{Szarkowska2018ViewersCK} claim that 15 characters per second is a standard reading time in English interlingual subtitling of films and videos for deaf and hard hearing. The standards in other European regions are close to 15 characters per second. We use this value for the evaluation in this work. \section{Estimating Usability} \label{empirical} The challenges in simultaneous SLT are quality, latency, and stability \cite{niehues2016inter,arivazhagan2019retranslation}. All of these properties are critical for the overall usability of the SLT system. The quality of translation is a property of the SLT system. The subtitler has no impact on it. The minimum reading time ensures the minimum level of stability, ensuring that every stable content is readable, and may increase the latency if the original speech is faster than reading time. The size of the subtitling window and timing parameters affect overall latency and stability. The bigger the window, the longer updates of translations fit into it without a reset. The \hideXXX{myslim, ze tu ma byt minimum reading time, vsude, az do konce odstavce: DM: nema. Blanking time ovlivnuje resety. Mozna ma byt jak minimum reading, tak blanking... OB: tak tedy oba, protoze minimum reading urcite. Kdyz uz radku prectes (tj. uplyne minumum reading), tak se odroluje a hrozi reset. Blanking typicky *nezazijes*, protoze je az po 20 vterinach bez vstupu. OB: napisme proste "timing constants"? timing parameters OK, DM: Ale nekdy jo. Spocital jsem resety pro 3 radky a pro ASR, kde se vsechny maji vejit, to nekde udelalo reset kvuli tomu. OK, chapu. Myslim, ze ted je to dobre. Pozor, dal jsou dalsi veci.} timing parameters determine how long the content stays unchanged in the window before scrolling. A small subtitling window or a short reading or blanking time may cause a reset. Every reset increases latency because it returns to the already displayed content. On the other hand, the significant latency may improve stability by skipping the early unstable hypotheses and present only the stable ones. We provide three automatic measures for assessing the practical usability of simultaneous SLT subtitling on the test set. The automatic evaluation may serve for a rough estimation of the usefulness, or for selection of the best candidate setups. We do not provide a strict way to judge which SLT system and subtitling setup are useful and which are not. The final decision should ideally consider the particular display conditions, expectations, and needs of the users, and should be based on a significant human evaluation. \subsection{Evaluation Measures} For quality, we report an automatic machine translation measure BLEU computed by sacrebleu \cite{post-2018-call} after automatic sentence alignment using mwerSegmenter \cite{segmentation:matusov:2005:iwslt}. BLEU is considered as correlating with human quality judgement. The higher BLEU, the higher translation quality. To explain the measure of latency and stability, let us use the terminology of \perscite{arivazhagan2019retranslation}. The \emph{EventLog} is an ordered list of \emph{events}. The $i^{th}$ \emph{event} is a triple $s_i, o_i, t_i$, where $s_i$ is the source text recognized so far, $o_i$ is the current SLT output, and $t_i$ is the time when this event was produced. Source and output, $s_i$ and $o_i$, are sequences of tokens. Let us denote $c(o_i)$ a transformation of a token sequence into a sequence of characters, including spaces and punctuation. Let $I$ be the number of all events, with an update either in source or output, and $T$ the number of events with an update in translation. \subsubsection{Character Erasure} To evaluate how many updates fit into the subtitling window, we define \emph{character erasure} (cE). It is the number of characters that must be deleted from the tail of the current translation hypothesis to update it to a new one. If a new translation only appends words to the end, the erasure is zero. The \emph{character erasure} is cE$(i) = |c(o_{i-1})| - |LCP(c(o_i),c(o_{i-1}))|$, where the $LCP$ stands for the longest common prefix. The average character erasure is AcE = $1/T \sum_{i=1}^I $cE$(i)$. It is inspired by the normalized erasure (NE) by \perscite{arivazhagan2019retranslation}, but we do not divide it by the output length in the final event, but only by the number of translation events. \subsubsection{Translation Latency with Sentence-Alignment Catch-up} The translation latency may be measured with the use of a \emph{finalization event} of the $j$-th word in output. It is $f(o,j) = min_i$ such that $o_{i',j'} = o_{I,j'}$ $\forall i'\ge i$ and $\forall j'\le j$. In other words, the word $j$ is finalized in the first event $i$, for which the word $j$ and all the preceding words $j'$ remain unchanged in all subsequent events $i'$. The translation latency of output word $j$ is the time difference of the finalization event of the word $j$ in the output and its \emph{corresponding} word $j^*$ in the source. \perscite{arivazhagan2019retranslation} estimate the source word simply as $j^* = (j/|o_I|) |s_I|$. This is problematic if the output is substantially shorter than input, because then it may incorrectly base the latency on a word which has not been uttered yet, leading to a negative time difference. A proper word alignment would provide the most reliable correspondence. However, we propose a simpler and appropriately reliable solution. The following improved measure is our novel contribution. We use it to compare the SLT systems. We utilize the fact that our ASR produces punctuated text, where the sentence boundaries can be detected. The sentences coming from SLT and ASR in their sequential order are parallel. They can be simply aligned because our SLT systems translate the individual sentences and keep the sentence boundaries. If the SLT does not produce individual sentences, then we use a rule-based sentence segmenter, e.g. from \perscite{moses}, and must be aware of the potential inaccuracy We use the sentence alignment for a catch-up, and the simple temporal correspondence of \perscite{arivazhagan2019retranslation} only within the last sentence. To express it formally, let us assume that the EventLog has also a function $S(o,j)$, returning the index of the sentence containing the word $j$ in $o$, and $L(o,k)$, the length of the sentence $k$ in $o$. Let $x(j) = j-\sum_{i=1}^{S(o,j)-1} L(o,i)$ be the index of an output word $j$ in its sentence. Then we define our caught-up correspondence as \DeclarePairedDelimiter\floor{\lfloor}{\rfloor} $j^{**} = \sum_{i=1}^{S(o,j)-1} L(s,i) + x(j) \floor*{\frac{L(s,S(o,j))}{L(o,S(o,j))}}$ \label{form:sdfsd} \defTL$^{*}${TL$^{*}$} Finally, our \emph{translation latency with sentence-alignment catch-up} is TL$^{*}(o,j) = t_{f(o,j)} - t_{f(s,j^{**})}$. This is then averaged for all output words in the document: TL$^{*}$ $= \frac{1}{|o_I|} \sum_{j=1}^{|o_I]} TL^*(o,j)$. \hidelong{\footnote{For a set of documents $D$, the TL$^{*}$ $= \frac{\sum_{o,I\in D}\sum_{j=1}^{|o_I]} TL^*(o,j)}{\sum_{o,I\in D}|o_I|}$.}} \subsection{SLT Evaluation} We use one ASR system for English and nine SLT systems from English into Czech (three different models differing in the data and training parameters), German (2 different systems), French (2 different systems), Spanish and Russian. All the SLT systems are cascades of an ASR, a punctuator, which inserts punctuation and capitalization to unsegmented ASR output, and a neural machine translation (NMT) from the text. \hidelong{The systems and their quality measures are in \cref{tab:scores}.} DE A, ES, and FR B are NMT adapted for spoken translation as in \perscite{Niehues_2018}. The others are basic sentence-level Transformer NMT connected to ASR. The ASR is a hybrid DNN-HMM by \perscite{janus-iwslt}. We evaluate the systems on IWSLT tst2015 dataset. \hidelong{We downloaded the referential translation from the TED website as \perscite{arivazhagan2019retranslation}, and removed the single words in parentheses because they were not verbatim translations of the speech, but marked sounds such as applause, laughter, or music. } \hidelong{ \begin{table}[t] \centering \caption{Quality measure of the English ASR and SLT systems from English into the target language in the left-most column, on IWSLT tst2015. The letters A, B, C denote different variants of SLT systems with the same target. Translation lag (TL$^{*}$) is in seconds. AcE is average character erasure, NE is normalized erasure.} \label{tab:scores} \small \begin{tabular}{l|rrrrrr} \bf SLT & \bf BLEU & \bf TL$^{*}$ & \bf AcE & \bf NE\\ \hline EN (ASR) &58.4747 & & 29.22 & 5.88 \\ \hline CZ A & 17.5441 & 2.226 & 24.20 & 7.05 \\ CZ B &12.2914 & 2.622 & 29.48 & 5.30 \\ CZ C &18.1505 & 2.933 & 27.90 & 3.93 \\ \hline DE A &15.2678 & 3.506 & 47.32 & 1.39 \\ DE B &15.9672 & 1.845 & 38.12 & 5.46 \\ \hline ES &21.8516 &5.429 & 43.30 & 1.49 \\ \hline FR A & 25.8964 & 1.269 & 31.97 & 3.32 \\ FR B &20.5367 & 5.425 & 47.92 & 1.46 \\ \hline RU &11.6279 & 3.168 & 31.78 & 4.05 \\ \end{tabular} \end{table} } \subsection{Reset Rate} \begin{figure} \centering \includegraphics[width=0.7\columnwidth]{plot.pdf} \caption{The percentage of translation updates in the validation set with the character erasure less than or equal to the value on the $x$-axis, for all our ASR and SLT systems.% \hideXXX{Nesla by osa x nazvat jednoduseji? Nebo aspon napsat: DM: jde to pripsat.} The $x$-axis corresponds with the size of the subtitling window.} \label{fig:cdf} \end{figure} The average character erasure does not reflect the frequency and size of the individual erasures. Therefore, in \cref{fig:cdf}, we display the cumulative density function of character erasure in the dataset. The vertical axis is the percentage of all translation updates, in which the character erasure was shorter or equal than the value on the horizontal axis. E.g., for the subtitler window with a total size of 140 characters, 99.03 \% of SLT updates of the SLT CZ A fit into this area. \cref{tab:cdf} displays the same for selected sizes, which fit into 1, 2, and 3 lines of subtitler window of size 70, and also the percentage of updates without any erasure ($x=0$). The values approximate the expected number of resets. However, the resets are also affected by the blanking time, so the real number of resets may be higher if the speech contains long pauses. The percentage in \cref{fig:cdf} serves as a lower bound. \hidelong{ \begin{table}[] \small \centering \caption{Percentage of character erasures in all translation updates, which are shorter or equal than $x$ characters, for selected values of $x$.} \label{tab:cdf} \begin{tabular}{l|ccccc} SLT & $x = 0$ & $x = 70$ & $x = 140$ & $x = 210$ \\ \hline EN (ASR) & 20.76 & 84.23 & 99.96 & 100.00 \\ CZ A & 41.37 & 91.98 & 99.03 & 99.76 & \\ CZ B & 28.61 & 89.78 & 98.63 & 99.77 & \\ CZ C & 30.93 & 88.31 & 98.53 & 99.72 & \\ FR A & 31.65 & 84.47 & 98.14 & 99.51 & \\ RU & 35.42 & 85.17 & 97.82 & 99.38 & \\ ES & 29.01 & 71.71 & 97.08 & 99.43 & \\ DE B & 27.89 & 80.90 & 97.05 & 99.38 & \\ DE A & 30.85 & 67.65 & 95.83 & 99.13 & \\ FR A & 30.39 & 66.15 & 95.67 & 99.39 & \\ \end{tabular} \end{table} } \subsection{Subtitling Latency} \hidelong{ \begin{figure}[t] \centering \includegraphics[width=0.7\columnwidth]{subtitler-lag-only-1.pdf} \caption{Subtitling latency (y-axis) over time (x-axis) for tst2015.en.talkid1922 translated by CZ A. The subtitling window has the width 70 and height 1, 2 and 3 lines. The minimum reading time is 15 characters per second (one line per 4.7s).} \label{fig:subtitler-lag} \end{figure} } The \emph{subtitling latency} is the difference of the finalization time of a word in subtitler and in the SLT. \hidelong{We count it similarly as the translation latency, but the word correspondence is the identity function because the language in SLT and subtitler is the same.} We computed the latency caused by the subtitler with 1, 2, and 3 lines of width 70 for one talk and SLT systems, see \cref{fig:subtitler-lag}. Generally, the bigger the translation window, the lower latency. \hideXXX{ The subtitling is useful only when the latency is continuously low. We can observe that in the case of the talk tst2015.en.talkid1922 translated by CZ A (\cref{fig:subtitler-lag}, top), the latency is around zero for 3-line window and below 10 seconds for 2-line window only at the first 400 seconds of the talk. After that, the latency is increasing up to 40 seconds, so the subtitling is desynchronized with the original and probably useless. In the second example (bottom plot), the subtitling is useless from the point where the talk starts. } \hideXXX{The long latency may be induced by the low stability of SLT, by the length of incoming segments, by the talking speed, or by other reasons. Our primary motivation in this work is to propose how to estimate the usefulness of the simultaneous subtitling of SLT in a limited area. We leave the analysis of subtitling latency for future work.} \subsection{User Evaluation} \begin{table}[] \centering \caption{Results of user evaluation with three subtitling windows of different heights (h). Quality level 4 is the highest, 1 is the lowest. The right-most column is the percentage of erasures fitting into the subtitling window.} \label{tab:rating} \small \begin{tabular}{r|r@{~}r@{~}r@{~}r|r} & \multicolumn{4}{c|}{Percentage of quality levels} \\ height & level=1 & level=2 & level=3 & level=4 & cE $<70\cdot h$\ \\ \midrule $h = 1$ & 35.27 \% & 28.79 \% & 14.95 \% & 20.99 \% & 88.59 \% \\ $h = 2$ & 11.08 \% & 29.94 \% & 35.73 \% & 23.24 \% & 98.73 \% \\ $h = 3$ & 16.33 \% & 19.90 \% & 33.67 \% & 30.11 \% & 99.64 \% \\ \end{tabular} \end{table} We asked one user to rate the overall fluency and stability of subtitling for the first 7-minute part of tst2015.en.talkid1922 translated by CZ A. We presented the user with the subtitles three times, in a window of width 70 and heights 1, 2 and 3. The minimum reading time parameter was 15 characters per second. The user was asked to express his subjective quality assessment by pressing one of five buttons: undecided (0), horrible (1), usable with problems (2), minor flaws, but usable (3), and perfect (4). The user was asked to press them simultaneously with reading subtitles, whenever the assessment changes. The source audio or video was not presented, so this setup is comparable to situations where the user does not understand the source language at all. The user is a native speaker of Czech. \cref{tab:rating} summarizes the percentage of the assessed duration and the quality levels. The user has not used the level undecided (0). The main problem that the user reported was limited readability due to resets and unstable translations. The flaws in usable parts of subtitling were subtle changes of subtitles which did not distract from reading the new input, or disfluent formulations. In the right-most column of \cref{tab:rating} we show the percentage of erasures in the part of the evaluated document which fit into the subtitling window. We hypothesize that the automatic measure of character erasure may be used to estimate the user assessment of readability. \section{Conclusion} \label{conclusion} We proposed an algorithm for presenting automatic speech translation simultaneously in the limited space of subtitles. The algorithm is independent of the SLT system. It ensures the minimum level of stability and allows simultaneity. Furthermore, we propose a way of estimating the reader's comfort and overall usability of the SLT with subtitling in limited space, and observe correspondence with user rating. Last but not least, we suggested a catch-up based on sentence-alignment in ASR and SLT to measure the translation latency simply and realistically. \section*{Acknowledgments} The research was partially supported by the grant CZ.07.1.02/0.0/0.0/16\_023/0000108 (Operational Programme -- Growth Pole of the Czech Republic), H2020-ICT-2018-2-825460 (ELITR) of the EU, 398120 of the Grant Agency of Charles University, and by SVV project number 260 575. \small
{'timestamp': '2020-09-22T02:01:10', 'yymm': '2009', 'arxiv_id': '2009.09016', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09016'}
arxiv
\section*{Acknowledgements} The work of EM was supported in part by NSF Grant Nos. NSF CCF-1907591, DMS-1800446. FAK acknowledges the support of the National Science Foundation under grants CMMI-1759823 and DMS1759824. \bibliographystyle{plain} \section{Introduction} Topological data analysis (TDA) is a field consisting of tools aimed at extracting shape in data. Persistent homology, one of the most commonly used tools from TDA, has proven useful in the field of time series analysis. Specifically, persistent homology has been shown to quantify features of a time series such as periodic and quasiperiodic behavior \cite{Perea2015,Sanderson2017,Tempelman2019,Maletic2016,Xu2018} or chaotic and periodic behavior \cite{Myers2019,Khasawneh2015}. Existing applications in time series analysis include studying machining dynamics \cite{Khasawneh2017,Khasawneh2018a,Yesilli2019b,Khasawneh2015,Yesilli2019a,Khasawneh2018b,Khasawneh2014a}, gene expression \cite{Perea2015, Berwald2014}, financial data \cite{Gidea}, video data \cite{tralie2018quasi,tralie2016high}, and sleep-wake states \cite{Chung2019, Tymochko2020}. These applications typically involve summarizing the underlying topological shape of each time series in a persistence diagram then using additional methods to analyze the resulting collection of persistence diagrams. While these applications have been successful, the task of analyzing a collection of persistence diagrams can still be difficult. Many methods have been created to convert persistence diagrams into a form amenable for machine learning \cite{Bubenik2015,Adams2017,Reininghaus2015,Perea2019}. However, so many methods have been developed, it can be difficult to choose one appropriate for the task. Additionally, the task of computing numerous persistence diagrams is computationally expensive. Our method aims to circumvent these issues using zigzag persistence, a generalization of persistent homology that is capable of summarizing information from a sequence of point clouds in a single persistence diagram. While less popular than standard persistent homology, zigzag persistence has been used in applications, including studying optical flow in computer generated videos \cite{Adams2019,Adams2020}, analyzing stacks of neuronal images \cite{Mata2015} and comparing different subsamples of the a dataset \cite{Tausz2011}. However, to the best of our knowledge, it has not been used in the context of dynamical systems or time series analysis. In this paper, we present Bifurcations using ZigZag (BuZZ), a one-step method to analyze bifurcations in dynamical systems using zigzag persistence. \section{Materials and Methods} Here we will present tools needed to build our method, including the time delay embedding, and an overview of the necessary topological tools. Specifically, we briefly introduce homology, persistent homology and zigzag persistent homology. However, we will not go into detail and instead direct the interested reader to \cite{Hatcher,Edelsbrunner2010,Carlsson2010} for more detail on homology, persistent homology, and zigzag homology, respectively. \subsection{Homology and persistent homology} \label{ssec:homology} Homology is a tool from the field of algebraic topology that encodes information about shape in various dimensions. Zero-dimensional homology studies connected components, 1-dimensional homology studies loops, and 2-dimensional homology studies voids. Persistent homology is a method from TDA which studies the homology of a parameterized space. For the purposes of this paper, we will focus on persistent homology applied to point cloud data. Here, we need only assume a point cloud is a collection of points with a notion of distance, however in practice, this distance often arises from a point cloud in Euclidean space inheriting the ambient metric. Given a collection of points, we will build connections between points based on their distance. Specifically, we will build simplicial complexes, which are spaces built from different dimensional simplices. A 0-simplex is a vertex, a 1-simplex is an edge, a 2-simplex is a triangle, and in general, a $p$-simplex is the convex hull of $p+1$ affinely independent vertices. Abstractly, a $p$-simplex can be represented by the set of $p+1$ vertices it is built from. So a simplicial complex, $\mathcal{K}$, is a family of sets that is closed under taking subsets. That is, given a $p$-simplex, $\sigma$, in $\mathcal{K}$, then any simplex consisting of a subset of the vertices of size $0<k\leq p$, called a $k$-dimensional face of $\sigma$, is also in $\mathcal{K}$. To create a simplicial complex from a point cloud, we use the Vietoris-Rips complex (sometimes just called the Rips complex). Given a point cloud, $X$, and a distance value, $r$, the Vietoris-Rips complex, $\mathcal{K}_r$, consists of all simplices whose vertices have maximum pairwise distance at most $r$. Taking a range of distance values, $r_0\leq r_1\leq r_2\leq \cdots r_n$ gives a set of simplicial complexes, $\{\mathcal{K}_{r_i}\}$. Since the distance values are strictly increasing, we have a nested sequence of simplicial complexes \begin{equation}\label{eqn:filtration} \mathcal{K}_{r_0} \subseteq \mathcal{K}_{r_1} \subseteq \cdots \subseteq \mathcal{K}_{r_n} \end{equation} called a filtration. Computing $p$-dimensional homology, $H_p(\mathcal{K})$, for each complex in the filtration gives a sequence of vector spaces and linear maps, \begin{equation} H_p(\mathcal{K}_{r_0}) \to H_p(\mathcal{K}_{r_1}) \to \cdots \to H_p(\mathcal{K}_{r_n}). \end{equation} Persistent homology tracks homological features such as connected components and loops as you move through the filtration. Specifically, it records at what distance value a feature first appears, and when a feature disappears or connects with another feature. These distance values are called the ``birth'' and ``death'' times respectively. These birth and death times are represented as a persistence diagram, which is a multiset of the birth death pairs $\{(b,d)\}$. \subsection{Time delay embedding} \label{ssec:timedelay} One way to reconstruct the underlying dynamics given only a time series is through a time delay embedding. Given a time series, $[x_1,\ldots,x_n]$, a choice of dimension $d$ and lag $\tau$, the delay embedding is the point cloud $\mathbf{X} = \{\mathbf{x}_i:= (x_i,x_{i+\tau}, \ldots, x_{i+(d-1)\tau}) \} \subset \mathbb{R}^d$. Takens' theorem \cite{Takens1981} shows that given most choices of parameters, the embedding retains the same topological structure as the state space of the dynamical system and that this is in fact a true embedding in the mathematical sense. In practice, not all parameter choices are optimal, so heuristics for making reasonable parameter choices have been developed \cite{Fraser1986,Kennel,Pecora2007,Chelidze2017,Pan2020,Kim1999}. In existing methods combing TDA with time series analysis, most works analyze a collection of time series by embedding each one into a point cloud using the time delay embedding. However, this can be computationally expensive and requires an analysis of the collection of computed persistence diagrams. Instead, we will employ a generalized version of persistent homology to avoid these additional steps. \subsection{Zigzag persistent homology} \label{ssec:zigzag} Zigzag persistence is a generalization of persistent homology that can study a collection of point clouds simultaneously. In persistent homology, you have a nested collection of simplicial complexes as in Eqn.~\ref{eqn:filtration}. However, for zigzag persistence, you can have a collection of simplicial complexes where the inclusions go in different directions. Specifically, the input to zigzag persistence is a sequence of simplicial complexes with maps, \begin{equation} \mathcal{K}_0 \leftrightarrow \mathcal{K}_1 \leftrightarrow \cdots \leftrightarrow \mathcal{K}_n \end{equation} where $\leftrightarrow$ is either an inclusion to the left or to the right. While in general these inclusions can go in any direction in any order, for this paper we will focus on a specific setup for the zigzag based on a collection of point clouds. Given an ordered collection of point clouds, $X_0,X_1,\ldots, X_n$, we can define a set of inclusions, \begin{equation} \label{eqn:zz_pc} \begin{tikzcd}[column sep=tiny] X_0 \arrow[hookrightarrow,dr] & & X_1 \arrow[hookrightarrow,dl]\arrow[hookrightarrow,dr] & & \arrow[hookrightarrow,dl] X_2 & \cdots & X_{n-1} \arrow[hookrightarrow,dr] & & \arrow[hookrightarrow,dl] X_n \\ & X_0 \cup X_1 & & X_1 \cup X_2 & & & & X_{n-1}\cup X_n. & \end{tikzcd} % \end{equation} However, these are all still point clouds, which have uninteresting homology. Thus, we can compute the Vietoris-Rips complex of each point cloud for a fixed radius, $r$. This results in the diagram of inclusions of simplicial complexes \begin{equation} \label{eqn:zz_rips_fixed} \begin{tikzcd}[column sep=-1.5em] R(X_0,r) \arrow[hookrightarrow,dr] & & R(X_1,r) \arrow[hookrightarrow,dl]\arrow[hookrightarrow,dr] & & R(X_2,r) \arrow[hookrightarrow,dl] & ~~~~~\cdots~~~~~ & R(X_{n-1},r) \arrow[hookrightarrow,dr] & & R(X_n,r) \arrow[hookrightarrow,dl] \\ & R(X_0 \cup X_1,r) & & R(X_1 \cup X_2,r) & & & & R(X_{n-1}\cup X_n,r). & \end{tikzcd} % \end{equation} Computing the 1-dimensional homology of each complex in Eqn.~\ref{eqn:zz_rips_fixed} will result in a zigzag diagram of vector spaces and induced linear maps, \begin{equation} \label{eqn:zz_rips_hom} % \begin{tikzcd}[column sep=-1.5em] H_1( R(X_0,r) ) \arrow[dr] & & H_1( R(X_1,r) ) \arrow[dl] & ~~~~~\cdots~~~~~ & H_1( R(X_{n-1},r) ) \arrow[dr] & & H_1( R(X_n,r) ) \arrow[dl] \\ & H_1( R(X_0 \cup X_1,r) ) & & & & H_1( R(X_{n-1}\cup X_n,r) ). & \end{tikzcd} % \end{equation} Zigzag persistence tracks features that are homologically equivalent through this zigzag. This means it records the range of the zigzag filtration where the same feature appears. The zigzag persistence diagram records ``birth'' and ``death'' relating to location in the zigzag. If a feature appears in $R(X_i,r),$ it is assigned birth time $i$, and if it appears at $R(X_i\cup X_{i+1},r),$ it is assigned birth time $i+0.5$. Similarly, if a feature last appears in $R(X_j,r)$, it is assigned a death time $j+0.5$, while if it last appears in $R(X_j \cup X_{j+1},r)$, it is assigned a death time of $j+1$. A small example is shown in Fig.~\ref{fig:zz_example}. In this example, there is a 1-dimensional feature that appears in $R(X_0,r)$ and disappears going into $R(X_0 \cup X_1,r)$, thus it appears in the zigzag persistence diagram as the point $(0,0.5)$. Additionally, there is one connected component that exists through the zigzag, corresponding to the 0-dimensional persistence point $(0,2)$. By default, we assume all features die at the end of the zigzag, rather than having infinite points as in standard persistence. There is one additional connected component that first appears in $R(X_0\cup X_1,r)$, corresponding to the 0-dimensional persistence point $(0.5,2).$ \begin{figure} \centering \includegraphics[width=0.75\textwidth]{Figures/ZZ_Example.png} \caption{Small example of zigzag filtration with corresponding zigzag persistence diagram.} \label{fig:zz_example} \end{figure} Note that we can easily generalize this idea to use a different radius for each Rips complex, $R(X_i,r_i)$. For the unions we choose the maximum radius between the two individual point clouds, $R(X_i\cup X_{i+1}, \max\{r_i,r_{i+1}\})$, to ensure the inclusions hold. \subsection{Bifurcations using ZigZag (BuZZ)} \label{ssec:ourmethod} \begin{figure} \centering \includegraphics[width=\textwidth]{Figures/Pipeline_Horizontal.png} \caption{ Outline of BuZZ method. The input time series is converted to an embedded point cloud via the time delay embedding. The Rips complexes are constructed for either a fixed $r$ or a choice of $r_i$ for each point cloud. Then, the zigzag persistence diagram is computed for the collection. } \label{fig:pipeline} \end{figure} We can now present our method, Bifurcations using ZigZag (BuZZ) for combining the above tools to detect changes in circular features in dynamical systems. We will focus on Hopf bifurcations \cite{Guckenheimer1983}, which are seen when a fixed point loses stability and a limit cycle is introduced. These types of bifurcations are particularly topological in nature, as the state space changes from a small cluster, to a circular structure, and sometimes reduces back to a cluster. The necessary data for our method is a collection of time series for a varying input parameter value, as shown in Fig.~\ref{fig:pipeline}(a). This particular example is a collection of time series given by $\{a\sin(t)\}$ for $a=0.5,1.0,1.5,2.0$ (going from top to bottom). Each time series is then embedded using the time delay embedding (shown in Fig.~\ref{fig:pipeline}(b) using $d=2$ and $\tau=3$). While in general, the delay could be varied for each time series, the embedding dimension needs to be fixed so each time series is embedded in the same space. For the sake of interpretability and visualization, we will use a dimension of $d=2$ throughout this paper. Sorting the resulting point clouds based on the input parameter value, the zigzag filtration can be formed from the collection of point clouds, as shown in Fig.~\ref{fig:pipeline}(c). Lastly, computing zigzag persistence gives a persistence diagram, as shown in Fig.~\ref{fig:pipeline}(d), encoding information about the structural changes moving through the zigzag. With the right choices of parameters, the 1-dimensional persistence point with the longest lifetime in the zigzag persistence diagram will have birth and death time corresponding to the indices in the zigzag where the Hopf bifurcation appears and disappears. Lastly, mapping the birth and death times back to the parameter values used to create the corresponding point clouds will give the range of parameter values where the Hopf bifurcation occurs. Note that there are several parameter choices that need to be selected during the course of the BuZZ method. First, the dimension $d$ and delay $\tau$ for converting each time series into a point cloud. Fortunately, there is a vast literature from the time series analysis literature for this, which leads to standard heuristics. The second and more difficult parameter is the choice of radius (or radii) for the Rips complexes. In this paper, the given examples are simple enough that the choice of radii in the BuZZ method can be tuned by the user. However, in future work, we would like to create new methods and heuristics for choosing these radii. \subsection{Algorithms} \label{ssec:algorithm} While zigzag persistence has been in the literature for a decade, it has not often been used in application, and thus the software that computes it is not well developed. A C++ package with python wrappers, Dionysus 2\footnote{ \url{https://www.mrzv.org/software/dionysus2/} }, has implemented zigzag persistence; however, it requires significant preprocessing to create the inputs. We have developed a python package \footnote{\url{https://github.com/sarahtymochko/BuZZ}} that, provided the collection of point clouds and radii, will perform all the necessary preprocessing to set up the zigzag diagram as shown in Eqn.~\ref{eqn:zz_rips_fixed} to pass as inputs to Dionysus. Dionysus requires two inputs, a list of simplices, \texttt{simplex\_list}, and a list of lists, \texttt{times\_list}, where the \texttt{times\_list[i]} consists of a list of indices in the zigzag where the simplex, \texttt{simplex\_list[i]}, is added and removed. A small example is shown in Fig.~\ref{fig:dio_input_fixed}. Looking at that example, the two vertices and one edge in $R(X_0)$ appear at time 0, and disappear at time 1. There are two edges and a triangle in $R(X_0\cup X_1)$ that appear there at time 0.5 (recalling that $R(X_i\cup X_{i+1})$ is time $i+0.5$) and disappear at time 1. Lastly, the one vertex in $R(X_1)$ appears at time 0.5, and never disappears in the zigzag sequence, so by default we set death time to be $2$, which is the next index beyond the end of the zigzag sequence. This is done to avoid infinite lifetime points, as our zigzag sequences are always finite and an infinite point has no additional meaning. Note there are other special cases that can occur. If a simplex is added and removed multiple times, then the corresponding entry in \texttt{times\_list} has more than two entries, where the zero and even entries in the list correspond to when it appears, and the odd entries correspond to when it disappears. An example with this special case is shown in Fig.~\ref{fig:dio_input_changing} and will be described in more detail later. If we are using a fixed radius across the whole zigzag, these inputs can be computed rather easily. In this setting, we only need to compute the Rips complex of the unions, $R(X_i\cup X_{i+1},r)$, which can be done using the Dionysus package, and the list of simplices can be created by combining lists of simplices for all $i$, removing duplicates. Next, we will outline how to construct the times list. Starting with the set of simplices in $R(X_i\cup X_{i+1},r)$, we can split them into three groups: (a) simplices for which all 0-dimensional faces are in $X_i$, (b) simplices for which all 0-dimensional faces are in $X_{i+1}$, or (c) simplices for which some 0-dimensional faces are in $X_i$ and some are in $X_{i+1}$. Because of the construction of the zigzag, all simplices in group (a) appear at time $i-0.5$, since $R(X_i,r)$ also includes backwards into $R(X_{i-1}\cup X_i,r)$, and disappear at time $i+1$, since the union $R(X_i \cup X_{i+1},r)$ is the last time simplices in $X_{i}$ are included. Similarly, all simplices in group (b) appear at time $i+0.5$, since this is the first time simplices $X_{i+1}$ are included, and disappear at time $i+2$, since $R(X_{i+1},r)$ also includes forward into $R(X_{i+1}\cup X_{i+2},r)$. Lastly, all simplices in group (c) exist only at $R(X_i\cup X_{i+1},r)$, so they appear at time $i+0.5$ and disappear at $i+1$. Note that the first case needs to be treated separately, since in $R(X_0\cup X_1,r)$, all vertices in group (a) will appear at $0$. \begin{figure} \centering \includegraphics[width=0.6\textwidth]{Figures/Dio_Input_Example.pdf} \caption{Example zigzag using fixed radius with computed inputs for Dionysus.} \label{fig:dio_input_fixed} \end{figure} \begin{figure} \centering \includegraphics[width=0.99\textwidth]{Figures/Dio_Input_Example_Changing.pdf} \caption{Example zigzag using a changing radius with computed inputs for Dionysus. In this example $r_0>r_1$ and $r_2>r_1$.} \label{fig:dio_input_changing} \end{figure} Using a varied radius, as described in Sec.~\ref{ssec:zigzag}, complicates the above procedure. Using the same radius, we are guaranteed all simplices in group (a) are in both $R(X_i,r)$ and $R(X_i\cup X_{i+1},r)$, and similarly for group (b), thus we only need to compute $R(X_i\cup X_{i+1}, r)$. However, with a changing radius this is no longer true. In the example shown in Fig.~\ref{fig:dio_input_changing}, the edge $e_{1,2}$ appears in both $R(X_0\cup X_1, r_0)$ and $R(X_1\cup X_2, r_2)$ since $r_2>r_1$ and $r_0>r_1$, but it is not in $R(X_1,r_1)$. Thus, its corresponding list in \texttt{times\_list} is $[0.5,1,1.5,2]$. Thus the inputs to Dionysus can be computed using the same method as above, except the rips complex needs to be computed for each point cloud, not just the unions, and additional checks need to be done to make sure a simplex being added did not already appear and disappear once before. If it did, the entry in \texttt{times\_list} needs to be extended to account for the newest appearance and disappearance. Because of the additional Rips complex computations, and the checks for the special case, the case of a changing radius is significantly more computationally expensive than the case of a fixed radius. In both cases, there is the computational cost of the zigzag persistence computation as well. The computational complexity of zigzag persistence is $O(nm^2)$ where $n$ is the number of simplices in the entire filtration and $m$ is the number of simplices in the largest single complex \cite{Carlsson2009}. Thus, the largest barrier to computation is the zigzag itself, so choosing a radius that is as small as possible without breaking the topology is the goal. \section{Results} We will test the BuZZ method on three different examples. The first example is not based on time series data, but is instead a simple proof-of-concept example to test our methods ability to detect changing circular behavior. The second example is based on synthetic time series data generated from noisy sine waves of varying amplitude. This lets us fully utilize the BuZZ method, including the time delay embedding, as well as test resiliency to noise. The last example is detecting a Hopf bifurcation in the Sel'kov model of glycolysis \cite{Selkov1968}. \subsection{Synthetic Point Cloud Example} \begin{figure}[] \centering \includegraphics[width=\textwidth]{Figures/Circle_Example_2.png} \includegraphics[width=\textwidth]{Figures/Circle_Example.png} \includegraphics[width=0.25\textwidth]{Figures/Circle_Example_PD.png} \caption{ Top: Example zigzag of point clouds with unions considered in Sec.~\ref{ssec:SyntheticExample}. Middle: Zigzag filtration applied to point clouds using the Rips complex with specified radii. Note that 2-simplices are not shown in the complexes. Bottom: The resulting zigzag persistence diagram.} \label{fig:circles} \end{figure} To start, we will consider a small, synthetic example generating point cloud circles of varying size as shown in Fig.~\ref{fig:circles}. Note, because we are starting with point clouds, we skip the time delay embedding step for this example. While each point cloud is sampled from a circle, the first and last point clouds consist of relatively small circles. So the strongest circular structure we can see visually starts with $X_1$ and ends with $X_3$. This is the range we would like to detect using zigzag persistence. For this example, we will use the generalized version of the zigzag filtration in (\ref{eqn:zz_rips_fixed}) using a changing radii. Computing the zigzag persistence gives the persistence diagram shown in Fig.~\ref{fig:circles}. Recall that birth and death times are assigned based on the location in the zigzag that a feature appears and disappears. Thus, the one-dimensional point $(1,3.5)$ in the persistence diagram corresponds to a feature that first appears at $R(X_1)$ and last appears in $R(X_3)$ Thus, using the persistence diagram we can detect the appearance and disappearance of the circular feature. This is clearly an overly simplified situation as each point cloud is sampled from a perfect circle. Next, we will look at a more realistic example. \subsection{Synthetic Time Series Example} \label{ssec:SyntheticExample} \begin{figure} \centering \includegraphics[width=\textwidth]{Figures/Sine-TS-0p1.png} \includegraphics[width=\textwidth]{Figures/Sine-TDE-0p1.png} \includegraphics[width=0.69\textwidth]{Figures/Sine-Rips-0p1.png} \includegraphics[width=0.3\textwidth]{Figures/Sine-PD-0p1.png} \caption{First and second rows: Generated time series data and corresponding time delay embeddings. Bottom left: The zigzag filtration using Rips complex with fixed radius of 0.72. Note that 2-simplices are not shown in the complexes. Bottom right:the corresponding zigzag persistence diagram. } \label{fig:sine_ts} \end{figure} For the second example, we generate synthetic time series data and apply the full method described in Sec.~\ref{ssec:ourmethod}. We start by generating sine waves of varying amplitudes and add noise drawn from uniformly from $[-0.1,0.1]$. The time series are then each embedded using the time delay embedding with dimension $d=2$ and delay $\tau=4$. The time series and corresponding time delay embeddings are shown in Fig.~\ref{fig:sine_ts}. Looking at the time series, in the first and last time series any signal is mostly obscured by noise, resulting in a small clustered time delay embedding. However, for the other time series, the time delay embedding is still circular, picking up the periodic behavior even with the noise. Next we compute zigzag persistence, resulting in the zigzag of rips complexes and zigzag persistence diagram shown in Fig.~\ref{fig:sine_ts}. The zigzag persistence diagram has a one-dimensional point with coordinates $(1,7.5)$, indicating the circular feature appears in $R(X_1)$, and disappears going into $R(X_8)$. This is the region we would expect to see a circular feature. \subsection{Sel'kov Model} \begin{figure}[] \centering \includegraphics[width=0.8\textwidth]{Figures/Selkov_Model_FULL.png} \includegraphics[width=0.69\textwidth]{Figures/Selkov_Rips_TDE.png} \includegraphics[width=0.3\textwidth]{Figures/Selkov_PD.png} \caption{ Top: Examples of samplings of the state space of the Sel'kov model for varying parameter value $b$. Bottom left: zigzag filtration using Rips complex with fixed radius of 0.25. Note that 2-simplices are not shown in the complexes. Bottom right: resulting zigzag persistence diagram.} \label{fig:selkov} \end{figure} Our last experiment is trying to detect a bifurcation in the Sel'kov model \cite{Selkov1968}, a model for glycolysis which is a process of breaking down sugar for energy. This model is defined by the system of differential equations, \begin{align*} \dot{x} & = -x+ay + x^2y \\ \dot{y} & = b - ay - x^2y \end{align*} where the overdot denotes a derivative with respect to time. In this system, $x$ and $y$ represent the concentration of ADP (adenosine diphosphate) and F6P (fructose-6-phosphate), respectively. This system has a Hopf bifurcation for select choices of parameters $a$ and $b$. This limit cycle behavior corresponds to the oscillatory rise and fall of the chemical compounds through the glycolysis process. For our experiments, we will fix $a=0.1$ and vary the parameter $b$. We generate 500 time points of the data ranging between 0 and 500 using \texttt{odeint} in python, with initial conditions $(0,0)$. We also remove the first 50 points to remove transients at the beginning of the model (this is sometimes referred to as a ``burn-in period''). This data is constructed using full knowledge of the model, however, in practice, you typically only have one measurement function and then the time-delay embedding is used to reconstruct the underlying system. To mimic this setup, we will only use the time series corresponding to the $x$-coordinates from the model and use the delay embedding. These time series are then embedded using the time delay embedding with dimension $d=2$ and delay $\tau=3$. The next step would be to compute zigzag persistence as described in Sec.~\ref{ssec:zigzag}, however due to the large number of points in the time delay embeddings, this becomes computationally expensive. In order to reduce the computation time, we subsample these point clouds using the furthest point sampling method (also called a greedy permutation) \cite{Cavanna2015}. We subsample down to only 20 points in each point cloud, compute the Rips complex zigzag for a fixed radius value of $0.25$, and then compute the zigzag persistence. Figure~\ref{fig:selkov} shows the zigzag filtration of Rips complexes along with the resulting zigzag persistence diagram. In the zigzag persistence diagram, the point with the longest lifetime has coordinates $(2,8.5)$. Again, since these coordinates correspond to the index in the zigzag sequence, this point corresponds to a feature appearing at $R(X_2)$ and disappearing at $R(X_8 \cup X_9)$. Looking back at which values of $b$ were used to generate these point clouds, we see this corresponds to a feature appearing at $b=0.45$ and disappearing at $b=0.8$. For the fixed parameter value of $a=0.1$, the Sel'kov model has a limit cycle approximately between the parameter values $0.4 \leq b \leq 0.8$ \cite{Strogatz2014}. Our method is picking up approximately that same range. These results use the $x$-coordinates of the model, however the same results can be obtained using the $y$-coordinates and a slightly larger radius value. \section{Discussion} Here we have introduced a method of detecting Hopf bifurcations in dynamical systems using zigzag persistent homology called BuZZ. This method was shown to work on two synthetic examples as well as a more realistic example using the Sel'kov model. Our method is able to detect the range of the zigzag filtration where circular features appear and disappear. Thus, this method could be applied to any application with an ordered set of point clouds and a changing topological structure. While this method has shown success, it also has its limitations. The method is computationally expensive due to numerous Rips complex computations in addition to the zigzag persistence computation itself. This issue can be alleviated using subsampling, as shown with the Sel'kov model, but this may not be feasible depending on the application. Future extensions of this project could include improvements of the algorithms described in Sec.~\ref{ssec:algorithm}. Additionally, while the method works well in practice, it lacks theoretical guarantees. Given the method requires parameter choices for the radii of the Vietoris-Rips complexes, we would like some heuristics to be used in practice to choose these radii more easily. Because our examples in this paper are small, selecting parameters by hand is reasonable. However, in the future when applied to larger, experimental data, these sorts of heuristics will be necessary.
{'timestamp': '2020-09-21T02:18:32', 'yymm': '2009', 'arxiv_id': '2009.08972', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08972'}
arxiv
\subsection{Immersive Sketching and Modeling} \label{sec:relatedDrawing} Immersive creation has a long history in computer graphics. Immersive 3D sketching was pioneered by the HoloSketch system \cite{deering1995holosketch}, which used a 6-DoF wand as the input device for creating polyline sketches, 3D tubes, and primitives. In a similar vein, various subsequent systems have explored the creation of freeform 3D curves and swept surfaces \cite{schkolne2001surface, keefe2001cavepainting, google2020tilt}. While directly turning 3D input to creative output is acceptable for ideation, the inherent imprecision of 3D sketching is quickly apparent when more structured creation is desired. The perceptual and ergonomic challenges in precise control of 3D input is well-known~\cite{keefe2007drawing, wiese2010investigating, arora2017experimental, machuca2019effect, machuca2018multi}, resulting in various methods for correcting 3D input. Input 3D curves have been algorithmically regularized to snap onto existing geometry, as with the FreeDrawer~\shortcite{wesche2001freedrawer} system, or constrained physically to 2D input with additional techniques for ``lifting'' these curves into 3D \cite{jackson2016lift, arora2018symbiosis, kwan2019mobi, paczkowski2011insitu}. Haptic rendering devices \cite{keefe2007drawing, kamuro20113d} and tools utilizing passive physical feedback \cite{grossman2002creating} are an alternate approach to tackling the imprecision of 3D inputs. We are motivated by similar considerations. Arora et al.~\shortcite{arora2017experimental} demonstrated the difficulty of creating curves that lie exactly on virtual surfaces in VR, even when the virtual surface is a plane. This observation directly motivates our exploration of techniques for projecting 3D strokes onto surfaces, instead of coercing users to awkwardly draw exactly on a virtual surface. \subsection{Drawing Curves on, near, and around Surfaces} \label{sec:relatedProjecting} Curve creation and editing on or near the surface of 3D virtual objects is fundamental for a variety of artistic and functional shape modeling tasks. Functionally, curves on 3D surfaces are used to model or annotate structural features \cite{iwires, neobarok}, define trims and holes \cite{schmidt2010meshmixer}, and to provide handles for shape deformation \cite{wires, kara2007sketch,nealen2007fibermesh}, registration \cite{gehre2018interactive} and remeshing \cite{krishlevoy,takayama2013sketch}. Artistically, curves on surfaces are used in painterly rendering \cite{goochbook}, decal creation \cite{schmidt2006discrete}, texture painting \cite{adobe2020substance}, and even texture synthesis \cite{fisher2007design}. Curve on surface creation in this body of research typically uses the established view-centric WYSIWYG projection of on-screen sketched 2D strokes. While the sketch view-point in these interfaces is interactively set by the user, there has been some effort in automatic camera control for drawing \cite{ortega2014direct}, auto-rotation of the sketching view for 3D planar curves \cite{flatfab}, and user assistance in selecting the most \emph{sketchable} viewpoints \cite{bae08ilovesketch}. Immersive 3D drawing enables direct, view-point independent 3D curve sketching, and is thus an appealing alternative to these 2D interfaces. Our work is also related to drawing curves \emph{around} surfaces. Such techniques are important for a variety of applications: modeling string and wire that wrap around objects \cite{coleman2006cords}; curves that loosely conform to virtual objects or define collision-free paths around objects \cite{krs2017Skippy}; curve patterns for clothing design on a 3D mannequin model \cite{turquin2007sketch}; curves for layered modeling of shells and armour \cite{depauli2015secondskin}; and curves for the design and grooming of hair and fur \cite{fu2007sketching,schmidt2011overcoat, xing2019hairbrush}. Some approaches such as SecondSkin~\shortcite{ depauli2015secondskin} and Skippy~\shortcite{krs2017Skippy} use insights into spatial relationship between a 2D stroke and the 3D object, to infer a 3D curve that lies on and around the surface of the object. Other techniques like Cords~\shortcite{coleman2006cords} or hair and clothing design \cite{xing2019hairbrush} are closer to our work, in that they drape 3D curve input on and around 3D objects using geometric collisions or physical simulation. In contrast, this paper is application agnostic, and remains focused on the general problem of projecting a drawn 3D stroke to a real-time inked curve on the surface of a virtual 3D object. While we do not address curve creation with specific geometric relationships to the object surface (like distance-offset curve), our techniques can be extended to incorporate geometry-specific terms (\S~\ref{sec:conclusion}). \subsection{Sketch-based 3D Modeling} \label{sec:relatedModeling} Sketch-based 3D modeling is a rich ongoing area of research (see survey by Olsen et al.~\shortcite{olsen2009sketch}). Typically, these systems interpret 2D sketch inputs for various shape modeling tasks. One could categorize these modeling approaches as single-view (akin to traditional pen on paper) \cite{schmidt2009analytic,andre11single,chen20133sweep,xu2014true2form} or multi-view (akin to 3D modeling with frequent view manipulation) \cite{igarashi1999teddy,fan2004sketch,nealen2007fibermesh,bae08ilovesketch,fan2013modeling}. Single-view techniques use perceptual insights and geometric properties of the 2D sketch to infer its depth in 3D, while multi-view techniques explicitly use view manipulation to specify 3D curve attributes from different views. While our work utilizes mid-air 3D stroke input, the ambiguity of projection onto surfaces connects it to the interpretative algorithms designed for sketch-based 3D modeling. We aim to take advantage of the immersive interaction space by allowing view manipulation as and when desired, independent of geometry creation. \subsection{Context-Free Projection Techniques} \label{sec:historyFree} Context-free techniques project points independent of each other, simply based on the spatial relationships between the controller, HMD, and 3D object ( Figure~\ref{fig:historyFree}). We can further categorize techniques as raycast or proximity based. \subsubsection{Raycast Projections} \label{sec:raycasting} View-centric projection in 2D interfaces project points from the screen along a ray from the eye through the screen point, to where the ray first intersects the 3D object. In an immersive setting, raycast approaches similarly use a ray emanating from the 3D stroke point to intersect 3D objects. This ray $(\mathbf{o}, \mathbf{d})$ with origin $\mathbf{o}$ and direction $\mathbf{d}$ can be defined in a number of ways. Similar to pointing behavior, {\it Occlude} defines this ray from the eye through the controller origin (also the stroke point, Figure~\ref{fig:historyFree}a) $\left(\mathbf{c}_i, (\mathbf{c}_i - \mathbf{h}_i) / \|\mathbf{c}_i - \mathbf{h}_i\|\right)$. If the ray intersects $\mathcal{M}$, then the closest intersection to $\mathbf{p}_i$ defines $\mathbf{q}_i$. In case of no intersection, $\mathbf{p}_i$ is ignored in defining the projected curve, i.e., $\mathbf{q}_i$ is marked undefined and the projected curve connects $\mathbf{q}_{i-1}$ to $\mathbf{q}_{i+1}$ (or the proximal index points on either side of $i$ for which projections are defined). The {\it Spraycan} approach treats the controller like a spraycan, defining the ray like a nozzle direction in the local space of the controller (Figure~\ref{fig:historyFree}b). For example the ray could be defined as $(\mathbf{c}_i, \mathbf{f}_i)$, where the nozzle $\mathbf{f}_i = \mathsf{c}_i\cdot [0, 0, 1]^T$ is the controller's local z-axis (or \emph{forward} direction). Alternately, {\it Head-centric} projection can define the ray using the HMD's view direction as $(\mathbf{h}_i, \mathsf{h}_i\cdot [0, 0, 1]^T)$ (Figure~\ref{fig:historyFree}c). {\bf Pros and Cons:} The strengths of raycasting are: a predictable visual/proprioceptive sense of ray direction; a spatially continuous mapping between user input and projection rays; and AR/VR scenarios where it is difficult or undesirable to reach and draw close to the virtual object. The biggest limitation of raycast projection stems from the controller/HMD-based ray direction being completely agnostic of the shape or location of the 3D object. Projected curves can consequently be very different in shape and size from drawn strokes, and ill-defined for stroke points with no ray-object intersection. \subsubsection{Proximity-Based Projections} \label{sec:proximity} In 2D interfaces, the on-screen 2D strokes are typically distant to the viewed 3D scene, necessitating some form of raycast projection onto the visible surface of 3D objects. In AR/VR, however, users are able to reach out in 3D and directly draw the desired curve on the 3D object. While precise mid-air drawing on a virtual surface is very difficult in practice (Figure~\ref{fig:imprecise3D}), projection methods based on proximity between the mid-air stroke and the 3D object are certainly worth investigation. The simplest proximity-based projection technique {\it Snap}, projects a stroke point $\mathbf{p}_i$ to its closest-point in $\mathcal{M}$ (Figure~\ref{fig:historyFree}d). \begin{equation} \mathbf{q}_i = \pi_{snap}(\mathbf{p}_i) = \argmin_{\mathbf{x}\in\mathcal{M}}\ d(\mathbf{p}_i, \mathbf{x}), \end{equation} \begin{wrapfigure}[10]{r}{0.3\columnwidth} \begin{center} \vspace{-0.7cm} \hspace{-0.7cm} \includegraphics[width=0.3\columnwidth]{cp_scp} \end{center} \end{wrapfigure} where $d(\cdot, \cdot)$ is the Euclidean distance between two points. Unfortunately, for triangle meshes, closest-point projection tends to snap to the edges of the mesh (\textcolor{matlabblue}{\textbf{blue}} curve inset), resulting in unexpectedly jaggy projected curves, even for smooth 3D input strokes (\textbf{black} curve inset)~\cite{panozzo2013weighted}. These discontinuities are due to the discrete nature of the mesh representation, as well spatial singularities in closest point computation even for smooth 3D objects. We mitigate this problem by formulating an extension of Panozzo et al.'s \emph{Phong} projection~\shortcite{panozzo2013weighted} in \S~\ref{sec:phong}, that simulates projection of points onto an imaginary smooth surface approximated by the triangle mesh. We denote this {\it smooth-closest-point} projection as $\pi_{SCP}$ (\textcolor{matlabred}{\textbf{red}} curve inset). {\bf Pros and Cons:} The biggest strength of proximity-based projection is it exploits the immersive concept of drawing directly on or near an object, using the spatial relationship between a 3D stroke point and the 3D object to determine projection. The main limitation is that since users rarely draw precisely on the surface, discontinuities and local extrema persist when projecting distantly drawn stoke points, even when using {\it smooth-closest-point}. In \S~\ref{sec:anchoredProximity}, we address this problem using stroke {\it mimicry} to anchor distant stroke points close to the object to be finally projected using {\it smooth-closest-point}. \subsection{Smooth-Closest-Point Projection} \label{sec:phong} \tikzcdset{column sep/huge=3.5cm} \begin{figure} \centering \begin{subfigure}{\linewidth} \begin{tikzcd} \{\mathbf{x}^d\}\subset\mathcal{M}^d \arrow[r, "\text{Def.}"] & \mathbf{y}^d=\sum w_i\mathbf{x}_i^d \arrow[r, "\mathcal{P}_{Phong}"] & \mathbf{z}^d\in\mathcal{M}^d \arrow[d, "\bary(\mathcal{M})"] \\ \{\mathbf{x}^d\}\subset\mathcal{M}^3 \arrow[u, "{\bary(\mathcal{M}),\ \mathbf{e}^d(\mathcal{M})}"] \arrow[r, "\text{Def.}"] & \mathbf{y}^3=\sum w_i\mathbf{x}_i^3 & \mathbf{z}^3\in\mathcal{M}^3 \end{tikzcd} \caption{Computing weighted averages in Panozzo et al.~\shortcite{panozzo2013weighted}} \end{subfigure} \begin{subfigure}{\linewidth} \begin{tikzcd}[column sep = huge] \mathbf{y}^d\in\mathcal{T}_\mathcal{M}^d \arrow[r, "\mathcal{P}_{Phong}"] & \mathbf{z}^d\in\mathcal{M}^d \arrow[d, "\bary(\mathcal{M})"] \\ \mathbf{y}^3\in\mathcal{T}_\mathcal{M}^3 \arrow[u, "{\bary(\mathcal{T}_\mathcal{M}),\ \mathbf{e}^d(\mathcal{T}_\mathcal{M})}"] & \mathbf{z}^3\in\mathcal{M}^3 \end{tikzcd} \caption{Computing smooth-closest-point projection.} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=.9\linewidth]{higher_dim_embedding} \caption{Computing a $d$-dimensional embedding for $\mathcal{M}$ (a) and $\mathcal{T}_\mathcal{M}$ (b).} \end{subfigure} \caption{Panozzo et al.~\shortcite{panozzo2013weighted} compute weighted averages on surfaces (a), while we want to compute a smooth closest-point projection for an arbitrary point \emph{near} the mesh in $\mathbb{R}^3$ (b). We therefore embed $\mathcal{T}_\mathcal{M}$---the region \emph{around} the mesh---in higher-dimensional space $\mathbb{R}^d$, instead of just $\mathcal{M}$ (c).} \label{fig:phongAdapt} \end{figure} Our goal with \emph{smooth-closest-point} projection is to define a mapping from a 3D point to a point on $\mathcal{M}$ that approximates the closest point projection but tends to be functionally smooth, at least for points near the 3D object. We note that computing the closest point to a Laplacian-smoothed mesh proxy, for example, will also provide a smoother mapping than $\pi_{snap}$, but a potentially poor closest-point approximation to the original mesh. \emph{Phong projection}, introduced by Panozzo et al.~\shortcite{panozzo2013weighted}, addresses these goals for points expressible as weighted-averages of points on $\mathcal{M}$, but we extend their technique to define a smooth-closest-point projection for points in the neighbourhood of the mesh. For completeness, we first present a brief overview of their technique. Phong projection is a two-step approach to map a point $\mathbf{y}^3 \in \mathbb{R}^3$ to a manifold triangle mesh $\mathcal{M}$ embedded in $\mathbb{R}^3$, emulating closest-point projection on a smooth surface approximated by the triangle mesh. First, $\mathcal{M}$ is embedded in a higher dimensional Euclidean space $\mathbb{R}^d$ such that Euclidean distance (between points on the mesh) in $\mathbb{R}^d$ better approximates geodesic distances in $\mathbb{R}^3$. Second, analogous to vertex normal interpolation in Phong shading, a smooth surface is approximated by blending tangent planes across edges. Barycentric coordinates at a point within a triangle are used to blend the tangent planes corresponding to the three edges incident to the triangle. We extend the first step to a higher dimensional embedding of not just the triangle mesh $\mathcal{M}$, but a tetrahedral representation of an offset volume around the mesh $\mathcal{M}$ (Figure~\ref{fig:phongAdapt}). The second step remains the same, and we refer the reader to Panozzo et al.~\shortcite{panozzo2013weighted} for details. For clarity, we refer to $\mathcal{M}$ embedded in $\mathbb{R}^3$ as $\mathcal{M}^3$, and the embedding in $\mathbb{R}^d$ as $\mathcal{M}^d$. Panozzo et al. compute $\mathcal{M}^d$ by first embedding a subset of the vertices in $\mathbb{R}^D$ using metric multi-dimensional scaling (MDS)~\cite{cox2008multidimensional}, aiming to preserve the geodesic distance between the vertices. This subset consists of the high-curvature vertices of $\mathcal{M}$. The embedding of the remaining vertices is then computed using LS-meshes~\cite{sorkine2004LSmeshes}. For the problem of computing weighted averages on surfaces, one only needs to project 3D points of the form $\mathbf{y}^3=\sum w_i\mathbf{x}_i^3$, where all $\mathbf{x}_i^3\in\mathcal{M}^3$. The point $\mathbf{y}^3$ is \emph{lifted} into $\mathbb{R}^d$ by simply defining $\mathbf{y}^d = \sum w_i\mathbf{x}_i^d$, where $\mathbf{x}_i^d$ is defined as the point on $\mathcal{M}^d$ with the same implicit coordinates (triangle and barycentric coordinates) as $\mathbf{x}_i^3$ does on $\mathcal{M}^3$. Therefore, their approach only embeds $\mathcal{M}$ into $\mathbb{R}^d$ (Figure~\ref{fig:phongAdapt}a,c). In contrast, we want to project arbitrary points \emph{near} $\mathcal{M}^3$ onto it using the Phong projection. Therefore, we compute the offset surfaces at signed-distance $\pm\mu$ from $\mathcal{M}$. We then compute a tetrahedral mesh $\mathcal{T}_\mathcal{M}^3$ of the space between these two surfaces in $\mathbb{R}^3$. In the final step, we embed the vertices of $\mathcal{T}_\mathcal{M}$ in $\mathbb{R}^d$ using MDS and LS-Meshes as described above. Note that all of the above steps are realized in a precomputation. Now, given a 3D point $\mathbf{y}^3$ within a distance $\mu$ from $\mathcal{M}^3$, we situate it within $\mathcal{T}_\mathcal{M}^3$, use tetrahedral Barycentric coordinates to infer its location in $\mathbb{R}^d$, and then compute its Phong projection (Figure~\ref{fig:phongAdapt}b,c). We fallback to closest-point projection for points outside $\mathcal{T}_\mathcal{M}^3$, since Phong projection converges to closest-point projection when far from $\mathcal{M}$. Furthermore, we set $\mu$ large enough to easily handle our smooth-closest-point queries in \S~\ref{sec:anchoredProximity}. \subsection{Analysis of Context-Free Projection} \label{sec:historyFreeProblems} We implemented the four different context-free projection approaches in Figure~\ref{fig:historyFree}, and had 4 users informally test each, drawing a variety of curves on the various 3D models seen in this paper. Qualitatively, we made a number of observations: \begin{itemize}[label=--, leftmargin=1em] \item {\it Head-centric} and {\it Occlude} projections become unpredictable if the user is inadvertently changing their viewpoint while drawing. These projections are also only effective when drawing frontally on an object, like with a 2D interface. Neither as a result exploits the potential gains of mid-air drawing in AR/VR. \item {\it Spraycan} projection was clearly the most effective context-free technique. Commonly used for graffiti and airbrushing, usually on fairly flat surfaces, we noted however, that consciously reorienting the controller while drawing on or around complex objects was both cognitively and physically tiring. \item {\it Snap} projection was quite sensitive to changes in the distance of the stroke from the object surface, and in general produced the most undulating projections due to closest-point singularities. \item All projections converge to the mid-air user stroke when it precisely conforms to the surface of the 3D object. But as the distance between the object and points on the mid-air stroke increases, their behavior diverges quickly. \item While users did draw in the vicinity and mostly above the object surface, they rarely drew precisely on the object. The average distance of stroke points from the target object was observed to be 4.8 cm in a subsequent user study (\S~\ref{sec:study}). \item The most valuable insight however, was that the user stroke in mid-air often tended to {\bf mimic} the expected projected curve. \end{itemize} Context-free approaches, by design, are unable to capture this mimicry, i.e., the notion that the change between projected point as we draw a stroke is commensurate with the change in the 3D points along the stroke. This inability due to a lack of curve history or context, materializes as problems in different forms. \begin{figure} \centering \includegraphics[width=\linewidth]{history_free_problems} \caption{Context-free projection problems: projection discontinuities (a), undesirable snapping (b) large depth disparity (c) and unexpected jumps (d).} \label{fig:historyFreeProblems} \end{figure} \subsubsection{Projection Discontinuities} \label{sec:discontinuity} Proximal projection (including \emph{smooth-closest-point}) can be highly discontinuous with increasing distance from the 3D object, particularly in concave regions (Figure~\ref{fig:historyFreeProblems}a). Mid-air drawing along valleys without staying in precise contact with virtual object is thus extremely difficult. Raycast projections can similarly suffer large discontinuous jumps across occluded regions (in the ray direction) of the object (Figure~\ref{fig:historyFreeProblems}d). While this problem theoretically exists in 2D interfaces as well, it is less observed in practice for two reasons: 2D drawing on a constraining physical surface is significantly more precise than mid-air drawing in AR/VR~\cite{arora2017experimental}; and artists minimize such discontinuities by carefully choosing appropriate views (raycast directions) before drawing each curve. Automatic diretion control of view or controller, while effective in 2D \cite{ortega2014direct}), is detrimental to a sense of agency and presence in AR/VR. \subsubsection{Undesirable Snapping} \label{sec:undesirableSnapping} Proximity-based methods also tend to get stuck on sharp (or high curvature) convex features of the object (Figure~\ref{fig:historyFreeProblems}b). While this can be useful to trace along a ridge feature, it is particularly problematic for general curve-on-surface drawing. \subsubsection{Projection depth disparity} \label{sec:geometryIgnorance} The relative orientation between the 3D object surface and raycast direction can cause large depth disparities between parts of user strokes and curves projected by raycasting (Figure~\ref{fig:historyFreeProblems}c). Such irregular bunching or spreading of points on the projected curve also goes against our observation of stroke mimicry. Users can arguably reduce this disparity by continually orienting the view/controller to keep the projection ray well aligned with object surface normal. Such re-orientation however can be tiring, ergonomically awkward, and deviates from 2D experience, where pen/brush tilt only impacts curve aesthetic, and not shape. We noted that the {\it Occlude} and {\it Spraycan} techniques were complementary: drawing with {\it Occlude} on parts of an object frontal to the view provided good comfort and control, which degraded when drawing closer to the object silhouette, and observed the opposite when drawing with {\it Spraycan}. We thus implemented a hybrid projection, where the ray direction was interpolated between {\it Occlude} and {\it Spraycan} based on alignment with the most recently projected smooth surface normal. Unfortunately, the difference between {\it Occlude} and {\it Spraycan} ray directions was often large enough to make even smooth ray transitions abrupt and hard to control. All these problems point to the projection function ignoring the shape of the mid-air stroke $\mathbf{P}$ and the projected curve $\mathbf{Q}$, and can be addressed using projection functions that explicitly incorporate both. We call these functions \emph{anchored}. \subsection{Mimicry Projection} \label{sec:anchoredProximity} \begin{figure} \centering \includegraphics[width=\linewidth]{anchored_proximity} \caption{Anchored smooth-closest-point (a), and refinements: using a locally-fit plane (b), and anchor point constrained to an offset (c) or parallel surface (d). $\mathbf{q}_i$, is obtained by projecting $\mathbf{r}_i$ (a), $\mathbf{r}_i'$ (c), or $\mathbf{r}_i''$ (d) onto $\mathcal{M}$ via smooth-closest-point; or closest-point to $\mathbf{r}_i$ in $\mathcal{M}\cap N_i$ (b). } \label{fig:historyProximity} \end{figure} Controller sampling rate in current AR/VR systems is 50Hz or more, meaning that even during ballistic movements, the distance $\|\Delta\mathbf{p}_i\|$ for any stroke sample $i$ is of the order of a few millimetres. Consequently, the anchored stroke point $\mathbf{r}_i$ is typically much closer to $\mathcal{M}$, than the stroke point $\mathbf{p}_i$, making closest-point {\it snap} projection a compelling candidate for projecting $\mathbf{r}_i$. Such an \emph{anchored closest-point} projection explicitly minimizes $\|\Delta\mathbf{p}_i - \Delta\mathbf{q}_i\|$, but precise minimization is less important than avoiding projection discontinuities and undesirably snapping, even for points close to the mesh. Our formulation of a \emph{smooth-closest-point} projection $\pi_{SCP}$ in \S~\ref{sec:phong} addresses these goals precisely. Also note that the maximum observed $\|\Delta\mathbf{p}\|$ for the controller readily defines the offset distance $\mu$ for our pre-computed tet mesh $\mathcal{T}_\mathcal{M}^3$. We define \emph{mimicry} projection as \begin{equation} \label{eq:acp} \Pi_{mimicry}(\mathbf{p}_i) = \begin{cases} \pi_{spray}(\mathbf{p}_i) & \text{if } i=0, \\ \pi_{SCP}(\mathbf{r}_i) & \text{otherwise.} \end{cases} \end{equation} \subsection{Refinements to Mimicry Projection} We further explore refinements to \emph{mimicry} projection, that might improve curve projection in certain scenarios. {\bf Planar curves} are very common in design and visualization \cite{mccrae2011slices}. We can locally encourage planarity in mimicry projection by constructing a plane $N_i$ with normal $\Delta\mathbf{p}_i \times \Delta\mathbf{p}_{i-1}$ (i.e. the local plane of the mid-air stroke) and passing through the anchor point $\mathbf{r}_i$ (Figure~\ref{fig:historyProximity}b). We then intersect $N_i$ with $\mathcal{M}$. $\mathbf{q}_i$ is defined as the closest-point to $\mathbf{r}_i$ on the intersection curve that contains $\mathbf{q}_{i-1}$. Note, we use $\pi_{spray}(\mathbf{p}_i)$ for $i<2$, and we retain the most recently defined normal direction ($N_{i-1}$ or prior) when $N_i= \Delta\mathbf{p}_i \times \Delta\mathbf{p}_{i-1}$ is undefined. We find this method works well for near-planar curves, but the plane is sensitive to noise in the mid-air stroke (Figure~\ref{fig:anchoredProblems}f), and can feel {\it sticky} or less responsive for non-planar curves. {\bf Offset and Parallel surface drawing} captures the observation that users tend to draw an intended curve as a corresponding mid-air stroke on an imaginary offset or parallel surface of the object $\mathcal{M}$. While we do not expect users to draw precisely on such a surface, we note that is unlikely a user would intentionally draw orthogonal to such a surface along the gradient of the 3D object. In scenarios when a user is sub-consciously drawing on a offset surface of $\mathcal{M}$ (an isosurface of its signed-distance function $d_\mathcal{M}(\cdot)$), we can remove the component of a user stroke segment that lies along the gradient $\nabla d_\mathcal{M}$, when computing the desired anchor point $\mathbf{r}_i$ in Equation~\ref{eq:offsetSurface} as (Figure~\ref{fig:historyProximity}c): \begin{equation} \label{eq:offsetSurface} \mathbf{r}_i' = \mathbf{q}_{i-1} + \Delta\mathbf{p}_i - \Big(\Delta\mathbf{p}_i \cdot \nabla d_\mathcal{M}(\mathbf{p}_i) \Big)\nabla d_\mathcal{M}(\mathbf{p}_i) \end{equation} We can similarly locally constrain user strokes to a parallel surface of $\mathcal{M}$ in Equation~\ref{eq:parallelSurface} as: \begin{equation} \label{eq:parallelSurface} \mathbf{r}_i'' = \mathbf{q}_{i-1} + \Delta\mathbf{p}_i - \Big(\Delta\mathbf{p}_i \cdot \nabla d_\mathcal{M}(\mathbf{r}_i) \Big)\nabla d_\mathcal{M}(\mathbf{r}_i)\text{.} \end{equation} Note that the difference from Eq.~\ref{eq:offsetSurface} is the position where $\nabla d_\mathcal{M}$ is computed, as shown in Figure~\ref{fig:historyProximity}d. A parallel surface better matched user expectation than an offset surface in our pilot testing, but both techniques produced poor results when user drawing deviated from these imaginary surfaces (Figure~\ref{fig:anchoredProblems}g--l). \subsection{Anchored Raycast Projection} \label{sec:anchoredRaycast} \begin{figure} \centering \includegraphics[width=\linewidth]{anchored_raycast} \caption{Anchored raycast techniques: ray direction defined orthogonal to $\Delta\mathbf{p}_i$ in a local plane (a); parallel transport of ray direction along the user stroke (b). The cast rays (forward/backward) are shown in blue.} \label{fig:historyRaycast} \end{figure} For completeness, we also investigated raycast alternatives to projection of the anchored stroke point $\mathbf{r}_i$. We used similar priors of local planarity and offset or parallel surface transport as with mimicry refinement, to define ray directions. Figure~\ref{fig:historyRaycast} shows two such options. In Figure~\ref{fig:historyRaycast}a, we cast a ray in the local plane of motion, orthogonal to the user stroke, given by $\Delta\mathbf{p}_i$. We construct the local plane containing $\mathbf{r}_i$ spanned by $\Delta\mathbf{p}_i$ and $\mathbf{p}_{i-1} - \mathbf{q}_{i-1}$, and then define the direction orthogonal to $\Delta\mathbf{p}_i$ in this plane. Since $\mathbf{r}_i$ may be inside $\mathcal{M}$, we cast two rays bi-directionally $(\mathbf{r}_i, \pm \Delta\mathbf{p}_i^\bot)$, where \[\Delta\mathbf{p}_i^\bot = \Delta\mathbf{p}_i \times \big( \Delta\mathbf{p}_i \times \left( \mathbf{p}_{i-1} - \mathbf{q}_{i-1} \right) \big) \] If both rays successfully intersect $\mathcal{M}$, we choose $\mathbf{q}_i$ to be the point closer to $\mathbf{r}_i$, a heuristic that works well in practice. As with locally planar mimicry projection, this technique suffered from instability in the local plane. Motivated by mimicry, in Figure~\ref{fig:historyRaycast}b, we also explored parallel transport of the projection ray direction along the user stroke. For $i>0$, we parallel transport the previous projection direction $\mathbf{q}_{i-1} - \mathbf{p}_{i-1}$ along the mid-air curve by rotating it with the rotation that aligns $\Delta\mathbf{p}_{i-1}$ with $\Delta\mathbf{p}_{i}$. Once again bi-directional rays are cast from $\mathbf{r}_i$, and $\mathbf{q}_i$ is set to the closer intersection with $\mathcal{M}$. In general, we found that all raycast projections, even when anchored, suffered from unpredictability over long strokes and stroke discontinuities when there are no ray-object intersections (Figure~\ref{fig:anchoredProblems}n,o). \begin{figure*}[htb] \centering \includegraphics[width=\linewidth]{problems_anchored} \caption{{\it Mimicry} vs. other anchored stroke projections: Mid-air strokes are shown in \textbf{black} and {\it mimicry} curves in \textcolor{matlabred}{\textbf{red}}. Anchored closest-point (\textcolor{matlabblue}{\textbf{blue}}), is similar to {\it mimicry} on smooth, low-curvature meshes (a,b) but degrades with mesh detail/noise (c,d). Locally planar projection (\textcolor{matlabblue}{\textbf{blue}}) is susceptible local plane instability (e,f). Parallel (\textcolor{matlabpurple}{\textbf{purple}} h,k) or offset (\textcolor{matlabblue}{\textbf{blue}} i,l) surface based projection fail in (h,l) when the user stroke deviates from said surface, while {\it mimicry} remains reasonable (g, j). Compared to {\it mimicry} (m), anchored raycasting based on a local plane (\textcolor{matlabpurple}{\textbf{purple}} n), or ray transport (\textcolor{matlabblue}{\textbf{blue}} o) can be discontinuous.} \label{fig:anchoredProblems} \end{figure*} \subsection{Final Analysis and Implementation Details} \label{sec:implementation} In summary, extensive pilot testing of the anchored techniques revealed that they seemed generally better than context-free approaches, specially when users drew further away from the 3D object. Among the anchored techniques, stroke mimicry captured as an \emph{anchored-smooth-closest-point} projection, proved to be theoretically elegant, and practically the most resilient to ambiguities of user intent and differences of drawing style among users. \emph{Anchored closest-point} can be a reasonable proxy to \emph{anchored smooth-closest-point} when pre-processing the 3D virtual objects is undesirable. Our techniques are implemented in C\#, with interaction, rendering, and VR support provided by the Unity Engine. For the smooth closest-point operation, we modified Panozzo et al.'s~\shortcite{panozzo2013weighted} reference implementation, which includes pre-processing code written in MATLAB and C++, and real-time code in C++. The real-time projection implementation is exposed to our C\# application via a compiled dynamic library. In their implementation, as well as ours, $d=8$; that is, we embed $\mathcal{M}$ in $\mathbb{R}^8$ for computing the Phong projection. We use $\mu=20\text{cm}$, and compute the offset surfaces using \texttt{libigl}~\cite{libigl}. We then improve the surface quality using TetWild~\cite{hu2018tetwild}, before computing the tetrahedral mesh $\mathcal{T}_\mathcal{M}$ between the two surfaces using TetGen~\cite{si2015tetgen}. We support fast closest-point queries, using an AABB tree implemented in \texttt{geometry3Sharp}~\cite{geometry3sharp}. Signed-distance is also computed using the AABB tree and fast winding number~\cite{barill2018fast}, and gradient $\nabla d_\mathcal{M}$ computed using central finite differences. To ease replication of our various techniques and aid future work, we will open-source our implementation. We now formally compare our most promising projection \emph{mimicry}, to the best state-of-the-art context-free projection {\it spraycan}. \begin{figure} \centering \includegraphics[width=\linewidth]{all_shapes} \caption{The six shapes utilized in the user study. The \emph{torus} shape was used for tutorials, while the rest were used for the recorded experimental tasks.} \label{fig:studyShapes} \end{figure} \subsection{Sampling the Target Curves} \label{sec:sampling} We wanted to design target curves that could be executed using a single smooth motion. Since users typically draw sharp corners using multiple strokes \cite{bae08ilovesketch}, we constrain our target curves to be smooth, created using cardinal cubic B-splines on the meshes, computed using Panozzo et al.~\shortcite{panozzo2013weighted}. We also control the length and curvature complexity of the curves, as pilot testing showed that very simple and short curves can be reasonably executed by almost any projection technique. Curve length and complexity is modeled by placing spline control points at mesh vertices, and specifying the desired geodesic distance and Gau{\ss} map distance between consecutive control points on the curve. We represent a target curve using four parameters $\langle n, i_0, k_G, k_N \rangle$, where $n$ is the number of spline control points, $i_0$ the vertex index of the first control point, and $k_G, k_N$ constants that control the geodesic and normal map distance between consecutive control points. We define the desired geodesic distance between consecutive control points as, $D_G = k_G\times\|\mathtt{BBox}(\mathcal{M})\|$, where $\|\mathtt{BBox}(\mathcal{M})\|$ is the length of the bounding box diagonal of $\mathcal{M}$. The desired Gau{\ss} map distance (angle between the unit vertex normals) between consecutive control points is simply $k_N$. A target curve $\mathbf{C}_0, \ldots, \mathbf{C}_{n-1}$ starting at vertex $\mathbf{v}_{i_0}$ of the mesh is generated incrementally for $i>0$ as: \begin{equation} \mathbf{C}_i = \argmin_{\mathbf{v}\in V'} \ \big(d_G(\mathbf{C}_{i-1}, \mathbf{v}) - D_G\big)^2 + \big(d_N(\mathbf{C}_{i-1}, \mathbf{v}) - k_N\big)^2, \end{equation} where $d_G$ and $d_N$ compute the geodesic and normal distance between two points on $\mathcal{M}$, and $V'\subset V$ contains only those vertices of $\mathcal{M}$ whose geodesic distance from $\mathbf{C}_0, \ldots, \mathbf{C}_{i-1}$ is at least $D_G/2$. The restricted subset of vertices conveniently helps prevent (but doesn't fully avoid) self-intersecting or nearly self-intersecting curves. Curves with complex self-intersections are less important practically, and can be particularly confusing for the curve re-creation task. All our target curve samples were generated using $k_G\in[0.05, 0.25]$, $k_N\in[\pi/6, 5\pi/12]$, $n=6$, and a randomly chosen $i_0$. The curves were manually inspected for self-intersections, and infringing curves rejected. We then defined keypoints on the target curves as follows: curve endpoints were chosen as keypoints; followed by greedily picking extrema of geodesic curvature, while ensuring that the arclength distance between any two consecutive keypoints was at least 3cm; and concluding the procedure when the maximum arclength distance between any consecutive keypoints was below 15cm. Our target curves had between 4--9 keypoints (including endpoints). \subsection{Experiment Design} \label{ref:expDesign} The main variable studied in the experiment was \emph{Projection method}---\emph{spraycan} vs. \emph{mimicry}---realized as a within-subjects variable. The order of methods was counterbalanced between participants. For each method, participants were exposed to all the six objects. Object order was fixed as torus, cube, trebol, bunny, hand, and fertility, based on our personal judgment of drawing difficulty. The torus was used as a tutorial, where participants had access to additional instructions visible in the scene and their strokes were not utilized for analysis. For each object, the order of the 10 target strokes was randomized. The first five were used for the tracing curves task, while the remaining five were used for re-creating curves. The target curve for the first tracing task was repeated after the five unique curves, to gauge user consistency and learning effects. A similar repetition was used for curve re-creation. Participants thus performed 12 curve drawing tasks per object, leading to a total of $12 \times 5$ (objects) $\times\ 2$ (projections) $= 120$ strokes per participant. Owing to the COVID-19 physical distancing guidelines, the study was conducted in the wild, on participants' personal VR equipment at their homes. A 15-minute instruction video introduced the study tasks and the two projection methods. Participants then filled out a consent form and a questionnaire to collect demographic information. This was followed by them testing the first projection method and filling out a questionnaire to express their subjective opinions of the method. They then tested the second method, followed by a similar questionnaire, and questions involving subjective comparisons between the two methods. Participants were required to take a break after testing the first method, and were also encouraged to take breaks after drawing on the first three shapes for each method. The study took approximately an hour, including the questionnaires. \subsection{Participants} \label{participants} Twenty participants (5 female) aged 21--47 from five countries participated in the study. All but one were right-handed. Participants self-reported a diverse range of artistic abilities (min. 1, max. 5, median 3 on a 1--5 scale), and had varying degrees of VR experience, ranging from below 1 year to over 5 years. Thirteen participants had a technical computer graphics or HCI background, while ten had experience with creative tools in VR, with one reporting professional usage. Participants were paid $\approx22$ USD as a gift card. \subsection{Apparatus} \label{sec:apparatus} As the study was conducted on personal VR setups, a variety of commercial VR devices were utilized---Oculus Rift, Rift S, and Quest using Link cable, HTC Vive and Vive Pro, Valve Index, and Samsung Odyssey using Windows Mixed Reality. All but one participant used a standing setup allowing them to freely move around. \subsection{Procedure} \label{sec:procedure} Before each trial, participants could use the ``grab'' button on their controller (in the dominant hand) to grab the mesh to position and orient it as desired. The trial started as soon as the participant started to draw by pressing the ``main trigger'' on their dominant hand controller. This action disabled the grabbing interaction---participants could not draw and move the object simultaneously. As noted earlier, for curve re-creation tasks, this had the additional effect of hiding the target curve, but leaving keypoints visible. \subsection{Data Processing and Filtering} \label{sec:dataProcess} We formulated three criteria to filter out meaningless user strokes:\\ {\it Short Curves:} we ignore projected curves $\mathcal{Q}$ that are too short as compared to the length of the target curves $\mathcal{X}$ (conservatively curves less than half as long as the target curve). While it is possible that the user stopped drawing mid-way out of frustration, we found it was more likely that they prematurely released the controller trigger by accident. Both curve lengths are computed in $\mathbb{R}^3$ for efficiency.\\ {\it Stroke Noise:} we ignore strokes for which the mid-air stroke is too noisy. Specifically, mid-air strokes with distant consecutive points ($\exists\ i\ \text{s.t.}\ \|\mathbf{p}_i - \mathbf{p}_{i-1}\| > 5\text{cm}$) are rejected.\\ {\it Inverted Strokes:} while we labelled keypoints with numbers and marked start and end points in green and red (Figure~\ref{fig:studyTasks}), some users occasionally drew the target curve in reverse. The motion to draw a curve in reverse is not symmetric, and such curves are thus rejected. We detect inverted strokes by look at the indices $i_0, i_1, \ldots, i_l$ of the points in $\mathcal{Q}$ which are closest to the keypoints $\mathbf{x}_{k_0}, \mathbf{x}_{k_1}, \ldots, \mathbf{x}_{k_l}$ of $\mathcal{X}$. Ideally, the sequence $i_0,\ldots, i_l$ should have no inversions, i.e., $\forall\ 0\le j<k\le l,\ i_j \le i_k$; and maximum $l(l+1)/2$ inversions, if $\mathcal{Q}$ is aligned in reverse with $\mathcal{X}$. We consider curves $\mathcal{Q}$ with more than $l(l+1)/4$ (half the maximum) inversions, to be inadvertently inverted and reject them. We compute distances to the keypoints in $\mathbb{R}^3$ for efficiency. Despite conducting our experiment remotely without supervision, we found that 95.6\% of the strokes satisfied our criteria and could be utilized for analysis. For comparisons between $\pi_{spray}$ and $\pi_{mimicry}$, we reject curve pairs where either curve did not satisfy the quality criteria. Out of 1200 curve pairs (2400 total strokes), 1103 (91.9\%) satisfied the quality criteria and were used for analysis, including 564 pairs for the curve re-creation task and 539 for the tracing task. \setlength{\tabcolsep}{3pt} \begin{table}[tbh] \centering \caption{Quantitative results (mean $\pm$ std-dev.) of the comparisons between \emph{mimicry} and \emph{spraycan} projection. All measures are analyzed using Wilcoxon signed-rank tests, lower values are better, and significantly better values ($p<.05$) are shown in \textbf{boldface}. Accuracy, aesthetic, and physical effort measures are shown with \textcolor{tablegreen}{green}, \textcolor{tablered}{red}, and \textcolor{tableblue}{blue} backgrounds, respectively. } \label{tbl:quantitativeResults} \begin{tabular}{@{}lccrr@{}} \midrule \multicolumn{5}{@{}c@{}}{\large{\textsc{Tracing}}}\\ \midrule \textbf{Measure\hspace{-1ex}} & \textbf{Spraycan} & \textbf{Mimicry} & \textbf{$p$-value} & \textbf{$z$-stat} \\ \rowcolor{tablegreen!30} $D_{ep}$ & 2.31 $\pm$ 2.64 mm & \textbf{1.13 $\pm$ 1.11 mm} & <.001 & 8.36 \\ \rowcolor{tablegreen!15} $D_{sym}$ & 0.64 $\pm$ 0.66 mm & 0.56 $\pm$ 0.44 mm & >.05 & -0.09 \\ \rowcolor{tablered!30} $K_E$ & 280 $\pm$ 262 rad/m & \textbf{174 $\pm$ 162 rad/m} & <.001 & 15.59 \\ \rowcolor{tablered!15} $K_g$ & 249 $\pm$ 245 rad/m & \textbf{152 $\pm$ 157 rad/m} & <.001 & 15.42 \\ \rowcolor{tablered!30} $F_g$ & 394 $\pm$ 413 rad/m & \textbf{248 $\pm$ 285 rad/m} & <.001 & 14.82 \\ \rowcolor{tableblue!15} $T_h$ & 0.81 $\pm$ 0.70 & \textbf{0.58 $\pm$ 0.40 } & <.001 & 7.93 \\ \rowcolor{tableblue!30} $R_h$ & 1.63 $\pm$ 2.18 rad/m & \textbf{1.18 $\pm$ 1.63 rad/m} & <.001 & 4.82 \\ \rowcolor{tableblue!15} $T_c$ & \textbf{1.05 $\pm$ 0.36 } & 1.10 $\pm$ 0.29 & <.001 & -3.36 \\ \rowcolor{tableblue!30} $R_c$ & 5.12 $\pm$ 5.88 rad/m & \textbf{3.79 $\pm$ 4.84 rad/m} & <.001 & 5.51 \\ \rowcolor{tableblue!15} $\tau$ & \textbf{4.69 $\pm$ 1.85 s} & 5.29 $\pm$ 2.17 s & <.001 & -7.32 \\ \midrule \multicolumn{5}{@{}c@{}}{\large{\textsc{Memory}}}\\ \midrule \textbf{Measure\hspace{-1ex}} & \textbf{Spraycan} & \textbf{Mimicry} & \textbf{$p$-value} & \textbf{$z$-stat} \\ \rowcolor{tablegreen!30} $D_{ep}$ & 2.34 $\pm$ 2.49 mm & \textbf{2.24 $\pm$ 23.32 mm} & <.001 & 8.63 \\ \rowcolor{tablegreen!15} $D_{sym}$ & 0.75 $\pm$ 0.65 mm & 1.12 $\pm$ 11.51 mm & >.05 & 0.55 \\ \rowcolor{tablered!30} $K_E$ & 254 $\pm$ 236 rad/m & \textbf{155 $\pm$ 127 rad/m} & <.001 & 14.70 \\ \rowcolor{tablered!15} $K_g$ & 223 $\pm$ 219 rad/m & \textbf{132 $\pm$ 123 rad/m} & <.001 & 14.95 \\ \rowcolor{tablered!30} $F_g$ & 348 $\pm$ 371 rad/m & \textbf{215 $\pm$ 227 rad/m} & <.001 & 14.11 \\ \rowcolor{tableblue!15} $T_h$ & 0.72 $\pm$ 0.54 & \textbf{0.54 $\pm$ 0.35 } & <.001 & 6.78 \\ \rowcolor{tableblue!30} $R_h$ & 1.50 $\pm$ 2.19 rad/m & \textbf{1.32 $\pm$ 1.99 rad/m} & .002 & 3.07 \\ \rowcolor{tableblue!15} $T_c$ & \textbf{1.05 $\pm$ 0.37 } & 1.11 $\pm$ 0.23 & <.001 & -5.94 \\ \rowcolor{tableblue!30} $R_c$ & 5.23 $\pm$ 6.36 rad/m & \textbf{3.63 $\pm$ 5.13 rad/m} & <.001 & 4.00 \\ \rowcolor{tableblue!15} $\tau$ & \textbf{4.33 $\pm$ 1.57 s} & 4.92 $\pm$ 1.89 s & <.001 & -7.12 \\ \end{tabular} \end{table} \setlength{\tabcolsep}{6pt} \subsection{Quantitative Analysis} \label{sec:quantitative} We define 10 different statistical measures (Table~\ref{tbl:quantitativeResults}) to compare $\pi_{spray}$ and $\pi_{mimicry}$ curves in terms of their accuracy, aesthetic, and effort in curve creation. We consistently use the non-parametric Wilcoxon signed rank test for all quantitative measures instead of a parametric test such as the paired $t$-test, since the recorded data for none of our measures was normally distributed (normality hypothesis rejected via the Kolmogorov-Smirnov test, $p<.005$). \subsubsection{Curve Accuracy} \label{sec:strokeAccuracy} Accuracy is computed using two measures of distance between points on the projected curve $\mathcal{Q}$ and target curve $\mathcal{X}$. Both curves are densely re-sampled using $m=101$ sample points equi-spaced by arc-length. Given $\mathcal{Q} = {\mathbf{q}_0, \ldots, \mathbf{q}_{m-1}}$ and $\mathcal{X} = {\mathbf{x}_0, \ldots, \mathbf{x}_{m-1}}$, we compute the \emph{average equi-parameter distance} $D_{ep}$ as \begin{equation} \label{eq:distanceEquiparameter} D_{ep}(\mathcal{Q}) = \frac1m \sum_{i=0}^{m-1} d_E\left( \mathbf{q}_i, \mathbf{x}_i \right) \text{,} \end{equation} where $d_E$ computes the Euclidean distance between two points in $\mathbb{R}^3$. We also compute the \emph{average symmetric distance} $D_{sym}$ as \begin{equation*} \label{eq:distanceSymmetric} D_{sym}(\mathcal{Q}) = \frac1{2m} \sum_{i=0}^{m-1}\left( \min_{\mathbf{x}\in X} d_E\left( \mathbf{q}_i, \mathbf{x} \right) \right) + \frac1{2m} \sum_{i=0}^{m-1}\left( \min_{\mathbf{q}\in Q} d_E\left( \mathbf{q}, \mathbf{x}_i \right) \right) \end{equation*} In other words, $D_{ep}$ computes the distance between corresponding points on the two curves and $D_{sym}$ computes the average minimum distance from each point on one curve to the other curve. For both tracing and re-creation tasks, $D_{ep}$ indicated that \emph{mimicry} produced significantly better results than \emph{spraycan} (see Table~\ref{tbl:quantitativeResults}, Figure~\ref{fig:teaser}c,~\ref{fig:smoothnessResult}). The $D_{sym}$ difference was not statistically significant, evidenced by users correcting their strokes to stay close to the intended target curve (at the expense of curve aesthetic). \subsubsection{Curve Aesthetic} \label{sec:strokeQuality} \begin{figure} \centering \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.44\linewidth]{quant_gkmean_tracing} \includegraphics[width=0.44\linewidth]{quant_gkmean_memory} \caption{Normalized geodesic curvature $K_g$.} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.44\linewidth]{quant_gfair_tracing} \includegraphics[width=0.44\linewidth]{quant_gfair_memory} \caption{Normalized fairness deficiency $F_g$.} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.88\linewidth]{example_strokes} \caption{Example strokes, \textcolor{matlaborange}{orange} points in (a, b) above.} \end{subfigure} \caption{Curvature measures (a,b) indicate that \emph{mimicry} produces significantly smoother and fairer curves than \emph{spraycan} for both tracing (left) and re-creating tasks (right). Pairwise comparison plots between \emph{mimicry} (y-axis) and \emph{spraycan} (x-axis), favour \emph{mimicry} for the vast majority of points (points below the $y=x$ line). A linear regression fit (on the log plots) is shown as a dashed line. Example curve pairs (\textcolor{matlaborange}{orange} points) for curve tracing (left) and re-creating (right) are also shown with the target curve $\mathcal{X}$ shown in gray (c).} \label{fig:smoothnessResult} \end{figure} For most design applications, jagged projected curves, even if geometrically quite accurate, are aesthetically undesirable~\cite{mccrae2008sketching}. Curvature-based measures are typically used to measure fairness of curves. We report three such measures of curve aesthetic for the projected curve $\mathcal{Q}$. We note that the smoothness quality of the user stroke $\mathcal{P}$, was similar to $\mathcal{Q}$ and significantly poorer than the target curve $\mathcal{X}$. This is expected since drawing in mid-air smoothly and with precision is difficult, and such strokes are usually neatened post-hoc \cite{arora2018symbiosis}. We therefore avoid comparisons to the target curve and simply report three aesthetic measures for a projected curve $\mathcal{Q}=\mathbf{q}_0,\ldots, \mathbf{q}_{n-1}$. We first refine $\mathcal{Q}$ by computing the exact geodesic on $\mathcal{M}$ between consecutive points of $\mathcal{Q}$ ~\cite{surazhsky2005fast}, to create $\widehat{\mathcal{Q}}$ with points $\widehat{\mathbf{q}}_0, \ldots, \widehat{\mathbf{q}}_{k-1}$, $k\ge n$. We choose to normalize our curvature measures using $L_{\mathcal{X}}$, the length of the corresponding target stroke $\mathcal{X}$. The \emph{normalized Euclidean curvature} for $\mathcal{Q}$ is defined as \begin{equation} \label{eq:euclideanCurvature} K_E(\mathcal{Q}) = \frac1{L_{\mathcal{X}}} \sum_{i=1}^{k-1} \theta_i \end{equation} where $\theta_i$ is the angle between the two segments of $\widehat{\mathcal{Q}}$ incident on $\widehat{\mathbf{q}}_i$. Thus, $K_E$ is the total discrete curvature of $\widehat{\mathcal{Q}}$, normalized by the target curve length. Since $\widehat{\mathcal{Q}}$ is embedded in $\mathcal{M}$, we can also compute discrete \emph{geodesic} curvature, computed as the deviation from the straightest geodesic for a curve on surface. Using a signed $\theta^g_i$ defined at each point $\widehat{\mathbf{q}}_i$ via Polthier and Schmies's definition~\shortcite{polthier2006straightest}, we compute \emph{normalized geodesic curvature} as \begin{equation} \label{eq:geodesicCurvature} K_g(\mathcal{Q}) = \frac1{L_{\mathcal{X}}} \sum_{i=1}^{k-1} |\theta_i^g|\text{.} \end{equation} Finally, we define fairness~\cite{arora2017experimental, mccrae2008sketching} as a first-order variation in geodesic curvature, thus defining the \emph{normalized fairness deficiency} as \begin{equation} \label{eq:fairness} F_g(\mathcal{Q}) = \frac1{L_{\mathcal{X}}} \sum_{i=2}^{m-1} |\theta_i^g - \theta_{i-1}^g|\text{,} \end{equation} For all three measures, a lower value indicates a smoother, pleasing, curve. Wilcoxon signed-rank tests on all three measures indicated that {\it mimicry} produced significantly smoother and better curves than {\it spraycan} (Table~\ref{tbl:quantitativeResults}). \subsubsection{Physical Effort} \label{sec:effortQuantitative} Quantitatively, we use the amount of head (HMD) and hand (controller) movement, and stroke \emph{execution time} $\tau$, as proxies for physical effort. For head and hand translation, we first filter the position data with a Gaussian-weighted moving average filter with $\sigma=20\text{ms}$. We then define \emph{normalized head/controller translation} $T_h$ and $T_c$ as the length of the poly-line defined by the filtered head/controller positions normalized by the length of the target curve $L_\mathcal{X}$. An important ergonomic measure is the amount of head/hand rotation required to draw the mid-air stroke. We first de-noise or filter the forward and up vectors of the head/controller frame, using the same filter as for positional data. We then re-orthogonalize the frames and compute the length of the curve defined by the filtered orientations in $\mathrm{SO(3)}$, using the angle between consecutive orientation data-points. We define \emph{normalized head/controller rotation} $R_h$ and $R_c$ as its orientation curve length, normalized by $L_\mathcal{X}$. Table~\ref{tbl:quantitativeResults} summarizes the physical effort measures. We observe lower controller translation (effect size $\approx 5\%$) and execution time (effect size $\approx 12\%$) in favour of {\it spraycan}; lower head translation and orientation (effect sizes $\approx 36\%, 26\%$) in favour of {\it mimicry}. Noteworthy, is the significantly reduced controller rotation using {\it mimicry}, with {\it spraycan} unsurprisingly requiring $35\%$ (tracing) and 44\% (re-creating) more hand rotation from the user. \begin{figure} \centering \includegraphics[width=\linewidth]{qual_difficulty} \caption{Perceived difficulty of drawing for the six 3D shapes in the study.} \label{fig:difficulty} \end{figure} \begin{figure} \centering \begin{subfigure}{\linewidth} \centering \includegraphics[width=\linewidth]{qual_accuracy} \caption{Perceived accuracy.} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=\linewidth]{qual_smoothness} \caption{Perceived smoothness.} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=\linewidth]{qual_effort} \caption{Physical and mental effort ratings.} \end{subfigure} \caption{Participants perceived \emph{mimicry} to be better than \emph{spraycan} in terms of accuracy (a), curve aesthetic (b) and user effort (c).} \label{fig:qualitativeComparison} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{preference_understand} \caption{Participants stated understanding \emph{spraycan} projection better (left); 17/20 users stated an overall preference for \emph{mimicry} over \emph{spraycan} (right). } \label{fig:prefenceUnderstanding} \end{figure} \subsubsection{Quantifying Users' Tendency to Mimic} \label{Sec:mimicriness} The study also provided an opportunity to test if the users actually tended to mimic their intended curve $\mathcal{X}$ in the mid-air stroke $\mathcal{P}$. To quantify the ``mimcriness'' of a stroke, we subsample $\mathcal{P}$ and $\mathcal{X}$ into $m$ points as in \S~\ref{sec:strokeAccuracy}, use the correspondence as in Eq.~\ref{eq:distanceEquiparameter} and look at the variation in the distance (distance between the closest pair of corresponding points subtracted from that of the farthest pair) as a percentage of the target length $L_\mathcal{X}$. We call this measure the \emph{mimicry violation} of a stroke. Intuitively, the lower the \emph{mimicry violation}, the closer the stroke $\mathcal{P}$ is to being a perfect mimicry of $\mathcal{X}$, going to zero if it is a precise translation of $\mathcal{X}$. Notably, users depicted very similar trends to mimic for both the techniques---with 86\% (\emph{mimicry}), 80\% (\emph{spraycan}) strokes exhibiting \emph{mimicry violation} below 25\% of $L_\mathcal{X}$, and 71\%, 66\% below 20\% of $L_\mathcal{X}$---suggesting that mimicry is indeed a natural tendency. \subsubsection{Consistency across Repeated Strokes} \label{sec:repeat} Recall that users repeated 2 of the 10 strokes per shape for both the techniques. To analyze consistency across the repeated strokes, we compared the values of the stroke accuracy measure $D_{eq}$ and the aesthetic measure $F_g$ between the original stroke and the corresponding repeated stroke. Specifically, we measured the relative change $|f(i) - f(i')|/f(i)$, where $(i, i')$ is a pair of original and repeated strokes, and $f(\cdot)$ is either $D_{eq}$ or $F_g$. Users were fairly consistent across both the techniques, with the average consistency for $D_{eq}$ being 35.4\% for \emph{mimicry} and 36.8\% for \emph{spraycan}, while for $F_g$, it was 36.5\% and 34.1\%, respectively. Note that the averages were computed after removing extreme outliers outside the $5\sigma$ threshold. \begin{figure*} \centering \includegraphics[width=\linewidth]{complex_curves} \caption{Gallery of free-form curves in \textcolor{matlabred}{\textbf{red}}, drawn using \emph{mimicry}. From left to right, tracing geometric features on the bunny, smooth maze-like curves on the cube, maze-like curve with sharp corners and a spiral on the trebol, and artistic tattoo motifs on the hand. Some mid-air strokes (\textbf{black}) are hidden for clarity.} \label{fig:curveGallery} \end{figure*} \subsection{Qualitative Analysis} \label{sec:qualitative} The mid- and post-study questionnaires elicited qualitative responses from participants on their perceived difficulty of drawing, curve accuracy and smoothness, mental and physical effort, understanding of the projection methods, and overall method of preference. Participants rated their perceived difficulty in drawing on the 6 study objects (Figure~\ref{fig:difficulty}), validating our ordering of shapes in the experiment based on expected drawing difficulty. Accuracy, smoothness, physical/mental effort responses were collected via 5-point Likert scales. We consistently order the choices from 1 (worst) to 5 (best) in terms of user experience in Figure~\ref{fig:qualitativeComparison}, and reported median ($M$) scores here. {\it Mimicry} was perceived to be a more accurate projection method (tracing, re-creating $M=3,3.5$) compared to {\it spraycan} ($M=2,2$), with 9 participants perceiving their traced curves to be either \emph{very accurate} or \emph{somewhat accurate} with {\it mimicry} (compared to 2 for {\it spraycan}) (Figure~\ref{fig:qualitativeComparison}a). User perception of stroke smoothness was also consistent with quantitative results, with {\it mimicry} (tracing, re-creating $M=4,4$) clearly outperforming {\it spraycan} (tracing, re-creating $M=1,2$) (Figure~\ref{fig:qualitativeComparison}b). Lastly, with no need for controller rotation, {\it mimicry} ($M=3$) was perceived as less physically demanding than {\it spraycan} ($M=2$), as expected (Figure~\ref{fig:qualitativeComparison}c). The response to understanding and mental effort was more complex. {\it Spraycan}, with its physical analogy and mathematically precise definition was clearly understood by all 20 participants (17 very well, 3 somewhat) (Figure~\ref{fig:prefenceUnderstanding}a). {\it Mimicry}, conveyed as ``drawing a mid-air stroke on or near the object as similar in shape as possible to the intended projection'', was less clear to users (7 very well, 11 somewhat, 3 not at all). Despite not understanding the method, the 3 participants were able to create curves that were both accurate and smooth. Further, users perceived {\it mimicry} ($M=2.5$) as less cognitively taxing than {\it spraycan} ($M=2$) (Figure~\ref{fig:qualitativeComparison}c). We believe this may be because users were less prone to consciously controlling their stroke direction and rather focused on drawing. The tendency to mimic may have thus manifested sub-consciously, as we had observed in pilot testing. The most important qualitative question was user preference (Figure~\ref{fig:prefenceUnderstanding}b). $85\%$ of the 20 participants preferred {\it mimicry} (10 highly preferred, 7 somewhat preferred). The remaining users were neutral (1/20) or somewhat preferred {\it spraycan} (2/20). \begin{figure}[b!] \centering \includegraphics[width=\linewidth]{texture} \caption{{\it Mimicry} used to interactively paint textures on 3D objects. } \label{fig:texturing} \end{figure} \subsection{Participant Feedback} We also asked participants to elaborate on their stated preferences and ratings. Participants (\emph{P4,8,16,17}) noted discontinuous \pquote{jumps} caused by {\it spraycan}, and felt the continuity guarantee of {\it mimicry}: \pquote[P6]{seemed to deal with the types of jitter and inaccuracy VR setups are prone to better}; \pquote[P9]{could stabilize my drawing}. \emph{P9,15} felt that {\it mimicry} projection was smoothing their strokes (no smoothing was employed): we believe this may be the effect of noise and inadvertent controller rotation, which {\it mimicry} ignores, but can cause large variations with {\it spraycan}, perceived as curve smoothing. Some participants (\emph{P4,17}) felt that rotating the hand smoothly while drawing was difficult, while others missed the {\it spraycan} ability to simply use hand rotation to sweep out long projected curves from a distance (\emph{P2,7}). Participants commented on physical effort: \pquote[P4]{Mimicry method seemed to required [sic] much less head movement, hand rotation and mental planning}. Participants appreciated the anchored control of {\it mimicry} in high-curvature regions (\emph{P1,2,4,8}) also noting that with {\it spraycan}, \pquote[P1]{the curvature of the surface could completely mess up my stroke}. Some participants did feel that {\it spraycan} could be preferable when drawing on near-flat regions of the mesh (\emph{P3,14,19,20}). Finally, participants who preferred spraycan felt that mimicry required more thinking: \pquote[P3]{with mimicry, there was extra mental effort needed to predict where the line would go on each movement}, or because mimicry felt \pquote[P7]{unintuitive} due to their prior experience using a {\it spraycan} technique. Some who preferred {\it mimicry} found it difficult to use initially, but felt it got easier over the course of the experiment (\emph{P4,17}). \subsection{Texture Painting} \emph{Texture Painting:} Figures~\ref{fig:teaser}e, \ref{fig:texturing} show examples of textures painted in VR using {\it mimicry}. The long, smooth, wraparound curves on the torus, are especially hard to draw with 2D interfaces. Our implementation uses Discrete Exponential Maps (DEM)~\cite{schmidt2006discrete} to compute a dynamic local parametrization around each projected point $\mathbf{q}_i$, to create brush strokes or geometric stamps on the object. \emph{Mesh Segmentation: } Figures~\ref{fig:teaser}e and \ref{fig:segmentation} show {\it mimicry} used for interactive segmentation in VR. In our implementation users draw an almost-closed curve $\mathcal{Q} = \{\mathbf{q}_0,\ldots,\mathbf{q}_{n-1}\}$ on the object using {\it mimcry}. We snap points $\mathbf{q}_i$ to their nearest mesh vertex, and use Dijkstra's shortest path to connect consecutive vertices, and to close the cycle of vertices. A mesh region is selected or segmented using mesh faces partitioned by these cycles that are easy to draw in AR/VR, but often require view changes and multiple strokes in 2D. \begin{figure} \centering \includegraphics[width=\linewidth]{segmentation} \caption{Interactive segmentation by drawing curves onto torus and bunny meshes. Each segmented portion is shown with a unique colour.} \label{fig:segmentation} \end{figure} \emph{Vector Field Design: } Vector fields on meshes are commonly used for texture synthesis~\cite{turk2001texture}, guiding fluid simulations~\cite{stam2003flows}, and non-photorealistic rendering~\cite{hertzmann2003illustrating}. We use {\it mimicry} curves as soft constraints to guide the vector field generation of Fisher et al.~\shortcite{fisher2007design}. Figure~\ref{fig:vectorFieldDesign} shows example vector fields, visualized using Line Integral Convolutions~\cite{cabral1993imaging} in the texture domain. \begin{figure} \centering \includegraphics[width=\linewidth]{vector_field_design} \caption{Smooth {\it mimicry} curves (\textcolor{matlabred}{\textbf{red}}) provide constraints for vector field design~\cite{fisher2007design}, which we visualize via Line Integral Convolutions~\cite{cabral1993imaging}.} \label{fig:vectorFieldDesign} \end{figure} \subsection{Mimicry Limitations} \paragraph{Mimicry Limitations} Our lack of a concise mathematical definition of observed stroke mimicry, makes it harder to precisely communicate it to users. While a precise mathematical formulation may exist, conveying it to non-technical users can still be a challenging task. {\it Mimicry} ignores controller orientation, producing smoother strokes with less effort, but can give participants a reduced sense of sketch control (\emph{P2,3,6}). We hypothesize that the reduced sense of control is in part due to the tendency for anchored smooth-closest-point to shorten the user stroke upon projection, sometimes creating a feeling of lag. {\it Spraycan} like techniques in contrast, have a sense of amplified immediacy, and the explicit ability to make lagging curves catch-up by rotating a controller in place. \paragraph{Future work} Our goal was to develop a general real-time inked projection with minimal stroke context via anchoring. Optimizing the method to account for the entire partially projected stroke may improve the projection quality. Relaxing the restriction of real-time inking would allow techniques such as spline fitting and global optimization that can account for the entire user stroke and geometric features of the target object. Local parametrizations such as DEM (\S~\ref{sec:applications}) can be used to incrementally grow or shrink the projected curve, so it does not lag the user stroke. Hybrid projections leveraging both proximity and raycasting are also subject to future work. On the interactive side, we did experiment with feedback to encourage users to draw closer to a 3D object. For example, we tried varying the appearance of the line connecting the controller to the projected point based on line length; or providing aural/haptic feedback if the controller got further than a certain distance from the object. While these techniques can help users in specific drawing or tracing tasks, we found them to be distracting and harmful to stroke quality for general stroke projection. Bimanual interaction in VR, such as rotating the shape with one hand while drawing on it with the other (suggested by \emph{P3,19}), can also be explored. Perhaps the most exciting area of future work is employing data-driven techniques to infer the user-intended projection, perhaps customized to the drawing style of individual users. Our study code and data will be made publicly available to aid in such endeavours. In summary, this paper presents early research on processing and projection of mid-air strokes drawn on and around 3D objects, that we hope will inspire further work and applications in AR/VR. \begin{acks} We are thankful to Michelle Lei for developing the initial implementation of the context-free techniques, and to Jiannan Li and Debanjana Kundu for helping pilot our methods. We also thank various 3D model creators and repositories for the models we utilized: Stanford bunny model courtesy of the Stanford 3D Scanning Repository, trebol model provided by Shao et al.\shortcite{shao2012crossshade}, fertility model courtesy the Aim@Shape repository, hand model provided by \texttt{Jeffo89} on \url{turbosquid.com}, and cup model (Figure~\ref{fig:2DProblems}) provided by Daniel Noree on \url{thingiverse.com} under a CC BY 4.0 license. \end{acks} \section{Introduction} \label{sec:intro} \input{1_intro} \section{Related Work} \label{sec:related} \input{2_related} \section{Projecting Strokes on 3D Objects} \label{sec:drawing} \input{3_drawing} \section{Anchored Stroke Projection} \label{sec:historical} \input{4_historical} \section{User Study} \label{sec:study} \input{5_study} \section{Study Results and Discussion} \label{sec:results} \input{6_results} \section{Applications} \label{sec:applications} \input{7_applications} \section{Conclusion} \label{sec:conclusion} \input{8_conclude} \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-09-22T02:01:44', 'yymm': '2009', 'arxiv_id': '2009.09029', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09029'}
arxiv
\section{Introduction} \label{sec:intro} \noindent One of the major challenges faced by an advanced-technology node IC designer is the overhead of large run-times of analysis tools. Fast and accurate analysis tools that aid quick design turn-around are particularly important for two critical, time-consuming simulations that are performed several times during the design cycle: \begin{itemize} \item {\em Thermal analysis}, which checks the feasibility of a placement/floorplan solution by computing on-chip temperature distributions in order to check for temperature hot spots. \item {\em IR drop analysis} in power distribution networks (PDNs), which diagnoses the goodness of the PDN by determining voltage (IR) drops from the power pads to the gates. \end{itemize} The underlying computational engines that form the crux of both analyses are similar: both simulate networks of conductances and current/voltage sources by solving a large system of equations of the form $G {\bf V} = {\bf J}$~\cite{Zhan08,Zhong05} with millions to billions of variables. In modern industry designs, a single full-chip temperature or IR drop simulation can take hours to several hours. Accelerating these analyses opens the door to optimizations in the design cycle that iteratively invoke these engines under the hood. The advent of machine learning (ML) has presented fast and fairly accurate solutions to these problems~\cite{zhang18, juan12, tan19, Lin18,incpird, powernet} which can successfully be used in early design cycle optimizations, operating within larger allowable error margins at these stages. To the best of our knowledge, no published work addresses full-chip ML-based thermal analysis: the existing literature focuses on coarser-level thermal modeling at the system level~\cite{zhang18, juan12, tan19}. For PDN analysis, the works in~\cite{Lin18, incpird} address incremental analysis, and are not intended for full-chip estimation. The work in~\cite{powernet} proposes a convolutional neural network (CNN)-based implementation for full-chip IR drop prediction, using cell-level power maps as features. However, it assumes similar resistance from each cell to the power pads, which may not be valid for practical power grids with irregular grid density. The analysis divides the chip into regions ({\it tiles}), and the CNN operates on each tile and its near neighbors. Selecting an appropriate tile and window size is nontrivial -- small windows could violate the principle of locality~\cite{Chiprout04}, causing inaccuracies, while large windows could result in large models with significant runtimes for training and inference. Our approach bypasses window size selection by providing the entire power map as a feature, allowing ML to learn the window size for accurate estimation. We translate static analysis problems to an image-to-image translation task and dynamic analysis problems to video-to-video translation, where the inputs are the power/current distributions and the required outputs are the temperature or IR drop contours. For static analysis, we employ fully convolutional (FC) EDGe networks for rapid and accurate thermal and IR drop analysis. FC EDGe networks have proven to be very successful with image-related problems with 2-D spatially distributed data~\cite{fcn, unet, mao16, segnet} when compared to other networks that operate without spatial correlation awareness. For transient analysis, we use long-short-term-memory (LSTM) based EDGe networks that maintain memory of analyses at prior time steps. \begin{figure}[tb] \centering \includegraphics[width=0.43\textwidth]{figs/enc-dec-arch.pdf} \caption{Image-to-image translation using EDGe network.} \label{fig:enc-dec-arch} \vspace{-1.5em} \end{figure} Based on these concepts, this work proposes two novel ML-based analyzers: {\bf ThermEDGe} for both \textit{full-chip} static and transient thermal analysis, and {\bf IREDGe} for \textit{full-chip} static IR drop estimation. The fast inference times of ThermEDGe and IREDGe enable {\bf full-chip} thermal and IR drop analysis in milliseconds, as opposed to runtimes of several hours using commercial tools. We obtain average error of 0.6\% and 0.008\% for ThermEDGe and IREDGe, respectively, over a range of testcases. {\em We will open-source our software.} Fig.~\ref{fig:enc-dec-arch} shows a general top-level structure of an EDGe network. It consists of two parts: (i) the encoder/downsampling path, which captures global features of the 2-D distributions of power dissipation, and produces a low-dimensional state space and (ii) the decoder/upsampling path, which transforms the state space into the required detailed outputs (temperature or IR drop contours). The EDGe network is well-suited for PDN/thermal analyses because: \\ {\em (a)} The convolutional nature of the encoder {\em captures the dependence of both problems on the spatial distributions of power}. Unlike CNNs, EDGe networks contain a decoder which acts as a generator to convert the extracted power and PDN density features into accurate high-dimensional temperature and IR drop contours across the chip. \\ {\em (b)} The trained EDGe network model for static analysis is {\em chip-area-independent}: it only stores the weights of the convolutional kernel, and the same filter can be applied to a chip of any size. The selection of the network topology (convolution filter size, number of convolution layers) is related to the expected sizes of the hotspots rather than the size of the chip: these sizes are generally similar for a given application domain, technology, and packaging choice. \\ {\em (c)} Unlike prior methods~\cite{powernet} that operate tile-by-tile, where finding the right tile and window size for accurate analysis is challenging, {\em the choice of window size is treated as an ML hyperparameter tuning problem} to decide the necessary amount of input spatial information. \section{EDGe Network for PDN and Thermal Analysis} \subsection{Problem formulations and data representation} \label{sec:problem-def} \noindent This section presents the ML-based framework for ThermEDGe and IREDGe. The first step is to extract an appropriate set of features from a standard design-flow environment. The layout database provides the locations of each instance and block in the layout, as outlined in Fig.~\ref{fig:data-rep}(a). This may be combined with information from a power analysis tool such as~\cite{voltus} (Fig.~\ref{fig:data-rep}(b)) that is used to build a 2-D spatial power map over the die area. \begin{figure}[tb] \centering \includegraphics[width=8.8cm]{figs/data-rep.pdf} \caption{Data representation: Mapping PDN and thermal analysis problems into image-to-image translations tasks.} \label{fig:data-rep} \vspace{-1em} \end{figure} For thermal analysis using ThermEDGe, both the inputs and outputs are images for the static case, and a sequence of images for the transient case. Each input image shows a 2-D die power distribution (static) image, and each output image is a temperature map across the die (Fig.~\ref{fig:data-rep}). For static PDN analysis, the output is an IR drop map across the full chip. However, in addition to the 2-D power distributions, IREDGe has two other inputs: \noindent (i)~\underline{\it A PDN density map}: This feature is generated by extracting the average PDN pitch in each region of the chip. For example, when used in conjunction with the PDN styles in~\cite{jsingh,OpeNPDN}, where the chip uses regionwise uniform PDNs, the average PDN density in each region, across all metal layers, is provided as an input (Fig.~\ref{fig:data-rep}(e)). \noindent (ii)~\underline{\it An effective distance to power pad}: This feature represents the equivalent distance from an instance to all power pads in the package. We compute the effective distance of each instance, $d_e$, to $N$ power pads on the chip as the harmonic sum of the distances to the pads: \begin{equation} d_e^{-1} = d_1^{-1} + d_2^{-1} + ...+d_N^{-1} \label{eq:deffective} \end{equation} where $d_i$ is the distance of the $i^{th}$ power pad from the instance. Intuitively, the effective distance metric and the PDN density map together, represent the equivalent resistance between the instance and the pad. The equivalent resistance is a parallel combination of each path from the instance to the pad. We use distance to each pad as a proxy for the resistance in Eq.~\eqref{eq:deffective}. Fig.~\ref{fig:data-rep}(f) shows a typical ``checkerboard'' power pad layout for flip-chip packages~\cite{checkerboard1, checkerboard2}. Temperature depends on the ability of the package and system to conduct heat to the ambient, and IR drop depends on off-chip (e.g., package) parasitics. In this work, our focus is strictly on-chip, and both ThermEDGe and IR-EDGe are trained for fixed models of a given technology, package, and system. Next, we map these problems to standard ML networks: \begin{itemize} \item For static analysis, the problem formulations require a translation from an input power image to an output image, both corresponding to contour maps over the same die area, and we employ a {\em U-Net-based EDGe network}~\cite{unet}. \item The dynamic analysis problem requires the conversion of a sequence of input power images, to a sequence of output images of temperature contours, and this problem is addressed using an {\em LSTM-based EDGe network}~\cite{seq2seq}. \end{itemize} We describe these networks in the rest of this section. \begin{figure}[htb] \centering \includegraphics[width=8.8cm]{figs/thermedge-arch.pdf} \caption{U-Net-based EDGe network for static thermal and PDN analysis.} \label{fig:thermedge} \vspace{-1.5em} \end{figure} \subsection{U-Nets for static thermal and PDN analysis} \label{sec:unet} \subsubsection{Overview of U-Nets} CNNs are successful in extracting 2-D spatial information for image classification and image labeling tasks, which have low-dimensional outputs (class or label). For PDN and thermal analysis tasks, the required outputs are high-dimensional distributions of IR drop and temperature contour, where the dimensionality corresponds to the number of pixels of the image and the number of pixels is proportional to the size of the chip. This calls for a generator network that can translate the extracted low-dimensional power and PDN features from a CNN-like encoder back into high-dimensional representing the required output data. Fig.~\ref{fig:thermedge} shows the structure of the EDGe network used for static PDN and thermal analysis. At the top level, it consists of two networks: \noindent (a)~\underline{\em Encoder/downsampling network} Like a CNN, the network utilizes a sequence of 2-D convolution and max pooling layer pairs that extract key features from the high-dimensional input feature set. The convolution operation performs a weighted sum on a sliding window across the image~\cite{conv-deconv}, and the max pooling layer reduces the dimension of the input data by extracting the maximum value from a sliding window across the input image. In Fig.~\ref{fig:thermedge}, the feature dimension is halved at each stage by each layer pair, and after several such operations, an encoded, low-dimensional, compressed representation of the input data is obtained. For this reason, the encoder is also called the downsampling path: intuitively, downsampling helps understand the {\em ``what"} (e.g., ``Does the image contain power or IR hotspots?'') in the input image but tends to be imprecise with the {\em ``where"} information (e.g., the precise locations of the hotspots). The latter is recovered by the decoder stages. \noindent (b)~\underline{\em Decoder/upsampling network} Intuitively, the generative decoder is responsible for retrieving the {\em ``where"} information that was lost during downsampling, This distinguishes an EDGe network from its CNN counterpart. The decoder is implemented using the transpose convolution~\cite{conv-deconv} and upsampling layers. Upsampling layers are functionally the opposite of a pooling layer, and increase the dimension of the input data matrix by replicating the rows and columns. \subsubsection{Use of skip connections} Static IR drop and temperature are strongly correlated to the input power -- a region with high power on the chip could potentially have an IR or temperature hotspot in its vicinity. U-Nets~\cite{unet} utilize {\it skip} connections between the downsampling and upsampling paths, as shown in Fig.~\ref{fig:thermedge}. These connections take information from one layer and incorporate it using a {\it concatenation} layer at a deeper stage skipping intermediate layers, and appends it to the embedding along the z-dimension. For IR analysis, skip connections combine the local power, PDN information, and power pad locations from the downsampling path with the global power information from the upsampling path, allowing the underlying input features to and directly shuttle to the layers closer to the output, and are similarly helpful for thermal analysis. This helps recover the fine-grained ({\em ``where"}) details that are lost in the encoding part of the network (as stated before) during upsampling in the decoder for detailed temperature and IR drop contours. \subsubsection{Receptive fields in the encoder and decoder networks} The characteristic of PDN and thermal analyses problems is that the IR drop and temperature at each location depend on both the local and global power information. During convolution, by sliding averaging windows of an appropriate size across the input power image, the network captures local spatially correlated distributions. For capturing the larger global impact of power on temperature and IR drop, max pooling layers are used after each convolution to appropriately increase the size of the {\it receptive field} at each stage of the network. The {\it receptive field} is defined as the region in the input 2-D space that affects a particular pixel, and it determines the impact of the local, neighboring, and global features on PDN and thermal analysis. In a deep network, the value of each pixel feature is affected by all of the other pixels in the receptive field at the previous convolution stage, with the largest contributions coming from pixels near the center of the receptive field. Thus, each feature not only captures its receptive field in the input image, but also gives an exponentially higher weight to the middle of that region~\cite{receptive-field}. This matches with our applications, where both thermal and IR maps for a pixel are most affected by the features in the same pixel, and partially by features in nearby pixels, with decreasing importance for those that are farther away. The size of the receptive field at each stage in the network is determined by the convolutional filter size, number of convolutional layers, max pooling filter sizes, and number of max pooling layers. On both the encoder and decoder sides in Fig.~\ref{fig:thermedge}, we use three stacked convolution layers, each followed by 2$\times$2 max-pooling to extract the features from the power and PDN density images. The number of layers and filter sizes are determined based on the magnitude of the hotspot size encountered during design iterations. \subsection{LSTM-based EDGe network for transient thermal analysis} Long short term memory (LSTM) based EDGe networks are a special kind of recurrent neural network (RNN) that are known to be capable of learning long term dependencies in data sequences, i.e., they have a memory component and are capable of learning from past information in the sequence. \begin{figure}[h] \centering \includegraphics[width=0.47\textwidth]{figs/lstm-edge.pdf} \caption{LSTM-based EDGe network for transient analysis in ThermEDGe.} \label{fig:lstm-edge} \end{figure} \begin{figure}[h] \centering \includegraphics[width=8.5cm]{figs/conv-lstm.pdf} \caption{A fully connected LSTM cell (left) and a ConvLSTM cell (right).} \label{fig:conv-lstm} \end{figure} For transient thermal analysis, the structure of ThermEDGe is shown in Fig.~\ref{fig:lstm-edge}. The core architecture is an EDGe network, similar to the static analysis problem described in Section~\ref{sec:unet}, except that the network uses additional LSTM cells to account for the time-varying component. The figure demonstrates the time-unrolled LSTM where input power frames are passed to the network one frame at a time. The LSTM cell accounts for the history of the power maps to generate the output temperature frames for all time steps. The network is used for sequence-to-sequence translation in transient thermal analysis, where the input is a set of time-varying power maps and the output is a set of time-varying temperature maps (Section~\ref{sec:problem-def}). Similar to the static ThermEDGe network (Fig.~\ref{fig:thermedge}), the encoder consists of convolution and max pooling layers to downsample and extract critical local and global spatial information and the decoder consists of upsampling and transpose convolution layers to upsample the encoded output. However, in addition, transient ThermEDGe has LSTM layers in both the encoding and decoding paths. A standard LSTM cell is shown in Fig.~\ref{fig:conv-lstm} (left). While the basic LSTM cell uses fully connected layers within each gate, our application uses a variation of an LSTM cell called a convolutional LSTM (ConvLSTM)~\cite{conv-lstm}, shown in Fig.~\ref{fig:conv-lstm} (right). In this cell, the fully connected layers in each gate are replaced by convolution layers that capture spatial information. Thus, the LSTM-based EDGe network obtains a spatiotemporal view that enables accurate inference. \section{ThermEDGe and IREDGe Model Training} \noindent We train the models that go into ThermEDGe and IREDGe to learn the temperature and IR contours from the ``golden" commercial tool-generated or ground truth data. We train ThermEdge using the full physics-based thermal simulations from the Ansys-Icepak~\cite{icepak} simulator, incorporating off-chip thermal dynamics from package and system thermal characteristics. IREDGe is trained using static IR drop distribution from a PDN analyzer~\cite{pdnsim, voltus} for various power, PDN density, and power pad distributions. \subsection{Generating training data} \label{sec:train} \noindent {\bf Static ThermEDGe and IREDGe} A challenge we faced to evaluate our experiments is the dearth of public domain benchmarks that fit these applications. The IBM benchmarks~\cite{ibm}, are potential candidates for our applications, but they assume constant currents per region and represent an older technology node. Therefore, we generate our dataset which comprises of 50 industry-relevant testcases, where each testcase represents industry-standard workloads for commercial designs implemented in a FinFET technology. The power images of size 34$\times$32 pixels, with each pixel representing the power/temperature a 250$\mu$m$\times$250$\mu$m tile on an 8.5mm$\times$8mm chip.\footnote{Note that although the temperature and power map work at this resolution, the actual simulation consists of millions of nodes; using fewer node (e.g., one node per pixel) is grossly insufficient for accuracy.} Our training is specific to the resolution: for another image resolution, the model must be retrained. We reiterate that although the training is performed on chips of fixed size, as we show (Section~\ref{sec:results}), inference can be performed on a chip of any size as long as the resolution remains the same. For static ThermEDGe our training data is based on static Ansys-Icepak~\cite{icepak} simulations of these 50 testcases. For IREDGe, we synthesize irregular PDNs of varying densities for each dataset element using {\it PDN templates}, as defined by OpeNPDN~\cite{OpeNPDN}. These templates are a set of PDN building blocks, spanning multiple metal layers in a 14nm commercial FinFET technology, which vary in their metal utilization. For our testcases, we use three templates (high, medium, and low density) and divide the chip into nine regions. As outlined in Section~\ref{sec:problem-def}), we use a checkerboard pattern of power pads that vary in the bump pitch and offsets across the dataset. The synthesized full-chip PDN, power pad locations, and power distributions are taken as inputs into the IR analyzer~\cite{pdnsim} to obtain training data for IREDGe. For each of the 50 testcases, we synthesize 10 patterns of PDN densities, and for each combination of combination of power and PDN distribution we synthesize 10 patterns of power pad distributions, creating a dataset with 5000 points. \noindent {\bf Transient ThermEDGe} For the transient analysis problem, our training data is based on transient Ansys-Icepak~\cite{icepak} simulations. The size of the chip is the same as that of the static ThermEDGe testcases. For each testcase, we generate 45 time-step simulations that range from 0 to 3000s, with irregular time intervals from the thermal simulator. Each simulation is expensive in terms of the time and memory resources: one simulation of a 3000s time interval with 45 time-steps can take 4 hours with 2 million nodes. Transient ThermEDGe is trained using constant time steps of 15s which enables easy integration with existing LSTM architectures which have an implicit assumption of uniformly distributed time steps, without requiring additional features to account for the time. The model is trained on 150 testcases with time-varying workloads as features, and their time-varying temperature from Ansys-Icepak as labels. \vspace{-1.0em} \subsection{Model training} \label{sec:training} \noindent For the static analysis problem, ThermEDGe and IREDGe use a static power map as input and PDN density map (for IR analysis only) to predict the corresponding temperature and IR drop contours. For the transient thermal analysis problem, the input is a sequence of 200 power maps and the output is a sequence of 200 temperature contours maps at a 15s time interval. The ML model and training hyperparameters used for these models are listed in Table~\ref{tbl:parameters}. \begin{table}[h] \centering \caption{ThermEDGe and IREDGe ML hyperparameters} \label{tbl:parameters} \resizebox{\linewidth}{!}{% \begin{tabular}{||l||l|l||l|l|l||} \hhline{|t:===:t:===:t|} \multicolumn{3}{||l||}{ML hyperparameters} & \begin{tabular}[c]{@{}l@{}}Static\\ThermEDGe \end{tabular} & IREDGe & \begin{tabular}[c]{@{}l@{}}Transient\\ThermEDGe\end{tabular} \\ \hhline{|:=:t:==::===:|} \multirow{9}{*}{\begin{tabular}[c]{@{}l@{}}Model layer \\parameters \end{tabular}} & \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}2D\_conv1 \\2D\_conv\_trans1 \end{tabular}} & filter size & 5x5 & 3x3 & 5x5 \\ \cline{3-6} & & \# filters & 64 & 64 & 64 \\ \cline{2-6} & \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}2D\_conv2 \\2D\_conv\_trans2 \end{tabular}} & filter size & 3x3 & 3x3 & 3x3 \\ \cline{3-6} & & \# filters & 32 & 32 & 32 \\ \cline{2-6} & \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}2D\_conv3 \\2D\_conv\_trans3 \end{tabular}} & filter size & 3x3 & 3x3 & -- \\ \cline{3-6} & & \# filters & 16 & 16 & -- \\ \cline{2-6} & Max pool layers & filter size & 2x2 & 2x2 & 2x2 \\ \cline{2-6} & \multirow{2}{*}{ConvLSTM} & filter size & -- & -- & 7x7 \\ \cline{3-6} & & \# filters & -- & -- & 16 \\ \hhline{|:=::==::===:|} \multirow{8}{*}{\begin{tabular}[c]{@{}l@{}}Training \\parameters \end{tabular}} & \multicolumn{2}{l||}{Epochs} & \multicolumn{3}{l||}{500} \\ \cline{2-6} & \multicolumn{2}{l||}{Optimizer} & \multicolumn{3}{l||}{ADAM} \\ \cline{2-6} & \multicolumn{2}{l||}{Loss function} & \multicolumn{3}{l||}{Pixelwise MSE} \\ \cline{2-6} & \multicolumn{2}{l||}{Decay rate} & \multicolumn{3}{l||}{0.98} \\ \cline{2-6} & \multicolumn{2}{l||}{Decap steps} & \multicolumn{3}{l||}{1000} \\ \cline{2-6} & \multicolumn{2}{l||}{Regularizer} & \multicolumn{3}{l||}{L2} \\ \cline{2-6} & \multicolumn{2}{l||}{Regularization rate} & \multicolumn{3}{l||}{1.00E-05} \\ \cline{2-6} & \multicolumn{2}{l||}{Learning rate} & \multicolumn{3}{l||}{1.00E-03} \\ \hhline{|b:=:b:==:b:===:b|} \end{tabular} } \end{table} We split the data in each set, using 80\% of the data points for training, 10\% for test, and 10\% for validation. The training dataset is normalized by subtracting the mean and dividing by the standard deviation. The normalized golden dataset is used to train the network using an ADAM optimizer~\cite{adam} where the loss function is a pixel-wise mean square error (MSE). The convolutional operation in the encoder and the transpose convolution in the decoder are each followed by ReLU activation to add non-linearity and L2 regularization to prevent over fitting. The model is trained in Tensorflow 2.1 on an NVIDIA GeForce RTX2080Ti GPU. Training run-times are: 30m each for static ThermEDGe and IREDGe, and 6.5h for transient ThermEDGe. We reiterate that this is a one-time cost for a given technology node and package, and this cost is amortized over repeated use over many design iterations for multiple chips. \section{Temperature/IR drop Results using ThermEDGe/IREDGe} \section{Results and Analysis using TherEDGe/IREDGe} \label{sec:results} \subsection{Experimental setup and metric definitions} \noindent ThermEDGe and IREDGe are implemented using Python3.7 within a Tensorflow 2.1 framework. We test the performance of our models on the 10\% of datapoints reserved for the testset (Section~\ref{sec:training}) which are labeled T1--T21. As mentioned earlier in Section~\ref{sec:train}, due the unavailability of new, public domain benchmarks to evaluate our experiments, we use benchmarks that represent commercial industry-standard design workloads. \noindent {\bf Error metrics} As a measure of goodness of ThermEDGe and IREDGe predictions, we define a discretized regionwise error, $T_{err}~=~\left | T_{true} - T_{pred} \right | $, where $T_{true}$ is ground truth image, generated by commercial tools, and $T_{pred}$ the predicted image, generated by ThermEDGe. $IR_{err}$ is computed in a similar way. We report the average and maximum values of $T_{err}$ and $IR_{err}$ for each testcase. In addition, the percentage mean and maximum error are listed as a fraction of a temperature corner, i.e., 105$^\circ$C for thermal analysis and as a fraction of VDD$=0.7$V for IR drop analysis. \subsection{Performance of ThermEDGe and IREDGe: Accuracy and speed} \noindent \noindent {\bf Static ThermEDGe results} A comparison between the commercial tool-generated temperature and the ThermEDGe-generated temperature map for T1--T5 are listed in Table~\ref{tbl:thermal-results}. The runtime of static ThermEDGe for each the five testcases which are of size 34$\times$32 is approximately 1.1ms in our environment. On average across the five testcases (five rows of the table), ThermEDGe has an average $T_{err}$ of 0.63$^\circ$C and a maximum $T_{err}$ of 2.93$^\circ$C.\footnote{Achieving this accuracy requires much finer discretization in Icepak.} These numbers are a small fraction when compared to the maximum ground truth temperature of these testcases (85 -- 150$^\circ$C). The fast runtimes imply that our method can be used in the inner loop of a thermal optimizer, e.g., to evaluate various chip configurations under the same packaging solution (typically chosen early in the design process). For such applications, this level of error is very acceptable. \begin{table}[h] \centering \caption{Summary of ThermEDGe results for static and transient analysis across 10 testcases.} \label{tbl:thermal-results} \resizebox{\linewidth}{!}{% \begin{tabular}{||l|l|l||l|l|l||} \hhline{|t:===:t:===:t|} \multicolumn{3}{||c||}{{\bf Static ThermEDGe }} & \multicolumn{3}{|c||}{{\bf Transient ThermEDGe}} \\ \hhline{|:===::===:|} \textbf{\#Testcase} & \textbf{Avg. $\bf T_{err}$} & \textbf{Max $\bf T_{err}$} & \textbf{\#Testcase} & \textbf{Avg. $\bf T_{err}$} & \textbf{Max $\bf T_{err}$} \\ \hline \hline T1 & 0.64C (0.61\%) & 2.76C (2.63\%) & T6 & 0.51C (0.49\%) & 5.59C (5.32\%) \\ \hline T2 & 0.63C (0.60\%) & 2.67C (2.54\%) & T7 & 0.58C (0.55\%) & 6.17C (5.88\%) \\ \hline T3 & 0.65C (0.62\%) & 2.93C (2.79\%) & T8 & 0.57C (0.54\%) & 5.83C (5.55\%) \\ \hline T4 & 0.48C (0.46\%) & 2.22C (2.11\%) & T9 & 0.52C (0.50\%) & 6.32C (6.02\%) \\ \hline T5 & 0.75C (0.71\%) & 2.86C (2.72\%) & T10 & 0.56C (0.53\%) & 7.14C (6.80\%) \\ \hhline{|b:===:b:===:b|} \end{tabular} } \end{table} \begin{figure}[h] \centering \includegraphics[width=6.5cm]{figs/static-thermal-results.pdf} \caption{ThermEDGe static temperature estimation on T1: (a) input normalized power distribution, (b) histogram of $T_{err}$ where maximum error is 2.76$^\circ$C which is very small compared to the maximum temperature of 85$^\circ$C, (c) ground truth temperature map, and (d) predicted temperature map.} \label{fig:static-thermal-results} \end{figure} A graphical view of the predicted map for T1 is depicted in Fig.~\ref{fig:static-thermal-results}. For a given input power distribution in Fig.~\ref{fig:static-thermal-results}(a), ThermEDGe generates the temperature contour plots, as shown in Fig.~\ref{fig:static-thermal-results}(d). We compare the predicted value against the true value (Fig.~\ref{fig:static-thermal-results}(c)). The discrepancy is visually seen to be small. Numerically, the histogram in Fig.~\ref{fig:static-thermal-results}(b) shows the distribution of \%$T_{err}$ across regions (Fig.~\ref{fig:static-thermal-results}(b). The average $T_{err}$ 0.64$^\circ$C and the maximum $T_{err}$ is 2.93$^\circ$C. This corresponds an average error of 0.52\% and worst-case error of 2.79\% as shown in the figure. \noindent {\bf Transient ThermEDGe results} The transient thermal analysis problem is a sequence-to-sequence prediction task where each datapoint in the testset has 200 frames of power maps at a 15s interval. Trained transient ThermEDGe predicts the output temperature sequence for the input power sequence. We summarize the results in Table~\ref{tbl:thermal-results}. The inference run-times of T6--10 to generate a sequence 200 frames of temperature contours is approximately 10ms in our setup. Across the five testcases, the prediction has an average $T_{err}$ of 0.52\% and a maximum $T_{err}$ of 6.80\% as shown. The maximum $T_{err}$ in our testcases occur during transients which do not have long-last effects (e.g., on IC reliability). These errors are reduced to the average $T_{err}$ values at sustained peak temperatures. Fig.~\ref{fig:video} (left) shows an animated video of the time-varying power map for T6, where each frame (time-step) is after a 15s time interval. As before, the corresponding ground truth and predicted temperature contours are depicted in center and right, respectively, of the figure. \begin{figure}[ht] \centering \includegraphics[width=1.05\linewidth]{figs/video-frames/frame120.png} \caption{{\em [For an animated version, visit the GitHub repository: https://github.com/asp-dac/asp-dac-1323.git to view the video.]} Video comparing the prediction of transient ThermEDGe against commercial tool-generated temperature contours for T6: (i) left video shows the time-varying power map, (ii) center video shows the commercial tool-generated temperature maps, and (iii) right video shows ThermEDGe-generated temperature maps} \label{fig:video} \end{figure} \noindent {\bf IREDGe results} We compare IREDGe-generated contours against the contours generated by ~\cite{pdnsim} across 500 different testcases (10\% of the data, orthogonal to the training set) with varying PDN densities and power distributions. Across the five testcases in Table~\ref{tbl:iredge-qcomm-results}, IREDGe has an average $IR_{err}$ of 0.053mV and a worstcase max $IR_{err}$ of 0.34mV which corresponds to 0.008\% and 0.048\% of VDD respectively. Given that static IR drop constraints are 1--2.5\% of VDD, a worstcase error of 0.34mV is acceptable in light of the rapid runtimes. We list the results of five representative testcases in Table~\ref{tbl:iredge-qcomm-results} where the percentage errors in $IR_{err}$ are listed as fraction of VDD$=0.7$V. \begin{table}[htb] \caption{Summary of results from IREDGe for 10 different testcases. T16-T20 are testcases which have a chip size that was not in the training set. } \centering \label{tbl:iredge-qcomm-results} \resizebox{\linewidth}{!}{% \begin{tabular}{||l|l|l||l|l|l||} \hhline{|t:===:t:===:t|} \multicolumn{3}{||c||}{{\bf Chip size: 34x32 }} & \multicolumn{3}{|c||}{{\bf Chip size: 68x32}} \\ \hhline{|:===::===:|} \textbf{\#Testcase} & \textbf{Avg. $\bf IR_{err}$} & \textbf{Max $\bf IR_{err}$} & \textbf{\#Testcase} & \textbf{Avg. $\bf IR_{err}$} & \textbf{Max $\bf IR_{err}$} \\ \hline \hline T11 & 0.052mV (0.007\%) & 0.26mV (0.03\%) & T16 & 0.035mV (0.005\%) & 0.16mV (0.02\%)\\ \hline T12 & 0.074mV (0.011\%) & 0.34mV (0.05\%) & T17 & 0.054mV (0.008\%) & 0.42mV (0.06\%)\\ \hline T13 & 0.036mV (0.005\%) & 0.21mV (0.03\%) & T18 & 0.035mV (0.005\%) & 0.35mV (0.05\%)\\ \hline T14 & 0.053mV (0.008\%) & 0.24mV (0.03\%) & T19 & 0.068mV (0.010\%) & 0.22mV (0.03\%)\\ \hline T15 & 0.051mV (0.007\%) & 0.23mV (0.03\%) & T20 & 0.061mV (0.009\%) & 0.38mV (0.05\%)\\ \hhline{|b:===:b:===:b|} \end{tabular} } \end{table} \begin{figure}[htb] \centering \includegraphics[width=9cm]{figs/ir-results.pdf} \vspace{-3em} \caption{IREDGe static IR drop estimation on T11: (a) input power map, (b) input PDN density map, (c) effective distance to power pad map (d) ground truth IR drop map, (e) predicted IR drop map, and (f) histogram of $IR_{err}$ showing a worstcase error of 0.16mV.} \label{fig:ir-result} \end{figure} \begin{figure}[htb] \centering \vspace{-1.0em} \includegraphics[width=8.5cm]{figs/size-independent.pdf} \caption{Size independent nature of IREDGe: Comparison between (a) Actual IR drop contours and (b) IREDGe-predicted contours for a power map (T16) with size 68$\times$32 using a model that was trained on images of size 34$\times$32.} \label{fig:size-independent} \vspace{-0.5em} \end{figure} A detailed view of T11 is shown in Fig.~\ref{fig:ir-result}. It compares the IREDGe-generated IR drop contour plots against contour plot generated by~\cite{pdnsim}. The input power maps, PDN density maps, and effective distance to power pad maps are shown in Fig.~\ref{fig:ir-result}(a), (b), and (c) respectively. Fig.~\ref{fig:ir-result}(d) and (e) shows the comparison between ground truth and predicted value for the corresponding inputs. It is evident that the plots are similar; numerically, the histogram in Fig.~\ref{fig:ir-result}(f) shows the \%$IR_{err}$ where the worst \%$IR_{err}$ is less than 0.02\% of VDD. \noindent {\bf Size-independence} One of the primary advantages of using IREDGe for static IR estimation is that its fully-convolutional nature enables the use of input images of any size, and the size of the hotspot determines the model rather than the size of the chip. Since the trained model comprises only of the trained weights of the kernel, the same kernel can be used to predict the temperature contours of chip of any size as long as resolution of the represented image remains the same. We test static IREDGe on chips of a different size (T16 -- T20), using a power distribution of size $68\times32$ as input. Fig.~\ref{fig:size-independent}(a) compares the actual IR drop of T16 (Fig.~\ref{fig:size-independent}(a)) and the IREDGe-predicted (Fig.~\ref{fig:size-independent}(b)) solution of T16 using a model which was trained on $34\times32$ power maps. We summarize the results for the rest of the testcases in Table~\ref{tbl:iredge-qcomm-results}. \noindent {\bf Runtime analysis} A summary of the runtime comparison of our ML-based EDGe network approach against the temperature and IR drop golden solvers is listed in Table~\ref{tab:runtime}. The runtimes are reported on a NVIDIA GeForce RTX 2080Ti GPU. With the millisecond inference times, and the transferable nature of our trained models, the one-time cost of training the EDGe networks is easily amortized over multiple uses within a design cycle, and over multiple designs. \begin{table}[ht] \centering \caption{Runtime comparison between EDGe networks and golden thermal analysis and IR drop analysis tools} \label{tab:runtime} \resizebox{0.4\textwidth}{!}{% \begin{tabular}{|l|l|l|l|l|} \hline \textbf{Analysis type} & \textbf{\# Nodes} & \textbf{\begin{tabular}[c]{@{}l@{}}Design \\ Area \\ (mm$^2$)\end{tabular}} & \textbf{\begin{tabular}[c]{@{}l@{}}Icepak/\\ PDNSim \\ (minutes)\end{tabular}} & \textbf{\begin{tabular}[c]{@{}l@{}}ThermEDGe/\\ IREDGe\\ (milli seconds)\end{tabular}} \\ \hline Static thermal & 2.0 million & 64 & 30 mins & 1.1 ms \\ \hline Transient thermal & 2.0 million & 64 & 210 mins & 10 ms \\ \hline Static IR drop & 5.2 million & 0.16 & 310 mins & 1.1 ms \\ \hline \end{tabular}% } \end{table} \begin{figure}[ht] \centering \vspace{-0.5em} \includegraphics[width=8.5cm]{figs/power-net-comparison.pdf} \caption{IR drop comparisons on T21: (a) ground truth, (b) from IREDGe, and (c) from our implementation of PowerNet.} \vspace{-1.5em} \label{fig:powernet-comp} \end{figure} \subsection{IREDGe compared with PowerNet} \noindent We compare the performance of IREDGe against our implementation of PowerNet, based on its description in~\cite{powernet}. The layout is divided into tiles, and the CNN features are the 2-D power distributions (toggle rate-scaled switching and internal power, total power, and leakage power) within each tile and in a fixed window of surrounding tiles. The trained CNN is used to predict the IR drop on a tile-by-tile basis by sliding a window across all tiles on the chip. The work uses a tile size of 5$\mu$m$\times$5$\mu$m and takes into consideration a 31$\times$31 tiled neighborhood (window) power information as features. For a fair comparison, we train IREDGe under a fixed PDN density and fixed power pad locations that is used to train PowerNet. Qualitatively, IREDGe is superior on three aspects: \\ (1) {\em Tile and window size selection:} It is stated in~\cite{powernet} that when the size of the tile is increased from 1$\mu$m$\times$1$\mu$m to 5$\mu$m$\times$5$\mu$m and the size of the resulting window is increased to represent 31$\times$31 window of 25$\mu$m$^2$ tiles instead of 1$\mu$m$^2$ tiles, the accuracy of the PowerNet model improves. In general, this is the expected behavior with an IR analysis problem where the accuracy increases as more global information is available, until a certain radius after which the principle of locality holds~\cite{Chiprout04}. IREDGe bypasses this tile-size selection problem entirely by providing the entire power map as input to IREDGe and allowing the network to learn the window size that is needed for accurate IR estimation. \\ (2) {\em Run times:} Unlike PowerNet, which trains and infers IR drop on a sliding tile-by-tile basis, IREDGe has faster training and inference. IREDGe requires a {\em single} inference, irrespective of the size of the chip while PowerNet performs an inference for every tile in the chip. For this setup and data, it takes 75 minutes to train and implementation of PowerNet, as against 30 minutes for IREDGe. For inference, PowerNet takes 3.2ms while IREDGe takes 1.1ms for a 34$\times$32 chip size. For a chip of $68\times32$ IREDGe takes 1.3ms to generate IR drop contours while PowerNet takes 6.2ms. (3) {\em Model accuracy:} Since PowerNet uses a CNN to predict IR drop on a region-by-region basis, where each region is 5$\mu$m by 5$\mu$m, the resulting IR drop image is pixelated, and the predicted region prediction value does not correlate well with the neighboring regions. We compare IREDGe against our implementation of PowerNet on five different testcases T21--25. These testcases have the same power distribution in T11--15 except that all the five testscases have identical uniform PDNs, and identical power pad distributions, as required by PowerNet; IREDGe does not require this. Fig.~\ref{fig:powernet-comp} shows a comparison between the IR drop solutions from a golden solver (Fig.~\ref{fig:powernet-comp}(a)), IREDGe (Fig.~\ref{fig:powernet-comp}(b), and our implementation of PowerNet (Fig.~\ref{fig:powernet-comp}(c)) for T21 (a representative testcase). On average, across T21--25 IREDGe has an average $IR_{err}$ of 0.028mV and a maximum $IR_{err}$ of 0.14mV as against 0.042mV and 0.17mV respectively for PowerNet. \section{Conclusion} \noindent This paper addresses the compute-intensive tasks of thermal and IR analysis by proposing the use EDGe networks as apt ML-based solutions. Our EDGe-based solution not only improves runtimes but overcomes the window size-selection challenge (amount of neighborhood information required for accurate thermal and IR analysis), that is faced by other ML-based techniques, by allowing ML to learn the window size. We successfully evaluate EDGe networks for these applications by developing two ML software solutions (i) ThermEDGe and (ii) IREDGe for rapid on-chip (static and dynamic) thermal and (static) IR analysis respectively. In principle, our methodology is applicable to dynamic IR as well, but is not shown due to the unavailability of public-domain benchmarks.
{'timestamp': '2020-09-22T02:01:02', 'yymm': '2009', 'arxiv_id': '2009.09009', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09009'}
arxiv
\section{Introduction} The cross-entropy (CE) method is a probabilistic optimization approach that attempts to iteratively fit a distribution to elite samples from an initial input distribution \cite{rubinstein2004cross,rubinstein1999cross}. The goal is to estimate a rare-event probability by minimizing the \textit{cross-entropy} between the two distributions \cite{de2005tutorial}. The CE-method has gained popularity in part due to its simplicity in implementation and straightforward derivation. The technique uses \textit{importance sampling} which introduces a proposal distribution over the rare-events to sample from then re-weights the posterior likelihood by the \textit{likelihood ratio} of the true distribution over the proposal distribution. There are a few key assumptions that make the CE-method work effectively. Through random sampling, the CE-method assumes that there are enough objective function evaluations to accurately represent the objective. This may not be a problem for simple applications, but can be an issue for computationally expensive objective functions. Another assumption is that the initial parameters of the input distribution are wide enough to cover the design space of interest. For the case with a multivariate Gaussian distribution, this corresponds to an appropriate mean and wide covariance. In rare-event simulations with many local minima, the CE-method can fail to find a global minima especially with sparse objective function evaluations. This work aims to address the key assumptions of the CE-method. We introduce variants of the CE-method that use surrogate modeling to approximate the objective function, thus updating the belief of the underlying objective through estimation. As part of this approach, we introduce evaluation scheduling techniques to reallocate true objective function calls earlier in the optimization when we know the covariance will be large. The evaluation schedules can be based on a distribution (e.g., the Geometric distribution) or can be prescribed manually depending on the problem. We also use a Gaussian mixture model representation of the prior distribution as a method to explore competing local optima. While the use of Gaussian mixture models in the CE-method is not novel, we connect the use of mixture models and surrogate modeling in the CE-method. This connection uses each elite sample as the mean of a component distribution in the mixture, optimized through a subroutine call to the standard CE-method using the learned surrogate model. To test our approach, we introduce a parameterized test objective function called \textit{sierra}. The sierra function is built from a multivariate Gaussian mixture model with many local minima and a single global minimum. Parameters for the sierra function allow control over both the spread and distinction of the minima. Lastly, we provide an analysis of the weak areas of the CE-method compared to our proposed variants. \section{Related Work} \label{sec:related_work} The cross-entropy method is popular in the fields of operations research, machine learning, and optimization \cite{kochenderfer2015decision,Kochenderfer2019}. The combination of the cross-entropy method, surrogate modeling, and mixture models has been explored in other work \cite{bardenet2010surrogating}. The work in \cite{bardenet2010surrogating} proposed an adaptive grid approach to accelerate Gaussian-process-based surrogate modeling using mixture models as the prior in the cross-entropy method. They showed that a mixture model performs better than a single Gaussian when the objective function is multimodal. Our work differs in that we augment the ``elite'' samples both by an approximate surrogate model and by a subroutine call to the CE-method using the learned surrogate model. Other related work use Gaussian processes and a modified cross-entropy method for receding-horizon trajectory optimization \cite{tan2018gaussian}. Their cross-entropy method variant also incorporates the notion of exploration in the context of path finding applications. An approach based on \textit{relative entropy}, described in \cref{sec:background_ce}, proposed a model-based stochastic search that seeks to minimize the relative entropy \cite{NIPS2015_5672}. They also explore the use of a simple quadratic surrogate model to approximate the objective function. Prior work that relate cross-entropy-based adaptive importance sampling with Gaussian mixture models show that a mixture model require less objective function calls than a na\"ive Monte Carlo or standard unimodal cross-entropy-based importance sampling method \cite{kurtz2013cross,wang2016cross}. \section{Background} \label{sec:background} This section provides necessary background on techniques used in this work. We provide introductions to cross-entropy and the cross-entropy method, surrogate modeling using Gaussian processes, and multivariate Gaussian mixture models. \subsection{Cross-Entropy} \label{sec:background_ce} Before understanding the cross-entropy method, we first must understand the notion of \textit{cross-entropy}. Cross-entropy is a metric used to measure the distance between two probability distributions, where the distance may not be symmetric \cite{de2005tutorial}. The distance used to define cross-entropy is called the \textit{Kullback-Leibler (KL) distance} or \textit{KL divergence}. The KL distance is also called the \textit{relative entropy}, and we can use this to derive the cross-entropy. Formally, for a random variable $\mat{X} = (X_1, \ldots, X_n)$ with a support of $\mathcal{X}$, the KL distance between two continuous probability density functions $f$ and $g$ is defined to be: \begin{align*} \mathcal{D}(f, g) &= \mathbb{E}_f\left[\log \frac{f(\vec{X})}{g(\vec{X})} \right]\\ &= \int\limits_{\vec{x} \in \mathcal{X}} f(\vec{x}) \log f(\vec{x}) d\vec{x} - \int\limits_{\vec{x} \in \mathcal{X}} f(\vec{x}) \log g(\vec{x}) d\vec{x} \end{align*} We denote the expectation of some function with respect to a distribution $f$ as $\mathbb{E}_f$. Minimizing the KL distance $\mathcal{D}$ between our true distribution $f$ and our proposal distribution $g$ parameterized by $\vec{\theta}$, is equivalent to choosing $\vec\theta$ that minimizes the following, called the \textit{cross-entropy}: \begin{align*} H(f,g) &= H(f) + \mathcal{D}(f,g)\\ &= -\mathbb{E}_f[\log g(\vec{X})] \tag{using KL distance}\\ &= - \int\limits_{\vec{x} \in \mathcal{X}} f(\vec{x}) \log g(\vec{x} \mid \vec{\theta}) d\vec{x} \end{align*} where $H(f)$ denotes the entropy of the distribution $f$ (where we conflate entropy and continuous entropy for convenience). This assumes that $f$ and $g$ share the support $\mathcal{X}$ and are continuous with respect to $\vec{x}$. The minimization problem then becomes: \begin{equation} \label{eq:min} \begin{aligned} \operatornamewithlimits{minimize}_{\vec{\theta}} & & - \int\limits_{\vec{x} \in \mathcal{X}} f(\vec{x}) \log g(\vec{x} \mid \vec{\theta}) d\vec{x} \end{aligned} \end{equation} Efficiently finding this minimum is the goal of the cross-entropy method algorithm. \subsection{Cross-Entropy Method} \label{sec:background_cem} Using the definition of cross-entropy, intuitively the \textit{cross-entropy method} (CEM or CE-method) aims to minimize the cross-entropy between the unknown true distribution $f$ and a proposal distribution $g$ parameterized by $\vec\theta$. This technique reformulates the minimization problem as a probability estimation problem, and uses adaptive importance sampling to estimate the unknown expectation \cite{de2005tutorial}. The cross-entropy method has been applied in the context of both discrete and continuous optimization problems \cite{rubinstein1999cross,kroese2006cross}. The initial goal is to estimate the probability \begin{align*} \ell = P_{\vec{\theta}}(S(\vec{x}) \ge \gamma) \end{align*} where $S$ can the thought of as an objective function of $\vec{x}$, and $\vec{x}$ follows a distribution defined by $g(\vec{x} \mid \vec{\theta})$. We want to find events where our objective function $S$ is above some threshold $\gamma$. We can express this unknown probability as the expectation \begin{align} \label{eq:expect} \ell = \mathbb{E}_{\vec{\theta}}[\mathbbm{1}_{(S(\vec{x}) \ge \gamma)}] \end{align} where $\mathbbm{1}$ denotes the indicator function. A straightforward way to estimate \cref{eq:expect} can be done through Monte Carlo sampling. But for rare-event simulations where the probability of a target event occurring is relatively small, this estimate becomes inadequate. The challenge of the minimization in \cref{eq:min} then becomes choosing the density function for the true distribution $f(\vec{x})$. Importance sampling tells us that the optimal importance sampling density can be reduced to \begin{align*} f^*(\vec{x}) = \frac{\mathbbm{1}_{(S(\vec{x}) \ge \gamma)}g(\vec{x} \mid \vec{\theta})}{\ell} \end{align*} thus resulting in the optimization problem: \begin{align*} \vec{\theta}_g^* &= \operatornamewithlimits{arg\,min}_{\vec{\theta}_g} - \int\limits_{\vec{x} \in \mathcal{X}} f^*(\vec{x})\log g(\vec{x} \mid \vec{\theta}_g) d\vec{x}\\ &= \operatornamewithlimits{arg\,min}_{\vec{\theta}_g} - \int\limits_{\vec{x} \in \mathcal{X}} \frac{\mathbbm{1}_{(S(\vec{x}) \ge \gamma)}g(\vec{x} \mid \vec{\theta})}{\ell}\log g(\vec{x} \mid \vec{\theta}_g) d\vec{x} \end{align*} Note that since we assume $f$ and $g$ belong to the same family of distributions, we get that $f(\vec{x}) = g(\vec{x} \mid \vec{\theta}_g)$. Now notice that $\ell$ is independent of $\vec{\theta}_g$, thus we can drop $\ell$ and get the final optimization problem of: \begin{align} \label{eq:opt} \vec{\theta}_g^* &= \operatornamewithlimits{arg\,min}_{\vec{\theta}_g} - \int\limits_{\vec{x} \in \mathcal{X}} \mathbbm{1}_{(S(\vec{x}) \ge \gamma)}g(\vec{x} \mid \vec{\theta}) \log g(\vec{x} \mid \vec{\theta}_g) d\vec{x}\\\nonumber &= \operatornamewithlimits{arg\,min}_{\vec{\theta}_g} - \mathbb{E}_{\vec{\theta}}[ \mathbbm{1}_{(S(\vec{x}) \ge \gamma)} \log g(\vec{x} \mid \vec{\theta}_g)] \end{align} The CE-method uses a multi-level algorithm to estimate $\vec{\theta}_g^*$ iteratively. The parameter $\vec{\theta}_k$ at iteration $k$ is used to find new parameters $\vec{\theta}_{k^\prime}$ at the next iteration $k^\prime$. The threshold $\gamma_k$ becomes smaller that its initial value, thus artificially making events \textit{less rare} under $\vec{X} \sim g(\vec{x} \mid \vec{\theta}_k)$. In practice, the CE-method algorithm requires the user to specify a number of \textit{elite} samples $m_\text{elite}$ which are used when fitting the new parameters for iteration $k^\prime$. Conveniently, if our distribution $g$ belongs to the \textit{natural exponential family} then the optimal parameters can be found analytically \cite{Kochenderfer2019}. For a multivariate Gaussian distribution parameterized by $\vec{\mu}$ and $\mat{\Sigma}$, the optimal parameters for the next iteration $k^\prime$ correspond to the maximum likelihood estimate (MLE): \begin{align*} \vec{\mu}_{k^\prime} &= \frac{1}{m_\text{elite}} \sum_{i=1}^{m_\text{elite}} \vec{x}_i\\ \vec{\Sigma}_{k^\prime} &= \frac{1}{m_\text{elite}} \sum_{i=1}^{m_\text{elite}} (\vec{x}_i - \vec{\mu}_{k^\prime})(\vec{x}_i - \vec{\mu}_{k^\prime})^\top \end{align*} The cross-entropy method algorithm is shown in \cref{alg:cem}. For an objective function $S$ and input distribution $g$, the CE-method algorithm will run for $k_\text{max}$ iterations. At each iteration, $m$ inputs are sampled from $g$ and evaluated using the objective function $S$. The sampled inputs are denoted by $\mat{X}$ and the evaluated values are denoted by $\mat{Y}$. Next, the top $m_\text{elite}$ samples are stored in the elite set $\mathbf{e}$, and the distribution $g$ is fit to the elites. This process is repeated for $k_\text{max}$ iterations and the resulting parameters $\vec{\theta}_{k_\text{max}}$ are returned. Note that a variety of input distributions for $g$ are supported, but we focus on the multivariate Gaussian distribution and the Gaussian mixture model in this work. \begin{algorithm}[ht] \begin{algorithmic} \Function{CrossEntropyMethod}{}($S, g, m, m_\text{elite}, k_\text{max}$) \For {$k \in [1,\ldots,k_\text{max}]$} \State $\mat{X} \sim g(\;\cdot \mid \vec{\theta}_k)$ where $\mat{X} \in \mathbb{R}^m$ \State $\mat{Y} \leftarrow S(\vec{x})$ for $\vec{x} \in \mat{X}$ \State $\mathbf{e} \leftarrow$ store top $m_\text{elite}$ from $\mat{Y}$ \State $\vec{\theta}_{k^\prime} \leftarrow \textproc{Fit}(g(\;\cdot \mid \vec{\theta}_k), \mathbf{e})$ \EndFor \State \Return $g(\;\cdot \mid \vec{\theta}_{k_\text{max}})$ \EndFunction \end{algorithmic} \caption{\label{alg:cem} Cross-entropy method.} \end{algorithm} \subsection{Mixture Models} A standard Gaussian distribution is \textit{unimodal} and can have trouble generalizing over data that is \textit{multimodal}. A \textit{mixture model} is a weighted mixture of component distributions used to represent continuous multimodal distributions \cite{kochenderfer2015decision}. Formally, a Gaussian mixture model (GMM) is defined by its parameters $\vec{\mu}$ and $\mat{\Sigma}$ and associated weights $\mathbf{w}$ where $\sum_{i=1}^n w_i = 1$. We denote that a random variable $\mat{X}$ is distributed according to a mixture model as $\mat{X} \sim \operatorname{Mixture}(\vec{\mu}, \vec{\Sigma}, \vec{w})$. The probability density of the GMM then becomes: \begin{gather*} P( \mat{X} = \vec{x} \mid \vec{\mu}, \mat{\Sigma}, \vec{w}) = \sum_{i=1}^n w_i \Normal(\vec{x} \mid \vec{\mu}_i, \mat{\Sigma}_i) \end{gather*} To fit the parameters of a Gaussian mixture model, it is well known that the \textit{expectation-maximization (EM)} algorithm can be used \cite{dempster1977maximum,aitkin1980mixture}. The EM algorithm seeks to find the maximum likelihood estimate of the hidden variable $H$ using the observed data defined by $E$. Intuitively, the algorithm alternates between an expectation step (E-step) and a maximization step (M-step) to guarantee convergence to a local minima. A simplified EM algorithm is provide in \cref{alg:em} for reference and we refer to \cite{dempster1977maximum,aitkin1980mixture} for further reading. \begin{algorithm}[ht] \begin{algorithmic} \Function{ExpectationMaximization}{$H, E, \vec{\theta}$} \For{\textbf{E-step}} \State Compute $Q(h) = P(H=h \mid E=e, \vec{\theta})$ for each $h$ \State Create weighted points: $(h,e)$ with weight $Q(h)$ \EndFor \For{\textbf{M-step}} \State Compute $\mathbf{\hat{\vec{\theta}}}_{\text{MLE}}$ \EndFor \State Repeat until convergence. \State \Return $\mathbf{\hat{\vec{\theta}}}_{\text{MLE}}$ \EndFunction \end{algorithmic} \caption{\label{alg:em} Expectation-maximization.} \end{algorithm} \subsection{Surrogate Models} In the context of optimization, a surrogate model $\hat{S}$ is used to estimate the true objective function and provide less expensive evaluations. Surrogate models are a popular approach and have been used to evaluate rare-event probabilities in computationally expensive systems \cite{li2010evaluation,li2011efficient}. The simplest example of a surrogate model is linear regression. In this work, we focus on the \textit{Gaussian process} surrogate model. A Gaussian process (GP) is a distribution over functions that predicts the underlying objective function $S$ and captures the uncertainty of the prediction using a probability distribution \cite{Kochenderfer2019}. This means a GP can be sampled to generate random functions, which can then be fit to our given data $\mat{X}$. A Gaussian process is parameterized by a mean function $\mathbf{m}(\mat{X})$ and kernel function $\mat{K}(\mat{X},\mat{X})$, which captures the relationship between data points as covariance values. We denote a Gaussian process that produces estimates $\hat{\vec{y}}$ as: \begin{align*} \hat{\vec{y}} &\sim\mathcal{N}\left(\vec{m}(\mat{X}),\vec{K}(\mat{X},\mat{X})\right)\\ &= \begin{bmatrix} \hat{S}(\vec{x}_1), \ldots, \hat{S}(\vec{x}_n) \end{bmatrix} \end{align*} where \begin{gather*} \vec{m}(\mat{X}) = \begin{bmatrix} m(\vec{x}_1), \ldots, m(\vec{x}_n) \end{bmatrix}\\ \vec{K}(\mat{X}, \mat{X}) = \begin{bmatrix} k(\vec{x}_1, \vec{x}_1) & \cdots & k(\vec{x}_1, \vec{x}_n)\\ \vdots & \ddots & \vdots\\ k(\vec{x}_n, \vec{x}_1) & \cdots & k(\vec{x}_n, \vec{x}_n) \end{bmatrix} \end{gather*} We use the commonly used zero-mean function $m(\vec{x}_i) = \vec{0}$. For the kernel function $k(\vec{x}_i, \vec{x}_i)$, we use the squared exponential kernel with variance $\sigma^2$ and characteristic scale-length $\ell$, where larger $\ell$ values increase the correlation between successive data points, thus smoothing out the generated functions. The squared exponential kernel is defined as: \begin{align*} k(\vec{x},\vec{x}^\prime) = \sigma^2\exp\left(- \frac{(\vec{x} - \vec{x}^\prime)^\top(\vec{x} - \vec{x}^\prime)}{2\ell^2}\right) \end{align*} We refer to \cite{Kochenderfer2019} for a detailed overview of Gaussian processes and different kernel functions. \section{Algorithms} \label{sec:algorithms} We can now describe the cross-entropy method variants introduced in this work. This section will first cover the main algorithm introduced, the cross-entropy surrogate method (CE-surrogate). Then we introduce a modification to the CE-surrogate method, namely the cross-entropy mixture method (CE-mixture). Lastly, we describe various evaluation schedules for redistributing objective function calls over the iterations. \subsection{Cross-Entropy Surrogate Method} \label{sec:alg_ce_surrogate} The main CE-method variant we introduce is the cross-entropy surrogate method (CE-surrogate). The CE-surrogate method is a superset of the CE-method, where the differences lie in the evaluation scheduling and modeling of the elite set using a surrogate model. The goal of the CE-surrogate algorithm is to address the shortcomings of the CE-method when the number of objective function calls is sparse and the underlying objective function $S$ has multiple local minima. The CE-surrogate algorithm is shown in \cref{alg:ce_surrogate}. It takes as input the objective function $S$, the distribution $\mathbf{M}$ parameterized by $\vec{\theta}$, the number of samples $m$, the number of elite samples $m_\text{elite}$, and the maximum iterations $k_\text{max}$. For each iteration $k$, the number of samples $m$ are redistributed through a call to \smallcaps{EvaluationSchedule}, where $m$ controls the number of true objective function evaluations of $S$. Then, the algorithm samples from $\mathbf{M}$ parameterized by the current $\vec{\theta}_k$ given the adjusted number of samples $m$. For each sample in $\mat{X}$, the objective function $S$ is evaluated and the results are stored in $\mat{Y}$. The top $m_\text{elite}$ evaluations from $\mat{Y}$ are stored in $\mathbf{e}$. Using all of the current function evaluations $\mat{Y}$ from sampled inputs $\mat{X}$, a modeled elite set $\mathbf{E}$ is created to augment the sparse information provided by a low number of true objective function evaluations. Finally, the distribution $\mathbf{M}$ is fit to the elite set $\mathbf{E}$ and the distribution with the final parameters $\vec{\theta}_{k_\text{max}}$ is returned. \begin{algorithm}[ht] \begin{algorithmic} \Function{CE-Surrogate}{$S$, $\mathbf{M}$, $m$, $m_\text{elite}$, $k_\text{max}$} \For {$k \in [1,\ldots,k_\text{max}]$} \State $m, m_\text{elite} \leftarrow \textproc{EvaluationSchedule}(k, k_\text{max})$ \State $\mat{X} \sim \mathbf{M}(\;\cdot \mid \vec{\theta}_k)$ where $\mat{X} \in \mathbb{R}^m$ \State $\mat{Y} \leftarrow S(\vec{x})$ for $\vec{x} \in \mat{X}$ \State $\mathbf{e} \leftarrow$ store top $m_\text{elite}$ from $\mat{Y}$ \State $\mathbf{E} \leftarrow \textproc{ModelEliteSet}(\mat{X}, \mat{Y}, \mathbf{M}, \mathbf{e}, m, m_\text{elite})$ \State $\vec{\theta}_{k^\prime} \leftarrow \textproc{Fit}(\mathbf{M}(\;\cdot \mid \vec{\theta}_k), \mathbf{E})$ \EndFor \State \Return $\mathbf{M}(\;\cdot \mid \vec{\theta}_{k_\text{max}})$ \EndFunction \end{algorithmic} \caption{\label{alg:ce_surrogate} Cross-entropy surrogate method.} \end{algorithm} The main difference between the standard CE-method and the CE-surrogate variant lies in the call to \smallcaps{ModelEliteSet}. The motivation is to use \textit{all} of the already evaluated objective function values $\mat{Y}$ from a set of sampled inputs $\mat{X}$. This way the expensive function evaluations---otherwise discarded---can be used to build a surrogate model of the underlying objective function. First, a surrogate model $\surrogate$ is constructed from the samples $\mat{X}$ and true objective function values $\mat{Y}$. We used a Gaussian process with a specified kernel and optimizer, but other surrogate modeling techniques such as regression with basis functions can be used. We chose a Gaussian process because it incorporates probabilistic uncertainty in the predictions, which may more accurately represent our objective function, or at least be sensitive to over-fitting to sparse data. Now we have an approximated objective function $\surrogate$ that we can inexpensively call. We sample $10m$ values from the distribution $\mathbf{M}$ and evaluate them using the surrogate model. We then store the top $10m_\text{elite}$ values from the estimates $\mathbf{\hat{\mat{Y}}}_\text{m}$. We call these estimated elite values $\mathbf{e}_\text{model}$ the \textit{model-elites}. The surrogate model is then passed to \smallcaps{SubEliteSet}, which returns more estimates for elite values. Finally, the elite set $\mathbf{E}$ is built from the true-elites $\mathbf{e}$, the model-elites $\mathbf{e}_\text{model}$, and the subcomponent-elites $\mathbf{e}_\text{sub}$. The resulting concatenated elite set $\mathbf{E}$ is returned. \begin{algorithm}[ht] \begin{algorithmic} \Function{ModelEliteSet}{$\mat{X}, \mat{Y}, \mathbf{M}, \mathbf{e}, m, m_\text{elite}$} \State $\surrogate \leftarrow \textproc{GaussianProcess}(\mat{X}, \mat{Y}, \text{kernel}, \text{optimizer})$ \State $\mat{X}_\text{m} \sim \mathbf{M}(\;\cdot \mid \vec{\theta}_k)$ where $\mat{X}_\text{m} \in \mathbb{R}^{10m}$ \State $\mathbf{\hat{\mat{Y}}}_\text{m} \leftarrow \surrogate(\vec{x}_\text{m})$ for $\vec{x}_\text{m} \in \mat{X}_\text{m}$ \State $\mathbf{e}_\text{model} \leftarrow$ store top $10m_\text{elite}$ from $\mathbf{\hat{\mat{Y}}}_\text{m}$ \State $\mathbf{e}_\text{sub} \leftarrow \textproc{SubEliteSet}(\surrogate, \mathbf{M}, \mathbf{e})$ \State $\mathbf{E} \leftarrow \{ \mathbf{e} \} \cup \{ \mathbf{e}_\text{model} \} \cup \{ \mathbf{e}_\text{sub} \}$ \algorithmiccomment{elite set} \State \Return $\mathbf{E}$ \EndFunction \end{algorithmic} \caption{\label{alg:model_elite_set} Modeling elite set.} \end{algorithm} To encourage exploration of promising areas of the design space, the algorithm \smallcaps{SubEliteSet} focuses on the already marked true-elites $\mathbf{e}$. Each elite $e_x \in \mathbf{e}$ is used as the mean of a new multivariate Gaussian distribution with covariance inherited from the distribution $\mathbf{M}$. The collection of subcomponent distributions is stored in $\mathbf{m}$. The idea is to use the information given to us by the true-elites to emphasize areas of the design space that look promising. For each distribution $\mathbf{m}_i \in \mathbf{m}$ we run a subroutine call to the standard CE-method to fit the distribution $\mathbf{m}_i$ using the surrogate model $\surrogate$. Then the best objective function value is added to the subcomponent-elite set $\mathbf{e}_\text{sub}$, and after iterating the full set is returned. Note that we use $\theta_\text{CE}$ to denote the parameters for the CE-method algorithm. In our case, we recommend using a small $k_\text{max}$ of around $2$ so the subcomponent-elites do not over-fit to the surrogate model but have enough CE-method iterations to tend towards optimal. \begin{algorithm}[ht] \begin{algorithmic} \Function{SubEliteSet}{$\surrogate, \mathbf{M}, \mathbf{e}$} \State $\mathbf{e}_\text{sub} \leftarrow \emptyset$ \State $\mathbf{m} \leftarrow \{ e_x \in \mathbf{e} \mid \Normal(e_x, \mathbf{M}.\Sigma) \}$ \For {$\mathbf{m}_i \in \mathbf{m}$} \State $\mathbf{m}_i \leftarrow \textproc{CrossEntropyMethod}(\surrogate, \mathbf{m}_i \mid \theta_{\text{CE}})$ \State $\mathbf{e}_\text{sub} \leftarrow \{\mathbf{e}_\text{sub}\} \cup \{\textproc{Best}(\mathbf{m}_i)\}$ \EndFor \State \Return $\mathbf{e}_\text{sub}$ \EndFunction \end{algorithmic} \caption{\label{alg:sub_elite_set} Subcomponent elite set.} \end{algorithm} \subsection{Cross-Entropy Mixture Method} \label{sec:alg_ce_mixture} We refer to the variant of our CE-surrogate method that takes an input \textit{mixture model} $\mathbf{M}$ as the cross-entropy mixture method (CE-mixture). The CE-mixture algorithm is identical to the CE-surrogate algorithm, but calls a custom \smallcaps{Fit} function to fit a mixture model to the elite set $\mathbf{E}$. The input distribution $\mathbf{M}$ is cast to a mixture model using the subcomponent distributions $\mathbf{m}$ as the components of the mixture. We use the default uniform weighting for each mixture component. The mixture model $\mathbf{M}$ is then fit using the expectation-maximization algorithm shown in \cref{alg:em}, and the resulting distribution is returned. The idea is to use the distributions in $\mathbf{m}$ that are centered around each true-elite as the components of the casted mixture model. Therefore, we would expect better performance of the CE-mixture method when the objective function has many competing local minima. Results in \cref{sec:results} aim to show this behavior. \begin{algorithm}[ht] \begin{algorithmic} \Function{Fit}{$\mathbf{M}, \mathbf{m}, \mathbf{E}$} \State $\mathbf{M} \leftarrow \operatorname{Mixture}( \mathbf{m} )$ \State $\mathbf{\hat{\vec{\theta}}} \leftarrow \textproc{ExpectationMaximization}(\mathbf{M}, \mathbf{E})$ \State \Return $\mathbf{M}(\;\cdot \mid \mathbf{\hat{\vec{\theta}}})$ \EndFunction \end{algorithmic} \caption{\label{alg:ce_mixture_fit} Fitting mixture models (used by CE-mixture).} \end{algorithm} \subsection{Evaluation Scheduling} \label{sec:alg_eval_schedule} Given the nature of the CE-method, we expect the covariance to shrink over time, thus resulting in a solution with higher confidence. Yet if each iteration is given the same number of objective function evaluations $m$, there is the potential for elite samples from early iterations dominating the convergence. Therefore, we would like to redistribute the objective function evaluations throughout the iterations to use more truth information early in the process. We call these heuristics \textit{evaluation schedules}. One way to achieve this is to reallocate the evaluations according to a Geometric distribution. Evaluation schedules can also be ad-hoc and manually prescribed based on the current iteration. We provide the evaluation schedule we use that follows a Geometric distribution with parameter $p$ in \cref{alg:evaluation_schedule}. We denote $G \sim \Geo(p)$ to be a random variable that follows a truncated Geometric distribution with the probability mass function $p_G(k) = p(1 - p)^k$ for $k \in \{0, 1, 2, \ldots, k_\text{max}\}$. Note the use of the integer rounding function (e.g., $\round{x}$), which we later have to compensate for towards the final iterations. Results in \cref{sec:results} compare values of $p$ that control the redistribution of evaluations. \begin{algorithm}[ht] \begin{algorithmic} \Function{EvaluationSchedule}{$k, k_\text{max}$} \State $G \sim \Geo(p)$ \State $N_\text{max} \leftarrow k_\text{max} \cdot m$ \State $m \leftarrow \round{N_\text{max} \cdot p_G(k)}$ \If{$k = k_\text{max}$} \State $s \leftarrow \displaystyle\sum_{i=1}^{k_\text{max}-1} \round{N_\text{max} \cdot p_G(i)}$ \State $m \leftarrow \min(N_\text{max} - s, N_\text{max} - m)$ \EndIf \State $m_\text{elite} \leftarrow \min(m_\text{elite}, m)$ \State \Return ($m, m_\text{elite}$) \EndFunction \end{algorithmic} \caption{\label{alg:evaluation_schedule} Evaluation schedule using a Geometric distr.} \end{algorithm} \section{Experiments} \label{sec:experiments} In this section, we detail the experiments we ran to compare the CE-method variants and evaluation schedules. We first introduce a test objective function we created to stress the issue of converging to local minima. We then describe the experimental setup for each of our experiments and provide an analysis and results. \subsection{Test Objective Function Generation} \begin{figure*}[!t] \centering \resizebox{0.8\textwidth}{!}{\input{sierra_group.tex}} \caption{ \label{fig:sierra} Example test objective functions generated using the sierra function. } \end{figure*} To stress the cross-entropy method and its variants, we created a test objective function called \textit{sierra} that is generated from a mixture model comprised of $49$ multivariate Gaussian distributions. We chose this construction so that we can use the negative peeks of the component distributions as local minima and can force a global minimum centered at our desired $\mathbf{\tilde{\vec{\mu}}}$. The construction of the sierra test function can be controlled by parameters that define the spread of the local minima. We first start with the center defined by a mean vector $\mathbf{\tilde{\vec{\mu}}}$ and we use a common covariance $\mathbf{\tilde{\mat{\Sigma}}}$: \begin{align*} \mathbf{\tilde{\vec{\mu}}} &= [\mu_1, \mu_2], \quad \mathbf{\tilde{\mat{\Sigma}}} = \begin{bmatrix}\sigma & 0\\ 0 & \sigma \end{bmatrix} \end{align*} Next, we use the parameter $\delta$ that controls the clustered distance between symmetric points: \begin{align*} \mat{G} &= \left\{[+\delta, +\delta], [+\delta, -\delta], [-\delta, +\delta], [-\delta, -\delta]\right\} \end{align*} We chose points $\mat{P}$ to fan out the clustered minima relative to the center defined by $\mathbf{\tilde{\vec{\mu}}}$: \begin{align*} \mat{P} &= \left\{[0, 0], [1, 1], [2, 0], [3, 1], [0, 2], [1, 3]\right\} \end{align*} The vector $\vec{s}$ is used to control the $\pm$ distance to create an `s' shape comprised of minima, using the standard deviation $\sigma$: $\vec{s} = \begin{bmatrix}+\sigma, -\sigma \end{bmatrix}$. We set the following default parameters: standard deviation $\sigma=3$, spread rate $\eta=6$, and cluster distance $\delta=2$. We can also control if the local minima clusters ``decay'', thus making those local minima less distinct (where $\text{decay} \in \{0, 1\})$. The parameters that define the sierra function are collected into $\vec{\theta} = \langle \mathbf{\tilde{\vec{\mu}}}, \mathbf{\tilde{\mat{\Sigma}}}, \mat{G}, \mat{P}, \vec{s} \rangle$. Using these parameters, we can define the mixture model used by the sierra function as: \begin{gather*} \mathbf{M}_\mathcal{S} \sim \operatorname{Mixture}\left(\left\{ \vec{\theta} ~\Big|~ \Normal\left(\vec{g} + s\vec{p}_i + \mathbf{\tilde{\vec{\mu}}},\; \mathbf{\tilde{\mat{\Sigma}}} \cdot i^{\text{decay}}/\eta \right) \right\} \right)\\ \text{for } (\vec{g}, \vec{p}_i, s) \in (\mat{G}, \mat{P}, \vec{s}) \end{gather*} We add a final component to be our global minimum centered at $\mathbf{\tilde{\vec{\mu}}}$ and with a covariance scaled by $\sigma\eta$. Namely, the global minimum is $\vec{x}^* = \mathbb{E}[\Normal(\mathbf{\tilde{\vec{\mu}}}, \mathbf{\tilde{\mat{\Sigma}}}/(\sigma\eta))] = \mathbf{\tilde{\vec{\mu}}}$. We can now use this constant mixture model with $49$ components and define the sierra objective function $\mathcal{S}(\vec{x})$ to be the negative probability density of the mixture at input $\vec{x}$ with uniform weights: \begin{align*} \mathcal{S}(\vec{x}) &= -P(\mathbf{M}_\mathcal{S} = \vec{x}) = -\frac{1}{|\mathbf{M}_\mathcal{S}|}\sum_{j=1}^{n}\Normal(\vec{x} \mid \vec{\mu}_j, \mat{\Sigma}_j) \end{align*} An example of six different objective functions generated using the sierra function are shown in \cref{fig:sierra}, sweeping over the spread rate $\eta$, with and without decay. \subsection{Experimental Setup} \label{sec:experiment_setup} Experiments were run to stress a variety of behaviors of each CE-method variant. The experiments are split into two categories: algorithmic and scheduling. The algorithmic category aims to compare features of each CE-method variant while holding common parameters constant (for a better comparison). While the scheduling category experiments with evaluation scheduling heuristics. \begin{figure*}[!t] \centering \subfloat[The cross-entropy method.] \resizebox{0.3\textwidth}{!}{\input{k5_ce_method.pgf}} } \subfloat[The cross-entropy surrogate method.] \resizebox{0.3\textwidth}{!}{\input{k5_ce_surrogate.pgf}} } \subfloat[The cross-entropy mixture method.] \resizebox{0.3\textwidth}{!}{\input{k5_ce_mixture.pgf}} } \caption{ \label{fig:k5} Iteration $k=5$ illustrated for each algorithm. The covariance is shown by the contours. } \end{figure*} Because the algorithms are stochastic, we run each experiment with 50 different random number generator seed values. To evaluate the performance of the algorithms in their respective experiments, we define three metrics. First, we define the average ``optimal'' value $\bar{b}_v$ to be the average of the best so-far objective function value (termed ``optimal'' in the context of each algorithm). Again, we emphasize that we average over the 50 seed values to gather meaningful statistics. Another metric we monitor is the average distance to the true global optimal $\bar{b}_d = \norm{\vec{b}_{\vec{x}} - \vec{x}^*}$, where $\vec{b}_{\vec{x}}$ denotes the $\vec{x}$-value associated with the ``optimal''. We make the distinction between these metrics to show both ``closeness'' in \textit{value} to the global minimum and ``closeness'' in the \textit{design space} to the global minimum. Our final metric looks at the average runtime of each algorithm, noting that our goal is to off-load computationally expensive objective function calls to the surrogate model. For all of the experiments, we use a common setting of the following parameters for the sierra test function (shown in the top-right plot in \cref{fig:sierra}): \begin{equation*} (\mathbf{\tilde{\vec{\mu}}} =[0,0],\; \sigma=3,\; \delta=2,\; \eta=6,\; \text{decay} = 1) \end{equation*} \subsubsection{Algorithmic Experiments} \label{sec:alg_experiments} We run three separate algorithmic experiments, each to test a specific feature. For our first algorithmic experiment (1A), we want to test each algorithm when the user-defined mean is centered at the global minimum and the covariance is arbitrarily wide enough to cover the design space. Let $\mathbf{M}$ be a distribution parameterized by $\vec{\theta} = (\vec{\mu}, \mat{\Sigma})$, and for experiment (1A) we set the following: \begin{equation*} \vec\mu^{(\text{1A})} = [0, 0] \qquad \mat\Sigma^{(\text{1A})} = \begin{bmatrix} 200 & 0\\ 0 & 200 \end{bmatrix} \end{equation*} For our second algorithmic experiment (1B), we test a mean that is far off-centered with a wider covariance: \begin{equation*} \vec\mu^{(\text{1B})} = [-50, -50] \qquad \mat\Sigma^{(\text{1B})} = \begin{bmatrix} 2000 & 0\\ 0 & 2000 \end{bmatrix} \end{equation*} This experiment is used to test the ``exploration'' of the CE-method variants introduced in this work. In experiments (1A) and (1B), we set the following common parameters across each CE-method variant: \begin{equation*} (k_\text{max} = 10,\; m=10,\; m_\text{elite}=5)^{(\text{1A,1B})} \end{equation*} This results in $m\cdot k_\text{max} = 100$ objective function evaluations, which we define to be \textit{relatively} low. For our third algorithmic experiment (1C), we want to test how each variant responds to an extremely low number of function evaluations. This sparse experiment sets the common CE-method parameters to: \begin{equation*} (k_\text{max} = 10,\; m=5,\; m_\text{elite}=3)^{(\text{1C})} \end{equation*} This results in $m\cdot k_\text{max} = 50$ objective function evaluations, which we defined to be \textit{extremely} low. We use the same mean and covariance defined for experiment (1A): \begin{equation*} \vec\mu^{(\text{1C})} = [0, 0] \qquad \mat\Sigma^{(\text{1C})} = \begin{bmatrix} 200 & 0\\ 0 & 200 \end{bmatrix} \end{equation*} \subsubsection{Scheduling Experiments} \label{sec:schedule_experiments} In our final experiment (2), we test the evaluation scheduling heuristics which are based on the Geometric distribution. We sweep over the parameter $p$ that determines the Geometric distribution which controls the redistribution of objective function evaluations. In this experiment, we compare the CE-surrogate methods using the same setup as experiment (1B), namely the far off-centered mean. We chose this setup to analyze exploration schemes when given very little information about the true objective function. \subsection{Results and Analysis} \label{sec:results} \begin{figure}[!hb] \resizebox{0.9\columnwidth}{!}{\input{experiment1a.tex}} \caption{ \label{fig:experiment_1a} Average optimal value for experiment (1A) when the initial mean is centered at the global minimum and the covariance sufficiently covers the design space. } \end{figure} \Cref{fig:experiment_1a} shows the average value of the current optimal $\bar{b}_v$ for the three algorithms for experiment (1A). One standard deviation is plotted in the shaded region. Notice that the standard CE-method converges to a local minima before $k_\text{max}$ is reached. Both CE-surrogate method and CE-mixture stay below the standard CE-method curve, highlighting the mitigation of convergence to local minima. Minor differences can be seen between CE-surrogate and CE-mixture, differing slightly towards the tail in favor of CE-surrogate. The average runtime of the algorithms along with the performance metrics are shown together for each experiment in \cref{tab:results}. \begin{table}[!ht] \centering \caption{\label{tab:results} Experimental results.} \begin{tabular}{cllll} \toprule \textbf{Exper.} & \textbf{Algorithm} & \textbf{Runtime} & $\bar{b}_v$ & $\bar{b}_d$\\ \midrule \multirow{3}{*}{1A} & CE-method & \textbf{0.029 $\operatorname{s}$} & $-$0.0134 & 23.48\\ &CE-surrogate & 1.47 $\operatorname{s}$ & \textbf{\boldmath$-$0.0179} & \textbf{12.23}\\ &CE-mixture & 9.17 $\operatorname{s}$ & $-$0.0169 & 16.87\\ \midrule \multirow{3}{*}{1B} & CE-method & \textbf{0.046 $\operatorname{s}$} & $-$0.0032 & 138.87\\ &CE-surrogate & 11.82 $\operatorname{s}$ & \textbf{\boldmath$-$0.0156} & \textbf{18.24}\\ &CE-mixture & 28.10 $\operatorname{s}$ & $-$0.0146 & 33.30\\ \midrule \multirow{3}{*}{1C} & CE-method & \textbf{0.052 $\operatorname{s}$} & $-$0.0065 & 43.14\\ &CE-surrogate & 0.474 $\operatorname{s}$ & \textbf{\boldmath$-$0.0156} & \textbf{17.23}\\ &CE-mixture & 2.57 $\operatorname{s}$ & $-$0.0146 & 22.17\\ \midrule \multirow{3}{*}{2} & CE-surrogate, $\operatorname{Uniform}$ & --- & \textbf{\boldmath$-$0.0193} & \textbf{8.53}\\ &CE-surrogate, $\Geo(0.1)$ & {\color{gray}---} & $-$0.0115 & 25.35\\ &CE-surrogate, $\Geo(0.2)$ & {\color{gray}---} & $-$0.0099 & 27.59\\ &CE-surrogate, $\Geo(0.3)$ & {\color{gray}---} & $-$0.0089 & 30.88\\ \bottomrule & & & \multicolumn{2}{l}{$-\text{0.0220} \approx\vec{x}^*$}\\ \end{tabular} \end{table} An apparent benefit of the standard CE-method is in its simplicity and speed. As shown in \cref{tab:results}, the CE-method is the fastest approach by about 2-3 orders of magnitude compared to CE-surrogate and CE-mixture. The CE-mixture method is notably the slowest approach. Although the runtime is also based on the objective function being tested, recall that we are using the same number of true objective function calls in each algorithm, and the metrics we are concerned with in optimization are to minimize $\bar{b}_v$ and $\bar{b}_d$. We can see that the CE-surrogate method consistently out performs the other methods. Surprisingly, a uniform evaluation schedule performs the best even in the sparse scenario where the initial mean is far away from the global optimal. \begin{figure}[!ht] \resizebox{0.9\columnwidth}{!}{\input{experiment1b.tex}} \caption{ \label{fig:experiment_1b} Average optimal value for experiment (1B) when the initial mean is far from the global minimum with a wide covariance. } \end{figure} When the initial mean of the input distribution is placed far away from the global optimal, the CE-method tends to converge prematurely as shown in \cref{fig:experiment_1b}. This scenario is illustrated in \cref{fig:example_1b}. We can see that both CE-surrogate and CE-mixture perform well in this case. \begin{figure}[!h] \centering \resizebox{0.7\columnwidth}{!}{\input{example1b.pgf}} \caption{ \label{fig:example_1b} First iteration of the scenario in experiment (1B) where the initial distribution is far away form the global optimal. The red dots indicate the true-elites, the black dots with white outlines indicate the ``non-elites'' evaluated from the true objective function, and the white dots with black outlines indicate the samples evaluated using the surrogate model. } \end{figure} \begin{figure}[!ht] \resizebox{0.9\columnwidth}{!}{\input{experiment1c.tex}} \caption{ \label{fig:experiment_1c} Average optimal value for experiment (1C) when we restrict the number of objective function calls. } \end{figure} Given the same centered mean as before, when we restrict the number of objective function calls even further to just 50 we see interesting behavior. Notice that the results of experiment (1C) shown in \cref{fig:experiment_1c} follow a curve closer to the far away mean from experiment (1B) than from the same setup as experiment (1A). Also notice that the CE-surrogate results cap out at iteration 9 due to the evaluation schedule front-loading the objective function calls, thus leaving none for the final iteration (while still maintaining the same total number of evaluations of 50). \section{Conclusion} \label{sec:conclusion} We presented variants of the popular cross-entropy method for optimization of objective functions with multiple local minima. Using a Gaussian processes-based surrogate model, we can use the same number of true objective function evaluations and achieve better performance than the standard CE-method on average. We also explored the use of a Gaussian mixture model to help find global minimum in multimodal objective functions. We introduce a parameterized test objective function with a controllable global minimum and spread of local minima. Using this test function, we showed that the CE-surrogate algorithm achieves the best performance relative to the standard CE-method, each using the same number of true objective function evaluations. \printbibliography \end{document}
{'timestamp': '2020-09-22T02:02:21', 'yymm': '2009', 'arxiv_id': '2009.09043', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09043'}
arxiv
\section{Introduction}\label{sec:introduction}} With today’s ever-increasing ease of access to the internet and information, we have reached a point of information overload. Users often find themselves in a dilemma where they spend more time sorting through the clutter of information rather than absorbing the information itself. Over the last decade, there has been a push towards creating accurate and efficient recommendation systems to help users sort through this clutter and improve the experience of obtaining information. However, with the recent increase in research in Machine Learning and Deep Learning, researchers have been experimenting with using deep learning techniques to provide recommendations rather than relying on traditional recommendation techniques like probabilistic matrix factorization \cite{mnih2008probabilistic} and Naive Bayes classifier \cite{aiguzhinov2010similarity}. The recent emergence of information overload has caused decreased productivity, increased frustration, and an overall more negative user experience \cite{zou2014information}. For example, users now often spend more time trying to find a movie on Netflix to watch rather than actually watching movies \cite{gomez2016netflix}. As with any industry, technology companies ultimately focus on their revenues and profits as key metrics for optimization. Recommendation systems play a significant role in increasing revenues, retaining customers and users, and gaining competitive advantages over competitors \cite{recsys}. By using recommendation systems, companies can encourage users to stay engaged with their application/website/service, which allows the companies to show more advertisements, attract new clients, and retain existing clients \cite{vaidya2017recommender}. From an e-commerce perspective, recommendation systems can entice customers to buy more. Carefully selected recommendations can make customers more satisfied, leading them to buy more items than they previously anticipated. Companies store large amounts of data in databases containing transactional, accounting, inventory, and customer contact information. These data can be analyzed to understand customer purchasing behavior, which allows companies to target customers through product recommendations based on past purchases or activities leading to increased revenue. Companies such as Amazon and Netflix are already using algorithms to give recommendations, and other companies are looking to implement similar recommendation system algorithms. The development of e-commerce solutions pioneered by Amazon not only demonstrated the importance of incorporating web data to meet customers’ shopping needs but also leveraging customer data to enhance sales using machine learning algorithms. In another example, Uber Eats food recommendations are based on many factors that take into account real-time information such as user queries, location, time of day/week and historical information about the user’s purchases, restaurants and delivery partners used \cite{uber}. A large parts supply company (the Company) has gathered a large amount of sales and transactional information and has an extensive product database. However, the Company performed minimal analysis of their databases from the perspective of product recommendations to customers. Furthermore, the Company’s databases are large, containing more than 500,000 stock keeping units (SKUs), 20 million rows of transactional data as well as information related to their 200,000 customers. The two primary databases are Invoiced Orders (Invoicedorders.csv) and Current Items (ITEMCURRENT.csv). The \say{Invoiced Orders} database contains the customers’ transaction data. The \say{Current Items} database contains detailed information about the products offered by the Company. The Company wants to use the available data to provide a list of 12 products the customers may be interested in purchasing and to improve the user experience of the Company's website. Collaborative Filtering (CF) was used to solve this problem, it relies on the intuitive idea that similar users tend to like different items similarly. CF methods use an a-priori available set of user-item ratings to learn the interdependencies among users and items, and then predict a user’s rating of an item either via the neighboring items’ ratings (neighbor-based \cite{das2007google}, \cite{sarwar2001item} ) or by inferring latent factors that find similar users and items in a low-dimensional embedding (latent factor-based \cite{hu2008collaborative}, \cite{he2017neural}, \cite{rendle2009bpr}, \cite{moussawi2018towards} ). The feedback can be explicit, i.e., the user either likes an item or dislikes an item. For example, the user either clicks “thumbs up” or “thumbs down” on a youtube video or rates a movie on a scale of one to five stars. Alternatively, the feedback can be implicit, i.e., the feedback derived from the browsing behavior of the user e.g., the user clicked on/purchased a product, checked into a venue, or viewed an article. The objective of this paper is to build a recommendation system for the Company’s online customers using machine learning techniques, which will allow the Company to predict their customers’ needs better and provide product recommendations tailored to the customers’ purchasing behaviors. The contributions associated with this work are listed below: \begin{itemize \item The evaluation and testing of the hypothesis that Collaborative Filtering with latent variable models can capture the historical, transactional and sparse customer purchasing behaviors to provide personalized product recommendations. This paper work continues related efforts in \cite{hu2008collaborative}, \cite{he2017neural}, \cite{rendle2009bpr}, \cite{moussawi2018towards} to understand the hidden factors in customers’ purchasing behaviors. \item The construction and evaluation of ranking metrics for four different models based on Matrix Factorization using Alternative Least Squares, Bayesian Personalized Ranking, Neural Collaborative Filtering and Autoencdoer Collaborative Filtering. \end{itemize} \section{Related Work} A recommendation system, often also called a \say{recommender system}, is used to estimate user preferences of items or objects they have not seen yet. Recommendation systems commonly use inputs such as user preferences, item/object features, histories of users-items’ past interactions, temporal data, and spatial data. Generally, there are three types of recommendation systems: Collaborative Filtering systems \cite{ekstrand2011collaborative}, \cite{zhao2010user}, \cite{sarwar2001item} , Content-Based Recommendation systems \cite{zenebe2009representation}, \cite{lops2011content}, and Hybrid systems\cite{burke2002hybrid}, \cite{burke2007hybrid}. Latent-factor or matrix factorization (MF) methods are popular in recommendation systems \cite{koren2009matrix} both for implicit \cite{rendle2009bpr},\cite{hu2008collaborative} and explicit feedback \cite{mnih2008probabilistic}. The latent factor model tries to predict the users' rating on an item by optimizing an objective function and by reconstructing the rating matrix into low-rank dimensional latent factors. Bayesian Personalized Ranking (BPR) \cite{rendle2009bpr} has emerged as one of the best Top-K recommendation models for implicit data. Popular deep learning-based recommendation techniques that utilize multi-layer perceptrons are Neural Collaborative Filtering (NCF) \cite{he2017neural} and deep factorization machine \cite{guo2017deepfm}. In MLP techniques, recommendations are considered as two-way interactions between users’ preferences and the features of an item/object. NCF uses the binary cross-entropy loss function for implicit feedback and the weighted square loss for explicit feedback. Further extension of the work using pairwise ranking loss are proposed by the authors in \cite{niu2018neural}, \cite{song2018neural} to improve the results. The NCF model is extended to cross-domain recommendations like \cite{lian2017cccfnet}, \cite{wang2016collaborative}. DeepFM \cite{guo2017deepfm} is an end-to-end model, able to integrate factorization machine and MLP to find lower and higher-order feature representation. DeepFM is similar to the wide and deep model, a two network deep learning architecture gives recommendations \cite{cheng2016wide}; however, it does not require sophisticated feature engineering. The authors in \cite{lian2018xdeepfm} proposed eXtreme deep factorization machine, which models implicit and explicit features together to improve the performance over DeepFM. Covington et al. proposed an MLP based YouTube recommendation model \cite{covington2016deep}, and the predictor generates a top-n list of videos based on the nearest neighbor scores from the several hundred videos. The authors in \cite{alashkar2017examples} explored and applied MLP in makeup recommendations. This work uses two identical MLPs to model labeled examples and expert rules, respectively, which provides highly precise recommendations. Autoencoders are also widely used in building recommendation systems. There are two general techniques for using autoencoders as recommendation systems. First, the autoencoder can be used to learn a lower-dimensional feature representation at the bottleneck layer, which means the employement of autoencoder as a dimensionality reduction tool, which is used sequentially with other deep learning techniques for recommendations \cite{zhang2019deep}. On the other hand, one can use autoencoders to fill in the blank values of the rating matrix directly in the reconstruction or decoder layer \cite{zhang2019deep}. Nearly all of the autoencoder alternatives, such as denoising autoencoder, variational autoencoder, contactive autoencoder, and marginalized autoencoder, can be employed to the recommendation task \cite{zhang2019deep}. The AutoRec \cite{sedhain2015autorec} system is a specific implementation of the technique to use the autoencoder as a generative tool for recommendations. The Collaborative Filtering Neural Network \cite{strub2015collaborative}, \cite{strub2016hybrid} is an extension of the AutoRec System. It uses denoising techniques to make the recommendation system more robust. It additionally uses side information (user profile information / item descriptions) to reduce data sparsity issues and the cold start problem, which in return, increases the training speed and robustness, and improves the prediction accuracy. Unlike other autoencoders, which are designed to output rating predictions, Collaborative Denoising Autoencoders (CDAE) models \cite{wu2016collaborative} are used to output ranking predictions and are prone to overfitting, because CDAE provides multiple predictions at once; for example, “What are the top 10 best movies for User A”. The authors in \cite{liang2018variational} proposed a modification of the variational autoencoder called Multi-VAE and Multi-DAE for recommendation tasks using implicit data. The proposed alternative showed better performance than CDAE. Matrix Factorization with Alternating Least Square (ALS) \cite{hu2008collaborative}, Bayesian Personalized Ranking (BPR) \cite{rendle2009bpr}, Neural Collaborative Filtering (NCF) \cite{he2017neural} and Autoencoder for Collaborative Filtering (ACF) \cite{moussawi2018towards} are the four different latent variable methods that were selected to analyze large customer purchasing behavior patterns because of the implicit feedback between customers and products. These modelling approaches were selected to examine different aspects of providing product recommendations. \section{Methodology} The specific details of the dataset cannot be directly summarized in this paper since the data are proprietary. The two primary databases are Invoiced Orders (Invoiced\_orders.csv) and Current Items (ITEM\_CURRENT.csv). The \say{Invoiced Orders} database contains 20 million historical transactional data from August 2016 to June 2019. It has more than 100 fields such as geographic location, selling location, regional order number, rebate value, stock quantity, etc. The \say{Current Items} database contains 500,000 unique products and has detailed information about the items offered by the Company, including dimensions, quantity, English, and French text descriptions, etc. The focus of the analysis was to recommend products/items based on past transaction history; therefore, most of the information is filtered out like location, manufacturer, order\_date, etc. The dataset is filtered using a structured query language (SQL) query where the final dataset has the following information: customer ID, product ID, English and French descriptions of the products, and the number of times a customer purchased a product (ratings). \subsection{Matrix Factorization with Alternating Least Squares (ALS)} Latent-factor or Matrix Factorization (MF) \cite{hu2008collaborative} methods are popular in recommendation systems, MF algorithms work by decomposing the user-item interaction matrix into the product of two lower dimensionality rectangular matrices. The latent factors (lower dimensions) otherwise called features, can be found using Singular Value Decomposition (SVD). Let $M$ and $N$ denote the number of users and items, repectively and $k$ denotes the dimensions of latent space. Let $p \in \mathbb{R}^{k \times M} $ be the latent factor matrix for the users, where the $u^{th}$ column $p_u \in \mathbb{R}^k$ is the latent factor for user $u$. Similarly, let $q \in \mathbb{R}^{k \times N} $ be the latent factor for the items, where the $i^{th}$ column $q_i \in \mathbb{R}^k$ is the latent factor for item $i$. The ratings ($\hat{r}_{u, i}$) for user $u$ and item $i$ are given by $\hat{r}_{u, i} = q_i^T p_u$. For implicit rating, the MF can be formulated \cite{hu2008collaborative} as \begin{equation} min \sum c_{(u, i)} ( p_{(u, i)} - q_i^T p_u)^2 + \lambda ( (\|q_i\| )^2 + (\|p_u\| )^2 ) \end{equation} where $c_{(u,i)} = 1 + \alpha r_{(u, i)}$ and $p_{(u, i)} = 1$ if $r_{(u, i)}>0$ and $p_{(u, i)} = 0$ if $r_{(u, i)} = 0$. $r_{(u, i)}$ is a numerical representation of users' preferences (e.g., number of purchases, number of clicks etc.) and $\lambda$ is a regularization parameter. Owing to the term of $q_i^T p_u$, the loss function is non-convex. The gradient descent method can be applied, but this will incur expensive computations. An Alternating Least Square (ALS) algorithm was therefore developed to overcome this issue \cite{hastie2015matrix}. The basic idea of ALS is to learn one of $q$ or $p$ at the time of optimization while keeping the other as constant. ALS makes the objective at each iteration convex and solvable. The alternating between $q$ and $p$ stops when the convergence is optimal. It is worth noting that the ALS iterative computation can be parallelized and/or distributed, which makes the algorithm desirable \cite{yu2014parallel} for use cases where the dataset is large and thus the user-item rating matrix is highly sparse (as typical in recommendation system scenarios). \subsection{Bayesian Personalized Ranking (BPR)} BPR \cite{rendle2009bpr} has emerged as one of the best Top-K recommendation models for implicit data. BPR is also a strong baseline, which makes it difficult to beat. BPR falls under the category of one-class collaborative filtering (for example 0 or 1) and pairwise comparison. It considers the recommendation task as a ranking problem and assumes that the user prefers items that they have already observed/interacted with, rather than unobserved/not interacted with items. To learn the relative ranking of items for each user, BPR needs to model negative feedback. BPR uses the pairwise interpretation of positive-only feedback by creating triplets (user, observed item, unobserved item). The positive-only feedback is then transformed into positive and negative feedback in pairs of item $(i,j)$. $D_s$ represents triplets $(u,i,j)$ such that a user $u$ prefers item $i$ over item $j$. The triplets ($D_s$) are sampled \cite{rendle2009bpr} from \begin{equation} D_s := (u,i,j)|i \in I_u^+ \land j \in I\backslash I_u^+ \end{equation} where we let $U$ be the set of all users and $I$ the set of all items, with implicit feedback $S$ defined as $ S \subseteq U \times I$; $I_u^+$ is defined as the items $I_u^+ := { i \in I : (u , i) \in S } $ where user $u$ gives positive feedback; $i$ is a positive item taken from $I_u^+$ and $j$ is a negative item randomly sampled from unobserved/not interacted with items. The author derives an optimization criterion called BPR-OPT \cite{rendle2009bpr}, which is an optimization framework. To provide a personalized ranking of items or recommendations, we need to train a separate model using BPR-OPT. Compared to standard MF or kNN methods, BPR ensures not only the rating predictions but also optimizes the item rankings. \subsection{Neural Collaborative Filtering (NCF)} \begin{figure} \centering \includegraphics[width=0.49\textwidth]{Images/chap3/ncf.png} \caption{Neural Collaborative Filtering model architecture} \label{fig:ncf} \end{figure} NCF \cite{he2017neural} is a new neural matrix factorization model that combines both Generalized Matrix Factorization (GMF) and Multi-Layer Perceptron (MLP) to combine the strengths of the linearity and non-linearity given by MF and MLP, respectively, for modeling user-item latent features. The input layer consists of latent vectors of items and users. Figure \ref{fig:ncf} shows the architecture of NCF. The User (u) and Item (i) are used to create low-dimensional embeddings for the user and item. Generalized Matrix Factorization (GMF) combines the two embeddings using the dot product. Multi-layer perceptron (MLP) also produces embeddings for the user and items. However, instead of taking a dot product to obtain the rating, the embeddings are concatenated to create a feature vector that can be passed on to the further layers. The outputs from the final layers of the MLP and GMF are concatenated, called a NeuMF layer to obtain the prediction score. The final layer output of GMF ($\hat{r}_{u,i}$) can be formulated as follows: \begin{equation} \hat{r}_{u,i} = a_{out} ( h^T (q_i \odot p_u ) ) \end{equation} where we let the user latent vector $p_u$ be $P^T v_u^U$ and item latent vector $q_i$ be $Q^T v_i^I$, where $ \odot $ is an element-wise product of vector terms. Additionally, $a_{out}$ and $h$ represent the activation function and weights of the output layer, respectively. The MLP model under the NCF framework is defined as follows. In the input layer, we concatenate the user latent vector $p_u$ and item latent vector $q_i$ as follows: \begin{equation} z_1 = \phi_1 (p_u, q_i) = \begin{bmatrix} p_u \\ q_i\end{bmatrix} \end{equation} where $z_1$ represents the concatenation of $p_u$ and $q_i$ at the input layer. The hidden layers are formulated as: \begin{equation} \phi_l(z_l) = a_{out} (W_l^T z_l + b_l) , (l = 2, 3, ..., L-1) \end{equation} where $W_l$, $b_l$, and $a_{out}$ denote the weight matrix, bias vector, and activation function for the $l$-th layer's perceptron, respectively and the output layer is formulated as: \begin{equation} \hat{r}_{u,i} = \sigma ( h^T \phi(z_{L-1})) \end{equation} where $\hat{r}_{u,i}$ is the predicted rating, $h$ denotes the edge weights and the activation function (sigmoid) of the output layer is defined as $\sigma (x) = \frac{1}{1 + \mathrm{e}^{-x} }$ to restrict the predicted score to be in (0,1). To have more flexibility in the fused model, we use GMF and MLP to learn the embeddings separately and then combine these two models by concatenating their last hidden layer \cite{he2017neural}. We get $\phi^{GMF}$ from GMF and obtain $\phi^{MLP}$ from MLP: \begin{equation} \phi^{GMF}_{u, i} = p^{GMF}_u \odot q^{GMF}_i \end{equation} \begin{equation} \phi^{MLP}_{u,i} = a_{out} \big( W_L^T \big( a_{out} \big( .. a_{out} \big( W_2^T \begin{bmatrix} p_u^{MLP} \\ q_i^{MLP}\end{bmatrix} + b_2 \big) ..\big) \big) + b_L \big) \end{equation} Lastly, we fuse the output from GMF and MLP: \begin{equation} \hat{r}_{u,i} = \sigma \bigg( h^T \begin{bmatrix} \phi^{GMF} \\ \phi^{MLP}\end{bmatrix} \bigg) \end{equation} where $\hat{r}_{u,i}$, $\sigma$, $h$, $\phi^{GMF}$ and $\phi^{MLP}$ denote the predicted ratings, sigmoid activation function, edge weights of the output layer, last hidden layer of GMF and last hidden layer of MLP, respectively. By taking a negative log likelihood, we obtain the objective function to minimize for the NCF method: \begin{equation} L = - \sum_{ (u,i) \in \mathbb{O} \cup \mathbb{O}^{-}} r_{u,i} log \hat{r}_{u,i} + ( 1 - r_{u,i} ) log ( 1 - \hat{r}_{u,i} ) \end{equation} where $\mathbb{O}$ denotes the set of observed interactions, $\mathbb{O}^{-}$ denotes the set of negative instances (unobserved interactions), $r_{u,i}$ denotes the actual ratings and $\hat{r}_{u,i}$ denotes the predicted ratings. \subsection{Autoencoder for Collaborative Filtering (ACF)} Recently, there has been a significant focus in research on using autoencoders for recommendation systems \cite{sedhain2015autorec}, \cite{strub2015collaborative}. Many different techniques have been proposed, such as denoising architecture \cite{wu2016collaborative}, dropout to increase efficiency, etc. Here, we use a particular type of autoencoder (ACF) \cite{moussawi2018towards} whose model is described in this section. Consider the user-item interaction matrix is represented as $ X \in \{0,1 \}^{|U| \times |I|} $ where $U$ and $I$ are the set of users and items, respectively. If there is an interaction between user $u$ and item $i$ then $X_{u,i} = 1$; otherwise, $X_{u,i} = 0$. Given user $u$ and item $i$, $I_u$ represents a set of items, $u$ has interacted with, and $U_i$ represents a set of users who have interacted with $i$. The autoencoder learns a model $p(x_u | z_u , \theta) = h(g_\theta(z_u))$, where $x_u$ is the user $u$ vector of interactions, $z_u$ represents the user latent factor, $g_\theta$ is an autoencoder parameterized by $\theta$ and $h$ is an activation function that maps the output of $g_\theta$ to probabilities based on the logistic likelihood distribution used to model $p(x_u | z_u , \theta)$. $z_u$ can be computed as a function of $f_\lambda(x_u)$, where $f_\lambda$ is an autoencoder parameterized by $\lambda$. The negative log-likelihood loss function of our model to be minimized is then: \begin{eqnarray} - \sum_i \log p(x_u | z_u, \theta)_i = - x_u \cdot \log (g_\theta ( z_u)) \nonumber\\ - ( 1 - x_u) \cdot \log (1 - g_\theta ( z_u)) \end{eqnarray} For regularization, dropouts are applied at the input layers, and also applied L2 weight decay on $\theta$ and $\lambda$. \section{Evaluation and Model Specifications} \subsection{Evaluation Protocols} To evaluate the efficiency of a product recommendation, we followed the leave-one-out evaluation \cite{he2017neural}, which has been widely used in the literature \cite{bayer2017generic}, \cite{he2016fast}, \cite{rendle2012bpr}. In leave-one-out evaluation, for each user, we keep their latest interaction with the item as a test set, and we use the remaining as a training set for the model. During evaluation, it is too tedious and time-consuming to rank all the items for each user. To overcome this problem, we adopted a common strategy used by the practitioners where we sample 100 random items that are not interacted with by the user as a test set and then rank those 100 items with respect to that user. Leave-one-out evaluation with negative sampling is implemented in this work. The efficiency of the ranked list is measured by a widely used metric in the learning-to-rank problem called Normalized Discounted Cumulative Gain (NDCG) \cite{yilmaz2008simple}. NDCG gives more weight to relevant predictions at the starting of the ranked list of items and discounts relevant predictions that occur farther from the beginning of the ranked list. One-product Hit Ratio is a metric we devised, which is relevant for the business. One-product Hit Ratio intuitively measures whether the test item is present on the ranked list. For example, if the test item present on the ranked list, then the score is 1; otherwise 0. \subsection{Model Specifications} The model specifications include the model training procedures and selection of hyperparameters for the Collaborative Filtering models. These models are prepared using Tensorflow \cite{abadi2016tensorflow} and PyTorch \cite{paszke2017automatic} frameworks with the Python programming language. These models are trained on a server with 32 cores of CPU and 256 GB of RAM. The dataset is split into a train, validation and a test set using a customized function, where the split is stratified so that the same set of customers and products will appear in all train, validation and test sets. Hyperparameter tuning is an essential part in machine learning; grid search, random search and bayesian optimization are the three standard methods for hyperparameter tuning. The Bayesian Optimization approach has been proven to outperform other state-of-the-art hyperparameter tuning approaches \cite{snoek2012practical}. Bayesian approach uses past choices made to make a smart choice of hyperparameters for the next set of values to evaluate, through which it reduces the cost of searching for parameters. In this paper, we use Bayesian Optimization for hyperparameter tuning. For the ALS methodology, we closely followed the implementation of \cite{hu2008collaborative} as mentioned in Section 3.1. We find that training the model in this fashion takes more time, so we experimented with different optimizers and used the Adam optimizer \cite{kingma2014adam} to reduce the training time. To make the training even faster, we converted the python code to Cython \cite{behnel2011cython}, where Cython converts the python code to C code to boost performance. We used Tensorflow's embedding layer to create user-item latent vectors. We used Bayesian Optimization to find the optimal hyperparameters. Table \ref{tab:MF_ALS} displays the hyperparameters of the ALS model. The hyperparameters include user-item latent dimensions, regularization, iterations and scaling factors. We find that the user-item latent dimensions have the most significant impact on performance. To create latent dimension vectors, we used embedding layers whose values were uniform and randomly initialized, and then the values were learned during the model training process. L2 regularization was used. The scaling factor was set to 15. During hyperparameter tuning, the number of iterations was found to be optimal at 50. \begin{comment} \begin{figure*}[!t] \centering \subfloat[Case I]{\includegraphics[width=2.5in]{Images/chap4/ALS_TL_k_200_reg_le4.png} \label{fig_first_case}} \hfil \subfloat[Case II]{\includegraphics[width=2.5in]{Images/chap4/BPR_TL_k_200_reg_le4.png} \label{fig_second_case}} \caption{Simulation results for the network.} \label{fig_sim} \end{figure*} \begin{figure}[!t] \centering \includegraphics[width=2.5in]{Images/chap4/ALS_TL_k_200_reg_le4.png} \caption{MF-ALS Training Loss Graph} \label{fig_sim} \end{figure} \end{comment} \begin{table}[ht] \caption{Hyperparameters for MF with ALS models} \begin{center} \begin{tabular}{ |c|c|c|c| } \hline \textbf{Hyperparameter} & \textbf{Value} \\ \hline user-item Latent Dimension (k) & 200 \\ Regularization & 0.0001 \\ Learning Rate & 0.01 \\ Iterations (Epochs) & 30 \\ Batch Size & 512 \\ Scaling Factor ($\alpha$) & 15 \\ \hline \end{tabular} \end{center} \label{tab:MF_ALS} \end{table} In MF with the ALS method described above, we focused on pointwise loss minimization, which captured the positive or negative user-item interactions separately. However, there may be some hidden information available in the negative user-item interactions for positive user-item interactions. The idea was formulated into pairwise loss minimization by \cite{rendle2009bpr}. We train the triplets using the pairwise loss function, as discussed in Section 3.5. The BPR latent factors are constructed using TensorFlow’s embedding layer, and we find that BPR has the same training characteristics as MF with the ALS method. However, BPR takes more iterations or epochs to converge to local minima. This problem arises because of the pairwise loss function, which needs to compute more gradients during the training procedure. The hyperparameter for this methodology consists of user-item latent dimensions (factors), the number of epochs, the learning rate for the optimizer, and regularization to prevent overfitting. By using Bayesian Optimization, we find the best hyperparameters for the BPR approach. Table \ref{tab:BPR} displays the hyperparameters of the BPR model. \begin{table}[ht] \caption{Hyperparameters for BPR model} \begin{center} \begin{tabular}{ |c|c|c|c| } \hline \textbf{Hyperparameter} & \textbf{Value} \\ \hline user-item Latent Dimension (k) & 200 \\ Learning Rate & 0.01 \\ Regularization & 0.0001 \\ Iterations (Epochs) & 200 \\ Batch Size & 512\\ \hline \end{tabular} \end{center} \label{tab:BPR} \end{table} In ALS and BPR methods, we tried to find the linear relationships that exist between the user and the item. However, in NCF, we try to find both linear and non-linear relationships in user-item interactions by utilizing the power of neural networks. As discussed in Section 3.3, we create GMF, MLP, and Fusion of GMF \& MLP (NeuMF) models. The goal of the NCF model is to train and minimize the binary cross-entropy loss function as defined in equation (10). The hyperparameters for the NCF methodology consist of n\_factors, layer\_size, n\_epochs, learning\_rate, and batch\_size, where n\_factors represents the dimensions of the latent space; layer\_size represents the sizes of the input and hidden layers of the MLP; n\_epochs is the number of iterations to run the training. In general, we find that increasing n\_factors increases the quality of predictions. The user/item labels are mapped to real-valued latent vectors with Tensorflow's embedding layers. Table \ref{tab:NCF} describes the optimal hyperparameters for the NCF models using Bayesian Optimization. We found that, in training a NeuMF model, using pre-trained model weights of GMF and MLP is far better in reducing cross-entropy loss than using gaussian normal sampled initialized weights. \begin{table}[ht] \caption{Hyperparameters for NCF model} \begin{center} \begin{tabular}{ |c|c|c|c| } \hline \textbf{Hyperparameter} & \textbf{Value} \\ \hline n\_factors & 16 \\ layer\_size & [64,32,16] \\ n\_epochs & 50 \\ learning\_rate & 0.001 \\ batch\_size & 256 \\ \hline \end{tabular} \end{center} \label{tab:NCF} \end{table} The ACF approach is entirely different from previous approaches. Here, we use the Autoencoder both as a tool for dimensionality reduction as well as a learning algorithm to discover the hidden user-item latent features in the dataset. We use the PyTorch framework to build the ACF model. The objective of the ACF model is to minimize the loss function which was defined in equation (11). Typically, an Autoencoder has two parts: an encoder and a decoder. PyTorch’s nn.embedding layers are used to build the encoder, whereas the same nn.embedding layers are used to build the decoder, but we reverse the encoder’s architecture. User/item labels are mapped to the latent space using an encoder. As the name suggests, the decoder is used to decode the encoder to get the original user/item labels from the latent space. Instead of randomly assigning weights to the embedding layer, Xavier’s initialization is used. An Adam optimizer, as well as the ReLU activation function, are used throughout the process. The hyperparameter for the ACF model consists of hidden\_layer, noise\_prob (dropout probability at the input layer), dropout\_prob (dropout probability at the bottleneck layer), lr (learning rate), weight\_decay, batch\_size, and num\_epochs. Like ALS, BPR and NCF methodologies, we use Bayesian Optimization to find the best hyperparameters. Table \ref{tab:ACF} shows the hyperparameters for the ACF model. \begin{table}[ht] \caption{Hyperparameters for ACF model} \begin{center} \begin{tabular}{ |c|c|c|c| } \hline \textbf{Hyperparameter} & \textbf{Value} \\ \hline hidden\_layer & 7 \\ noise\_prob & 0.3 \\ dropout\_prob & 0.2 \\ lr (learning rate) & 0.001 \\ weight\_decay & 2e-5 \\ batch\_size & 256 \\ num\_epochs & 30 \\ \hline \end{tabular} \end{center} \label{tab:ACF} \end{table} \section{Results and Discussion} \subsection{Results} The average performance of the CF model predictions for the test set using leave-one-out evaluation are displayed in Table \ref{tab:Results}. The NDCG metric was used to calculate the performance of the model, according to the business objective, we choose twelve products to recommend; hence, we used NDCG@12. NDCG@12 gives us the twelve most relevant ranked products based on customer purchasing behavior. The results in the Table \ref{tab:Results} demonstrate that the NCF model achieved the best average performance for NDCG@12 over the leave-one-out evaluation test interval. One-Product Hit Ratio is 1 for ALS, BPR, NCF, and ACF; which means the algorithms at least predict one product that the customer intend to buy. \begin{table}[ht] \caption{CF average performance metrics} \begin{center} \begin{tabular}{ |c|c|c|c| } \hline \textbf{Average Predictions} & \textbf{NDCG@12} & \textbf{One-Product Hit Ratio} \\ \hline ALS & 0.577 $\pm$ 0.055 & 1 \\ \hline BPR & 0.636 $\pm$ 0.048 & 1\\ \hline NCF & 0.724 $\pm$ 0.049 & 1\\ \hline ACF & 0.604 $\pm$ 0.069 & 1\\ \hline \end{tabular} \end{center} \label{tab:Results} \end{table} We consider ALS as the baseline since it tries to find the most direct relationship between the user and item using the matrix factorization technique. From the results in the Table \ref{tab:Results}, the performance of ALS is good over the test period. BPR performed better than ALS, which was expected, because it also implemented matrix factorization with the same user/item latent factors to discover the hidden features in the dataset. BPR varies from ALS in that we implemented pairwise training between positive and negative interactions, which was described in Section 3.2. NCF performed better than all other models, which was expected since it combines the linearity and non-linearity of matrix factorization and neural networks, respectively, which allows NCF to find more relevant hidden features over the dataset. The ACF performed better than ALS but not better than BPR and NCF, which is not always the case. The efficiency of an autoencoder depends on the data; it learns to capture as much information as possible rather than relevant information \cite{ghasemi2018neural}. This means that if we have less user-item interactions, the autoencoder may lose this information. \subsection{Discussion} For the specific dataset investigated in this paper, CF with NCF produced the best test performance. MF with ALS is considered as a baseline in this paper since it focused on direct linear relationships between a user and an item. From the results shown in Table 5.1, we can see that all the models performed relatively well compared with the baseline model. NCF has a significant 14.7\% increase in NDCG over the baseline and BPR has a 5.9\% increase in NDCG. Compared with BPR and NCF, ACF performance is relatively less, with a 2.7\% increase in NDCG over the baseline. The BPR matrix factorization model achieved better NDCG performance than the MF with the ALS model (the baseline), which indicates that the pairwise training in BPR was effective in exploring the parameter space as opposed to the pointwise training used in ALS, leading to the improved performance of NDCG, though both BPR and ALS used matrix factorization with the same user/item latent factor vector dimensions. The ACF did not perform as well as the BPR approach in terms of NDCG metrics. The huge sparsity in the dataset investigated likely limited the usefulness of the autoencoder-based deep learning approaches. As discussed before, the autoencoder captures more irrelevant information as opposed to relevant information; since the dataset is sparse in nature, it is likely to capture non-relevant information on the user-item interactions. Although the autoencoder can be used as a dimensionality reduction tool, the sparsity issue does not allow us to use the autoencoder to its full potential. The NCF model combines matrix factorization and neural networks at the final layer, which allows the model to create a more effective and useful hidden representation of the sparse dataset that allows the model to perform better than other models. \begin{figure} \centering \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/BPR_k_500_lr_01_reg_01.png} \caption{k = 500} \label{fig:BPR500} \end{subfigure} \hfill \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/BPR_k_200_lr_01_reg_01.png} \caption{k = 200} \label{fig:BPR200} \end{subfigure} \caption{BPR Training Loss Graph} \label{fig:BPRK} \end{figure} Since the factors determined by the models are hidden, it is difficult to understand which factors of the user/item interaction are driving the results. We know that the hyperparameters of the model greatly affect performance. For the BPR model, the major hyperparameters that drive the results are user-item latent dimensional factors (k) and regularization. From Figure \ref{fig:BPR500}, we can see that for higher k values, the loss is relatively higher in the first few epochs compared with lower k values (Figure \ref{fig:BPR200}) by keeping other hyperparameters the same. Also, the model takes a significantly higher time to train when the k value is large. Another important hyperparameter is regularization; this is a technique used for tuning the loss function by adding an additional penalty term. From Figure \ref{fig:BPRKR1}, we can see that the pairwise loss is starting around 0.90 for a regularization value of 0.001. From Figure \ref{fig:BPRKR2}, it can be seen that the pairwise loss starts at 0.68 for a regularization value of 0.0001. Therefore, it is apparent that regularization is a driving factor in reducing the loss. \begin{figure} \centering \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/BPR_k_200_reg_001.png} \caption{k = 200, reg = 0.001} \label{fig:BPRKR1} \end{subfigure} \hfill \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/BPR_k_200_reg_0001.png} \caption{k = 200, reg = 0.0001} \label{fig:BPRKR2} \end{subfigure} \caption{BPR Training Loss Graph} \label{fig:BPRKR} \end{figure} For the NCF model, pre-training GMF and MLP was also an essential hyperparameter in reducing the loss function and achieving better NDCG performance. As described in Section 3.3, the NCF model was constructed by concatenating the last hidden layer of GMF and MLP to learn the hidden features of user-item interactions. The concatenated layer is called the NeuMF layer. The training loss for the GMF and MLP are shown in Figure \ref{fig:GMF} and \ref{fig:MLP}. From Figure \ref{fig:GMF}, we can see that the binary cross-entropy loss for GMF starts at approximately 0.50 and drops down to 0.10 and from Figure \ref{fig:MLP}, it can be seen that the binary cross-entropy loss for MLP begins around at 0.35 and ends at 0.07. We trained the NCF model without pre-training weights and observed the training loss. From Figure \ref{fig:WPT}, we can see that the binary cross-entropy loss is very high, which starts at approximately 0.35. \cite{he2017neural} argued that the pre-trained weights reduced the training loss; we trained the GMF and MLP model separately with an Adam optimizer. The trained GMF and MLP model weights are used to train the NeuMF layer. As a result, the binary cross-entropy training loss reduced drastically and started at 0.064, which is shown in Figure \ref{fig:PT}, whereas the non-pre-trained model started at 0.35. The pre-trained model achieved 0.724 on the NDCG metric, while the non-pre-trained model achieved 0.698, a 2.6\% drop in NDCG performance, showing that pre-training has a significant impact on the training loss. For the ACF model, we implemented different loss functions like mean squared loss and binary cross entropy loss to see any improvement in the overall performance of the model. We found that changing the loss function did not improve the NDCG performance; we believe this is likely due to the sparse nature of the dataset. \begin{figure} \centering \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/NCF-GMF_loss.png} \caption{GMF} \label{fig:GMF} \end{subfigure} \hfill \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/NCF-MLP_loss.png} \caption{MLP} \label{fig:MLP} \end{subfigure} \caption{Training Loss Graph} \label{fig:NCF1} \end{figure} \begin{figure} \centering \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/NCF-NeuMF_loss.png} \caption{Without Pre-training} \label{fig:WPT} \end{subfigure} \hfill \begin{subfigure}[b]{0.24\textwidth} \centering \includegraphics[width=\textwidth]{Images/chap5/NCF-NeuMF-Pretrained_loss.png} \caption{With Pre-training} \label{fig:PT} \end{subfigure} \caption{NCF Training Loss Graph} \label{fig:NCF2} \end{figure} Hyperparameter tuning by Bayesian Optimization (BO) sometimes results in overfitting, the knowledge of the validation data split(s) increases as the number of iterations increases on optimizing hyperparameters. k-fold cross-validation is the standard solution to the problem of overfitting in hyperparameter optimization. The authors \cite{wainer2017empirical} conducted an experimental study to find the number of validation folds to be used for cross-validation evaluation, and they found that two or three validation folds are adequate for finding optimal hyperparameters. In this paper, we used NDCG as a target function and applied Bayesian Optimization to find the optimal combination of parameters that maximized the NDCG. We selected the iterations (number of validation folds) to be three, and the hyperparameters include the number of epochs, learning rate, batch size, weight decay, etc. Table \ref{tab:BO} shows the Bayesian Optimization results for the NCF model with two hyperparameters, namely learning rate and n\_factors. From Table \ref{tab:BO} it can be seen that learning rate 0.001 and n\_factors 16 gives the maximum NDCG (0.708). This discussion motivates further work on how to best represent sparse datasets to predict product recommendations efficiently. The CF with NCF predictions demonstrated in this paper discovers the hidden features of user-item interactions that lead to a good generalization, though a hybrid approach of combining item-based and user-based recommenders for predictions on a more complex representation of user-item interactions may improve the NDCG results presented in this paper. The extensions to matrix factorization and the usage of click data for future work are discussed in the next section. \begin{table}[ht] \caption{Bayesian Optimization for NCF} \begin{center} \begin{tabular}{ |c|c|c|c| } \hline \textbf{Iterations} & \textbf{NDCG@12} & \textbf{Learning Rate} & \textbf{n\_factors} \\ \hline 1 & 0.698 & 0.003 & 12\\ \hline 2 & 0.703 & 0.09 & 14\\ \hline 3 & 0.708 & 0.001 & 16\\ \hline \end{tabular} \end{center} \label{tab:BO} \end{table} \section{Future Work and Conclusions} \subsection{Future Work} Research into collaborative filtering with matrix factorization has demonstrated algorithmic, logical, and practical insights that explain the NDCG performance observed in this paper and has provided future directions of research in predicting sparse user-item interactions with implicit feedback by creating a similarity metric over the latent variable model \cite{borgs2017thy}. The cold start problem is an active area of research that also applies to the work in this paper. The cold start problem can be relevant to both users and items that have no reviews or history; in simple terms, what to recommend to users/items that are not part of a training dataset. Different procedures have been proposed to address the cold start problem. A user/item deep learning content-based recommender was proposed by \cite{volkovs2017dropoutnet} gives a probability of user/item interaction in the absence of particular user/item interaction in the training dataset. Similar to ACF, which is implemented in this paper, VAEs also learn hidden non-linear representations of the data using a probabilistic framework \cite{kingma2013auto}. VAEs that implemented CF demonstrated state-of-the-art results for movie recommendations on Netflix dataset \cite{liang2018variational}. Another critical area of future work is to utilize click-data. In this work, we did not have click-data. However, we suggested the Company to consider implementing click-data so that it can be incorporated in future versions of the Company’s recommender system. Clickthrough Rate (CTR) is a ratio that indicates how often the people who see the recommendation ends up clicking it. In future, after accumulating click-data, the Deep Interest Network \cite{zhou2018deep} model could be implemented with the current use case and investigated further. \subsection{Conclusions} In this paper, the problem of predicting sparse product recommendations at a specific customer level was studied on a proprietary dataset from August 2016 to June 2019. It was hypothesized that CF with latent variable models could discover hidden features in the broad range of products by exploiting the similarity of customers’ past purchasing behaviors, which could be generalized to future purchases. CF with NCF using latent hidden factors for customers and products presented the highest average performance metrics over the period of the dataset studied. The BPR model is shown to be nearly as efficient as CF with NCF. Deep Learning strategies for CF with latent variables like ACF were investigated and revealed to not be as powerful as NCF. A benefit of the NCF approach is that it has discovered that non-linear hidden relationships exist between customers and products, information that was very valuable in the product recommendations. A limitation of NCF is that the learned hidden representation of user/item matrices is not interpretable, which makes it complicated to comprehend why NCF recommends these products to a customer. Recent work illustrated that matrix factorization with latent variables not limited to low-rank approximation shows excellent generalization properties, enduring sparsity and predicting CTR using Deep Interest Network are promising for further application development in predicting product recommendations where data may be sparse and underlying factors may be complicated, noisy and challenging to apprehend explicitly. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi The authors would like to thank the Center for Management of Technology and Entrepreneurship (CMTE) and their sponsors for providing funding to our project. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2020-09-21T02:18:09', 'yymm': '2009', 'arxiv_id': '2009.08950', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08950'}
arxiv
\section{Introduction} \textbf{The significance of recommender systems.} In an increasingly digital world, institutions must accurately anticipate the next movie, song, product, or job that a user will interact with. From YouTube to Netflix, Spotify to Amazon, Facebook to Linkedin, recommender systems are a staple of our daily routines. They influence how we perceive our environment, from media content to human relationships. \textbf{Standard evaluation does not reflect real-life use-cases.} Traditional methods of evaluation that entail random sampling over a long period of time are perfect if the system is designed to remain unchanged for an equally long and predefined period. However, if the system is to be used in a dynamic setting, the way it is evaluated must reflect that. Inadequate evaluation techniques can lead to a false confidence, which is especially detrimental in commercial settings. Evaluating a recommender system can be done \emph{online} or \emph{offline}. \emph{Online} evaluation entails deployment of the recommender in a commercial setting. While this may be the best way to measure the real-life impact of a system, it is also costly and therefore rarely used in research and benchmarking. \emph{Offline} evaluation is far more common in recommender systems research. Here, the model is evaluated on historical data, by selecting some portion of the data to train on, while some other subset is used for performance testing. \textbf{Many existing recommenders ignore temporal information.} Most recommender systems fall into one of the two main categories: content-based and collaborative filtering. Content-based filtering relies on recommended items having similar attributes to those that the user has previously interacted with. Collaborative filtering methods base the recommendation on items bought by similar users. However, most models ignore temporal information, except a subtype of recommenders that focuses on the order of interactions. Time-aware recommender systems -- called sequence-aware recommenders -- introduce additional information to the interactions: the time at which the users' decisions were made. Consequently, there is a need to incorporate the temporal context into traditional recommenders. \textbf{In this work,} we first focus on the importance of temporal dynamics in recommender system creation, training, and offline evaluation. While much effort is directed towards establishing the importance of proper evaluation design, it is generally focused on implementing relevant metrics to avoid under- or over-estimating real-world performance \cite{aggarwal2016recommender}. We draw attention to the lack of standardization in this domain, and the differences between research settings and the systems' ultimate applications. Then, we propose two temporal evaluation protocols and show how they attain a closer approximation of the real-life conditions in which recommender systems are deployed. Second, we present a multi-objective approach to time-unaware recommender systems to incorporate the temporal context without any change in the model architecture. We demonstrate the advantages of such systems. Then, we introduce recency as an objective and as a means to include temporal dynamics in typically time-independent recommender systems. We also provide a measure of recency in the form of a performance metric. Experiments on three real-world publicly available datasets show both improvements in recency and relevance. Finally, we demonstrate that the Pareto Fronts obtained with the added objective dominate those produced by state-of-the-art models. To the best of our knowledge, this is the first study quantifying the difference in recommender system performance when evaluated using methods that model real-world environments, as opposed to traditional techniques. After demonstrating the impact of recency, we show that a recommender system can be optimized for both the relevance and recency objectives simultaneously. To summarize, the main contributions of this paper are as follows: \begin{itemize} \item We demonstrate how commonly used evaluation protocols do not provide adequate modeling of real-world deployment settings. To combat this, we propose two evaluation techniques to facilitate offline modeling of online production environments that inherently incorporate temporal dynamics; \item We introduce a recency function that can be utilized to create a recency objective. We show that optimizing for both recency and relevance \cite{milojkovic2019multi} leads to solutions that dominate those optimized just for relevance in both dimensions. \end{itemize} \section{Related Work} \subsection{Evaluating Recommender Systems} \subsubsection{Traditional Recommender Systems.} Inputs and outputs share similarities with classification and regression modeling: a class variable is predicted from a set of given features. Therefore, given that recommendation tasks can be seen as a generalization of these, some evaluation techniques used for classification are transferrable to recommender systems. In collaborative filtering research, recommenders are generally evaluated either through \emph{strong} or \emph{weak generalization}, characterized by \cite{marlin2004collaborative}. In both approaches, models are trained on observed interactions and validated or tested on those that are held-out. \emph{Weak generalization} is introduced in \cite{10.5555/2074094.2074100}, where the held-out set is created through random sampling of the available interactions. \emph{Strong generalization} differs by taking disjoint sets of users for the training, validation, and testing sets. Following this, some interactions are held-out from the validation and test sets and then approximated using the recommender. Methods that encode user representation cannot apply \emph{strong generalization}, as they cannot generate outputs for previously unseen users. An example of the \emph{strong generalization} approach can be seen in \cite{liang2018variational}, whereas \cite{ning2011slim, wu2016collaborative, rendle2012bpr} all use \emph{weak generalization}. Several of these works emphasize that the application of their recommender system would be in predicting future user actions, yet all validation and testing is done with randomly selected interactions. This can break the time linearity as the knowledge of future interactions can help predict an anterior interaction. \subsubsection{Temporal Recommender Systems.} They denote time-aware models (TARS), and incorporate time explicitly or implicitly. Temporal recommender systems include, but are not limited to, sequence-aware recommender systems (SARS). As previously stated, SARS can be evaluated similarly to TARS. \cite{campos2014time} provide an extensive overview of possible evaluation techniques, which served as an inspiration and point of reference for this work. While traditional evaluation protocols may be used on temporal recommenders, it is more representative to preserve the temporal ordering between interactions since this is something that the recommender aims to learn. By extension, train, validation, and test splits should also be~ordered. \cite{quadrana2018sequence} state that they were unable to find a consensus among evaluation protocols used in recent sequence-aware recommender work, which is mirrored in our findings. Yet we did determine that most recent SARS focus only on next item prediction, meaning they output one recommendation. They also typically employ certain target item conditions to decrease computational cost \cite{campos2014time}. The target item conditions determine the (sub)set of items for which a recommender should produce predictions and are specific for top-N recommendation evaluation. The reduction of the computational costs is generally done through conditions that rank one ground truth item against a set of other items false items. Examples can be found in \cite{sun2019bert4rec, kang2018self, hidasi2018recurrent}. We return to the problem of subsampling in Section \ref{sec:proposed}. \subsection{Temporal Context in Recommender Systems} In this paper, we introduce the concept of recency. An important note is that there are multiple definitions of recency in recommender systems literature. In fact, this lack of consensus has persisted for years. \cite{ding2006recency, vinagre2015collaborative} treat the recency of an item as an attribute that is user-dependent. The value is determined by the last time the user interacted with a given item. \cite{chakraborty2017optimizing, gabriel2019contextual} also claim to incorporate recency into their research: when recommending news articles, they measure recency as the age of the item on the platform. Our analysis will follow the latter definition. \section{Proposed Evaluation Protocols} \label{sec:proposed} We propose that the temporal dimension should be considered when evaluating the performance of any recommender. While random sampling may be an appropriate target selection technique for some classification or regression tasks, we argue that this is not the case when it comes to predicting a user's subsequent move. Unlike the vast majority of evaluation methods applied to traditional recommenders, temporal recommender systems literature does model the passage of time. However, as stated above, the performance is often computed over a subset of the itemset and the user's true chosen item. The argument is that subsampling is necessary due to the complexity of the ranking task. While this has some validity, itemsets of around 10,000 datapoints can be ranked highly efficiently, especially when taking into consideration recent advancements in machine learning libraries and GPU programming. Therefore, we do not utilize subsampling in our work. The adoption of a recommender system in real scenarios has two major phases. The first, called the development phase, is purely offline and theoretical. In this part, three separate sets of data must be created: a training set that the model will use to learn item and user representations, a validation set for hyperparameter tuning, and a test set to evaluate how well the model performs. The second, called the deployment-ready phase, include interactions with end-users. The maximum amount of data is leveraged to train a model with as much information as possible, evaluate its performance, and then deploy it into production. In this case, only two sets are needed: a training and a validation set. One downside of collaborative filtering methods is that most models are incapable of incorporating new items without retraining. While ways to alleviate this problem have been explored \cite{luo2012incremental}, the issue remains widespread and worthy of more study, but lies outside the scope of this paper. Therefore, we assume an industry-like environment: the recommender system will be retrained regularly and will be exposed to clients for a relatively short period, ranging from a couple of days to a maximum of a few months. We postulate that the performance of the recommender on the last portion of historically available data is most indicative of how it will behave when deployed. \begin{figure}[t] \centering \includegraphics[width=.85\linewidth]{Figures/proportional.pdf} \caption{Proportional Temporal Selection.} \label{fig:prop} \end{figure} \begin{figure}[t] \centering \includegraphics[width=.85\linewidth]{Figures/cutoff.pdf} \caption{Strict Temporal Cutoff.} \label{fig:cutoff} \end{figure} Our protocols focus on set creation. When selecting the target values in a validation set, we take two possible approaches. The first, \emph{proportional selection}, depicted in Figure \ref{fig:prop}, selects the final \(X\%\) of each user's interactions and uses these to create target items. Here we preserve the time ordering of the input and target interactions, maintaining similarity with the real-life use-case. However, there is no strict time cutoff, as is the case when we train a system on data available to a certain point and then deploy it. The second approach, shown in Figure \ref{fig:cutoff}, is precisely based on a \emph{strict time cutoff} to select the target items of the validation set. This method is even closer to the real-world use case. However, it does suffer from certain drawbacks as user interactions are not necessarily evenly distributed through time, leading to some users being more represented than others in the target set. While these are similar to the suggestions developed in \cite{campos2014time}, we underline that these approaches should not be limited to evaluating TARS. It is crucial to approximate with maximum precision the performance of a model when developing a novel system, before it is released into production. The second approach directly models the real-world context and contains user-item interaction sequences created after a specific strict time cutoff. \section{Recency to Improve Recommendation} The main task of a recommender system is to anticipate users' future desires and suggest content that they would find relevant. However, just recommending the most relevant items does not always satisfy all the concerns of those building the system. The \emph{relevance} objective is the one that is most commonly found in recommender systems literature and accounts for the accuracy or correctness. It actively focuses the recommender on selecting the item(s) with which the users will most likely interact. However, relevance is not the only objective used in practice. We distinguish two types of objectives: \emph{correlated} and \emph{uncorrelated} to relevance. The former ones correspond to those whose optimization is linked to the relevance objective. Examples are novelty \cite{vargas2011rank}, serendipity \cite{ge2010beyond}, and utility-based objectives, such as revenue. The latter, \emph{not correlated to relevance}, can be diversity and fairness. We introduce such a utility-based objective used to inject temporal information alongside the relevance objective. While the exploration of uncorrelated objectives is essential for the future of recommender systems, we leave it for future~work. \subsection{Adding Temporal Context} Based on the our experience with real-life use-cases, we discovered that users seem to gravitate towards purchasing content that had more recently been added to a given platform. Building on these findings, and works such as \cite{chakraborty2017optimizing} and \cite{gabriel2019contextual}, we decided to explore the effects of incorporating recency as an objective during the learning phase. Given an item \(x\) with a timestamp \(t_x\), we further define the recency function \(f\) as: {\small \begin{equation} f(x) = \left\{ \begin{array}{ll} 1 & \frac{t_{x} - t_{min}}{t_{max} - t_{min}} \geq 0.8 \\ 0.3^{(0.8 - \frac{t_{x} - t_{min}}{t_{max} - t_{min}})\times \frac{10}{3}}& otherwise \\ \end{array} \right. \end{equation} } where \(t_{max}\) and \(t_{min}\) are the maximum (most recent) and minimum (oldest) timestamps over the itemset. In \(f\), we first scale all timestamps to \([0, 1]\) using the min-max scaler, and then apply a transformation inspired by \cite{huang2013incorporating}. A plot of the function is shown in Figure \ref{fig:recency}. \begin{figure}[t] \centering \includegraphics[width=.7\linewidth]{Figures/recency_function.pdf} \caption{Our proposed recency function (Equation 1).} \label{fig:recency} \end{figure} The recency objective is formulated as a loss that stimulates the recommendation of recent items. Each item in the itemset is assigned a recency weight, based on the recency function. The vector is then used to weigh item importance when calculating the loss. Adding weights into a traditional loss does not affect the differentiability of the function. To illustrate how our temporal objective can be easily integrated into a traditionally time-unaware recommender system, we take as a use-case the state-of-the-art variational autoencoder Mult-VAE\textsuperscript{PR} of \cite{liang2018variational}. For the sake of brevity, we refer the reader to \cite{liang2018variational} for more details about the model. We thus propose an extension of Mult-VAE\textsuperscript{PR}, where the loss function for user $u$ is modified to: \begin{align*} \mathcal{L}_{\beta}(x_u;\theta, \phi) = \mathbb{E}_{q_\phi(z_{u}|x_{u})}\left[ \log p_\theta(f(x_u) \ast x_{u}|z_{u})\right] \\ - \beta \cdot \mathrm{KL}(q_\phi(z_{u}|x_{u}) || p(z_{u})) \end{align*} where the expected negative log-likelihood is modified to include the element-wise multiplication of input vector $x_u$ by $f(x_u)$, which corresponds to the recency scores of the given items in $x_u$. $\beta$ controls how much importance is given to the KL term, \(z_u\) is a variational parameter of the variational distribution $\theta$ and $\phi$ are model parameters. \begin{algorithm}[t] \scriptsize \caption{SMSGDA with Gradient Normalization. }\label{alg:multiobj} \label{vanila_alg} \begin{algorithmic}[1] \State $initialize()$ \For{$i \in {1,...,n}$} \State $empirical\_loss_i = \mathcal{L}_i(w)$ \EndFor \For{$epoch \in {1,...,M}$} \For{$batch \in {1,...,B}$} \State $do\_forward\_pass()$ \For{$i \in {1,...,n}$} \State $calculate \, loss \;\; \mathcal{L}_i(w)$ \State $calculate \, gradient \;\; \nabla_{w} \mathcal{L}_i(w)$ \State $normalize \, gradient \;\; \hat{\nabla_{w}\mathcal{L}_i(w)} = \frac{\nabla_{w} \mathcal{L}_i(w)}{empirical\_loss_i} $ \EndFor \State $\alpha_{1}, \ldots, \alpha_{n} = QCOPSolver\left(\hat{\nabla_{w}\mathcal{L}_1(w)}, \ldots, \hat{\nabla_{w}\mathcal{L}_n(w)}\right)$ \State $\nabla_{w} \mathcal{L}(w)=\sum_{i=1}^{n} \alpha_{i} \hat{\nabla_{w}\mathcal{L}_i(w)}$ \State $w = w - \eta \nabla_{w} \mathcal{L}(w)$ \EndFor \State $evaluate\_model()$ \State $update\_pareto\_set()$ \EndFor \end{algorithmic} \end{algorithm} \subsection{Multi-Objective Optimization} Optimizing a recommender on multiple objectives is non-trivial. Thanks to the recent work of \cite{milojkovic2019multi}, we employ the proposed multi-gradient descent algorithm for multiple objectives to train our recommenders. Additionally, the authors show that the algorithm is efficient and does not impact on training time, as it can be seen in Algorithm~\ref{alg:multiobj}, where $n$ is the number of objectives, $M$ is the number of epochs, and $B$ the number of batches. After a standard forward pass (Line 7), the loss and gradient are computed for each objective (Line 8-10). Then, weights of the gradients are computing as a Quadratic Constrained Optimization Problem \cite{desideri2012multiple}, which can be solved analytically for two objectives, or solved as a constrained optimization problem as proposed in \cite{sener2018multi} for more than two objectives. Solving it allows us to obtain the common descent vector and update the parameters (Line 14-15). This training procedure enables us to incorporate both our temporal context and the relevance objectives to retrieve time-aware recommendations. The algorithm adapts~the weight repartition between the two objectives in an advanced manner to optimize both during~training. \section{Experiments} \label{ExperimentsSection} \subsection{Datasets} \begin{table}[t] \centering \begin{threeparttable} \begin{tabular}{@{}lccc@{}} \textbf{ } & \textbf{ML-20M} & \textbf{Steam} & \textbf{Netflix$\geq$4} \\ \toprule \# of users & 46,295 & 257,775 & 471,457 \\ \# of items & 9479 & 13,018 & 13,995\\ \# of interactions & 3.76M & 3.14M & 38.87M \\ \% of interactions & 0.86\% & 0.09\% & 0.59\% \\ \bottomrule \end{tabular} \end{threeparttable} \caption{Statistics of the datasets, after preprocessing.} \label{table:datasets} \end{table} We study the performance of various models on three real-world publicly available datasets. The characteristics of the preprocessed datasets are summarized in Table \ref{table:datasets}. \textbf{MovieLens-20M} contains about 20 million ratings\footnote{\url{https://grouplens.org/datasets/movielens/20m/}.}, with values between 1 and 5. To transform it into implicit feedback, we binarize the user-item interaction matrix, keeping ratings of~4 and above as positive feedback. We filter out all users with less than five ratings, and all movies rated by less than five users. Since this dataset contains entries from 1999 up to 2015, we chose to focus on the last ten years of available data. \textbf{Steam} has review information from the gaming platform Steam\footnote{\url{https://cseweb.ucsd.edu/~jmcauley/datasets.html}.}. We converted user-item interactions into a positive feedback signals. The dataset contains reviews from 2010 to 2018; however, the platform only sees an uptick in review activity after 2014, which is why we select the last four years available for further analysis. \textbf{Netflix} is the well-known Netflix Prize Competition dataset\footnote{\url{https://www.kaggle.com/netflix-inc/netflix-prize-data}.}. It consists of over 100 million ratings. The ratings are on a scale from 1 to 5 and were collected between 1998 and 2005. We filter these ratings in the same way as the MovieLens ratings, and take the last two years of activity. Because of low performance on certain baselines, we denote two variants for the implicit feedback: one with threshold of~$4$ and above (Netflix$\geq$4), the other one with a threshold of~$5$ (Netflix$\geq$5). \subsection{Recommendation Techniques} For all models, we ensured that the items that the user had previously interacted with were removed from the output before the top-k results were selected for metric calculation. All models were trained with the Adam optimizer, with a learning rate of 0.001. \textbf{Mult-VAE\textsuperscript{PR}: } All experiments with the Mult-VAE\textsuperscript{PR} \cite{liang2018variational} were conducted using the implementation from the MAMO framework\footnote{\url{https://github.com/swisscom/ai-research-mamo-framework}.}. We used the same setup as in the original paper. \textbf{SVD: } We utilize the PyTorch implementation\footnote{\url{https://pytorch.org/docs/stable/generated/torch.svd.html}.} of the Singular Value Decomposition \cite{sarwar2000application}, taking only the top 100 dimensions. \textbf{NCF: } For Neural Collaborative Filtering \cite{he2017neural}, we take the implementation from \footnote{\url{https://github.com/guoyang9/NCF}.}, sample four negative instances for every existing user-item interaction, set the predictive factor of 64, and the number of hidden layers for the multilayer perceptron (MLP) to three. We do not present results obtained using pre-trained NeuMF, as they exhibited the same patterns as generalized matrix factorizaion (GMF) and MLP, but did not give a significant improvement. To resolve the difficulties to obtain good results with the \emph{Netflix$\geq$4} dataset for GMF and MLP models, we used instead the \emph{Netflix$\geq$5} dataset. The main difference being that only ratings of five and above are considered as positive. \textbf{BERT4Rec: } This sequence-aware recommender system was introduced in \cite{sun2019bert4rec}. We implemented it in PyTorch and integrated it with the MAMO framework. Most of the hyperparameters used were taken from the original paper. The number of transformer layers is set to 2, the head number is 4, head dimensionality is 64, and the dropout is 0.1. We use a sequence length of 100, while the proportion of masked inputs is 0.2. The model is trained using the Adam optimizer with a learning rate of 1e-4. \textbf{BERT4Rec Extension: } We propose an extension to BERT4Rec. BERT4Rec consumes sequences of items. The positions in the sequence that the user wishes to predict are filled with a special mask identifier. When predicting the next item(s) in a sequence, \cite{sun2019bert4rec} place a mask on the last position in the sequence, and then take the top-$k$ items from the probability distribution of this position, as generated by the model. Instead of selecting the top-\(k\) items from the last (masked) position in the sequence, we suggest to select them from the last-\(p\) positions, all of which are masked in the input sequence. From each position in \(p\) we select the top-\(\lfloor \frac{k}{p} \rfloor\) items, making sure that there are no repeated items. If \(k\) is not divisible by \(p\), the leftover elements are selected from the first masked position. \begin{table*}[t] \centering \begin{threeparttable} \begin{tabular}{@{}llcccc@{}} \textbf{Dataset}&\textbf{Model}& \textbf{Val\textsuperscript{trad}} & \textbf{Val\textsuperscript{prop}} & \textbf{Val\textsuperscript{cutoff}}& \textbf{Test\textsuperscript{temp}} \\ \toprule \multirow{4}{*}{ML-20M} & Mult-VAE\textsuperscript{PR} & 0.32 / 0.18 & 0.26 / 0.13 & 0.11 / 0.06 & 0.11 / 0.07\\ & SVD & 0.25 / 0.22 & 0.14 / 0.11 & 0.07 / 0.03 & 0.11 / 0.07\\ & GMF & 0.25 / 0.22 & 0.11/ 0.10 & 0.08 / 0.03 & 0.10 / 0.07\\ & MLP & 0.25 / 0.23 & 0.12 / 0.10 & 0.07 / 0.03 & 0.11 / 0.07\\ \midrule \multirow{2}{*}{Steam} & Mult-VAE\textsuperscript{PR} & 0.20 / 0.02 & 0.14 / 0.02 & 0.11 / 0.01 & 0.13 / 0.01\\ & SVD & 0.10 / 0.02 & 0.10 / 0.02 & 0.09 / 0.01 & 0.08 / 0.01\\ \midrule \multirow{2}{*}{Netflix$\geq$4} & Mult-VAE\textsuperscript{PR} & 0.35 / 0.18 & 0.22 / 0.10 & 0.12 / 0.05 & 0.10 / 0.05\\ & SVD & 0.23 / 0.16 & 0.23 / 0.16 & 0.09 / 0.05 & 0.07 / 0.04\\ \midrule \multirow{3}{*}{Netflix$\geq$5} & SVD & 0.23 / 0.10 & 0.23 / 0.11 & 0.12 / 0.05 & 0.09 / 0.03\\ & GMF & 0.31 / 0.14 & 0.30 / 0.14 & 0.14 / 0.05 & 0.12 / 0.04\\ & MLP & 0.31 / 0.14 & 0.30 / 0.14 & 0.14 / 0.05 & 0.12 / 0.04\\ \bottomrule \end{tabular} \end{threeparttable} \caption{\label{table:combinedResults}Results of the Mult-VAE\textsuperscript{PR}, SVD, GMF, and MLP evaluated on a traditional, proportionally selected temporal, and strict cutoff validation set, as well as on a temporally shifted test set. We report Recall / Precision at $k=20$.} \end{table*} \subsection{Experimental Setup} The experiments conducted show how an inadequate manner of creating the validation sets in the \emph{deployment-ready} phase leads to false confidence in the performance of the evaluated model. In the \emph{deployment-ready} phase, what we call the validation set is not necessarily used for hyperparameter tuning, but to assess the performance of the model before it is deployed. There are minor differences in the datasets used for the models with and without user representation. Models without user representation require some input interactions to be able to predict targets, while those without simply need to be passed a user identifier. We divide our experiments into three sets, corresponding to the type of evaluation. \subsubsection{Traditional Evaluation.} Similarly to \cite{liang2018variational}, we divide the data into a train set with 80\% of users, validation set with 10\% and test set with 10\%. The target user-item interactions are selected by randomly sampling 20\% of the user-item interactions in the validation and test sets. We show that if a model is evaluated on and later applied to a task that entails predicting randomly held-out interactions, the performance achieved on both validation and test sets is comparable. This traditional approach is typically used to report model performance. We then contrast performance on randomly held-out interactions in the validation set against temporally held-out interactions in the test set. We take 5\% of the users from the train set to create the validation set and hold-out 20\% of their interactions. The test set contains the interactions and users from the train and validation sets as inputs, and the temporally held-out interactions are targets. \subsubsection{Temporal Evaluation.} We show that when evaluated with either a proportional or hard temporal cutoff, the model's performance is closer to what would be observed in a real-life setting. However, it is important to note the ideal evaluation technique is heavily domain dependent. First, we hold out the last 20\% of user-item interactions from each user in the validation set. In the second approach, we hold out the last couple of months of activity and evaluate the model's ability to predict these interactions. We create the validation and test sets as before. \subsubsection{Temporal Evaluation with Added Temporal Context.} We introduce temporal context into the traditionally time-independent Mult-VAE\textsuperscript{PR} by using the work from \cite{milojkovic2019multi} to optimize the model for accuracy and recency. To calculate the recency score we must determine a timestamp for every item in the itemset. We take the timestamp of the moment that the item first became available, or the first recorded instance of any user interacting with the given item. The strict temporal cutoff validation set is utilized, as well as the temporal test set described previously. \subsection{Evaluation Metrics} We evaluate models using three ranking metrics, as recommenders can often only show a predefined number of recommendations. \begin{itemize} \item \textbf{Precision@K: }calculates how many of the recommended items are relevant to the user; \item \textbf{Recall@K: }quantifies the proportion of relevant items in the top-k recommended items by calculating how many of the desirable items are are suggested to the end-user. We take our definition from \cite{liang2018variational}; \item \textbf{Recency@K: }assigns a recency score to each item, calculating the rating of the top-k recommended and relevant items. For user \(u\) with relevant items \(I_{u}\) we define \(\omega(k)\) as the item at rank \(k\), where \(\mathbb{I}\) is the indicator function: \begin{equation} Recency@K(u, \omega, f) = \sum_{k = 1}^{K}{\mathbb{I} [\omega(k) \in I_{u}]\times f(\omega(k))} \end{equation} \end{itemize} \section{Results} \subsubsection{Traditional Evaluation.} This experiment aims to show that the traditional way of evaluation recommender systems, shown in Table \ref{table:vaeTraditional}, is not a faithful representation of the environments in which they are actually deployed. The good performance achieved by evaluating in this way can provide a false sense of security. \begin{table}[t] \centering \begin{threeparttable} \begin{tabular}{@{}lcc@{}} \textbf{Dataset} & \textbf{Val\textsuperscript{trad}} & \textbf{Test\textsuperscript{trad}} \\ \toprule ML-20M & 0.31 / 0.17 & 0.31 / 0.17 \\ Steam & 0.20 / 0.02 & 0.20 / 0.02\\ Netflix$\geq$4 & 0.35 / 0.19 & 0.35 / 0.19 \\ \bottomrule \end{tabular} \end{threeparttable} \caption{Results of initial Mult-VAE\textsuperscript{PR} experiments, evaluated on a traditional evaluation protocol. We report Recall / Precision at $k=20$.} \label{table:vaeTraditional} \end{table} Our claim is supported by the values highlighted by Table \ref{table:combinedResults}. Even though the validation sets are not identical to the ones before, the performance observed is very similar. However, it degrades on the time delayed test set, or to be more precise, when it simulates what would happen in a production setting. Drops in performance of -65.63\%, -35.00\%, and -71.43\% can be observed, on the Recall@20 values. We postulate that this discrepancy leads to significant dissonance between the results of certain recommenders as reported in literature, and those observed in their real-life application. \subsubsection{Temporal Evaluation.} The results shown in Table \ref{table:combinedResults} depict what happens when using traditional validation as apposed to our proposed evaluation sets. The table illustrates how the strict cutoff validation set approximates the \emph{deployment} behavior. For all datasets, this approach seems to be a closer estimation of the ``real-life" performance. For example, the drop in performance is reduced from -71.43\% to -16.67\% on the Netflix$\geq$4 dataset. The proportionally selected validation sets seems to work well for the Steam dataset, and we know from industry experience that it can be good on others. However, it seems to be highly dataset specific and is something that should be kept in mind. Table \ref{table:combinedResults} also shows that this phenomenon is not isolated to the Mult-VAE\textsuperscript{PR}, but can be repeated with the SVD, GMF, and MLP models. As mentioned before, we were unable to conduct experiments on Netflix$\geq$4 with the GMF and MLP models; therefore we report their results on Netflix$\geq$5. The most severe drop in performance is in the case of traditional evaluation on the GMF and MLP on the Netflix$\geq$5 dataset, where the Recall@20 decreases by -61.29\%. It is important to note that simpler methods, especially those based on matrix factorization, do not deal well with the Steam dataset. This is the sparsest dataset that we work with, as shown in Table \ref{table:datasets}, and this seems to make it difficult to learn anything meaningful. Following this conclusion, we exclude the Steam dataset results for GMF and MLP. However, we keep the results for SVD. \begin{figure*}[t] \centering \begin{subfigure}[b]{.32\textwidth} \centering \includegraphics[width=\linewidth]{Figures/VAE_ml20m_strict_last_single_vs_multi_150.pdf} \caption{ML20m dataset.} \label{fig:sub1} \end{subfigure} \hfill \begin{subfigure}[b]{.335\textwidth} \centering \includegraphics[width=\linewidth]{Figures/VAE_steam_strict_last_single_vs_multi_100.pdf} \caption{Steam dataset.} \label{fig:sub2} \end{subfigure} \hfill \begin{subfigure}[b]{.32\textwidth} \centering \includegraphics[width=\linewidth]{Figures/VAE_netflix_strict_last_single_vs_multi_75.pdf} \caption{Netflix$\geq$4 dataset.} \label{fig:sub3} \end{subfigure} \caption[Comparison of Pareto Fronts obtained through optimizing on one objective and two objectives]{Pareto Fronts obtained through optimizing on one objective (accuracy), and two objectives (accuracy and recency).} \label{fig:paretofronts} \end{figure*} We strongly recommend that these evaluation methods be taken into account when presenting novel achievements in the field. When feasible, we recommend to apply both evaluation protocols. \subsubsection{Temporal Evaluation and Temporal Models.} The results presented so far were achieved using traditional recommender architectures, with no way of learning temporal dynamics. Our next contribution is to integrate the temporal dynamic in the training process. Table \ref{table:bertpropcomp} shows the results obtained with BERT4Rec and BERT4Rec\textsuperscript{(5)}. We apply this extension in the testing phase only. The results show that while it boosts the predictive power of the model in some cases, the benefits vary from case to case. \begin{table}[t] \centering \begin{threeparttable} \begin{tabular}{@{}llcc@{}} \textbf{Dataset} & \textbf{Model} & \textbf{Val\textsuperscript{cutoff}} & \textbf{Test\textsuperscript{temp}}\\ \toprule \multirow{2}{*}{ML-20M} & BERT4Rec & 0.20 / 0.09 & 0.15 / 0.08 \\ & BERT4Rec\textsuperscript{(5)} & - & 0.15 / 0.08 \\ \midrule \multirow{2}{*}{Steam} & BERT4Rec & 0.21 / 0.02 & 0.17 / 0.02\\ & BERT4Rec\textsuperscript{(5)} & - & 0.18 / 0.02 \\ \midrule \multirow{2}{*}{Netflix$\geq$4} & BERT4Rec & 0.24 / 0.13 & 0.20 / 0.05\\ & BERT4Rec\textsuperscript{(5)} & - & 0.21 / 0.06 \\ \bottomrule \end{tabular} \end{threeparttable} \caption{Results of BERT4Rec and BERT4Rec\textsuperscript{(5)} evaluated on a strict cutoff validation set and a time delayed test set. BERT4Rec\textsuperscript{(5)} is only applied on the test set. We report Recall / Precision at $k=20$.} \label{table:bertpropcomp} \end{table} By comparing Table~\ref{table:bertpropcomp} and Table~\ref{table:combinedResults} (that contain results achieved with traditional, time-independent recommenders), BERT4Rec achieves the best performance on the test set. This confirms our hypothesis that temporal dynamics should be accounted for in both evaluation design and model architecture in order to attain the best possible recommenders. \subsubsection{Temporal Evaluation with Added Temporal Context.} To further integrate the temporal context, our following contribution has the recency included as an objective influencing the optimization. We refer to the multi-objective Mult-VAE\textsuperscript{PR} as the Multi-Objective Recency Enriched mult-VAE\textsuperscript{PR}(MOREVAE). \begin{table}[t] \centering \begin{threeparttable} \begin{tabular}{@{}llccc@{}} \textbf{Dataset} & \textbf{Model} & \textbf{R} & \textbf{P} & \textbf{Re}\\ \toprule \multirow{2}{*}{ML-20M} & Mult-VAE\textsuperscript{PR} & 0.11 & 0.07 &0.23 \\ & MOREVAE & \textbf{0.13} & \textbf{0.08} & \textbf{0.47}\\ \midrule \multirow{2}{*}{Steam} & Mult-VAE\textsuperscript{PR} & \textbf{0.13} & \textbf{0.01}& 0.15\\ & MOREVAE & \textbf{0.13} & \textbf{0.01} & \textbf{0.18}\\ \midrule \multirow{2}{*}{Netflix$\geq$4} & Mult-VAE\textsuperscript{PR} & 0.10 & 0.04 &0.34\\ & MOREVAE & \textbf{0.12} & \textbf{0.05} & \textbf{0.66} \\ \bottomrule \end{tabular} \end{threeparttable} \caption{\label{table:vaeRecncyAdded}Comparison of Mult-VAE\textsuperscript{PR} and MOREVAE results obtained on temporally shifted test sets. We report \textbf{R}ecall, \textbf{P}recision, and \textbf{Re}cency at $k=20$.} \end{table} We present both the Pareto Fronts obtained during training and the results of the best models on the test sets. Those results were obtained through more intense training than those shown in the previous sections. The Pareto Fronts were generated by evaluating on the strict cutoff validation sets during training, and the best models were chosen by selecting those with the highest Recall@20 and applying them to the time delayed test sets. Figure \ref{fig:paretofronts} shows that the multi-objective approach not only dominates the single objective one in terms of recency, but that optimizing for recency also increases the relevance of the recommendations, validating our initial intuition. The results of the best models over the test sets are shown in Table \ref{table:vaeRecncyAdded}. The improvements obtained are 18.18\%, 0.00\%, and 20\% for Recall@20; 14.29\%, 0.00\%, and 25.00\% for Precision@20. The improvements seen in Recency@20 are 104.35\%, 20.00\%, and 94.12\%. \section{Conclusion} Following standard offline recommendation evaluations during development, based on random sampling of user-item interactions as held-out data, leads to false confidence when deploying models in real-life scenarios. Previous research generally focused on developing better metrics to reflect real-world performance, but still omitted temporal context. We highlighted the lack of standardization and proposed two temporal evaluation protocols that empirically better approximate real-life conditions. Our second contribution is a novel recency objective, that can be used to integrate temporal information in existing time-unaware recommenders. We propose to leverage~a multi-objective approach and train models on relevance and recency simultaneously. Experiments on three real-world publicly available datasets showed that our method produced solutions that strictly dominate those obtained with a model trained on a single-objective optimization. We explored datasets that are frequently used in recommender systems research, all related to digital media content. Digital media content is consumed frequently and generally without much repetition. The importance of recency and capturing transient behavioral trends may not be equivalent in other recommender systems applications, such as grocery or clothes shopping. The influence of temporal dynamics on these sectors is an exciting topic, and we leave it to future academic and commercial research.
{'timestamp': '2020-09-22T02:00:08', 'yymm': '2009', 'arxiv_id': '2009.08978', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08978'}
arxiv
\section{Introduction} Graph embeddings aim to learn a low-dimensional representation for each node in a graph accurately capturing relationships among the nodes. This has wide applicability in many graph analysis tasks including node classification \cite{bhagat2011node}, clustering \cite{ding2001min}, recommendation \cite{liben2007link}, and visualization \cite{maaten2008visualizing}. Various embedding methods have been proposed, including classical spectral embedding algorithms (\cite{balasubramanian2002isomap}, \cite{de2002locally}, \cite{belkin2002laplacian}), factorization (\cite{ahmed2013distributed}), neural embedding (\cite{he2017neural}, \cite{hamilton2017inductive}). The above approaches aim to provide point estimators of embedding features, and a significant shortcoming is their inability to express variation, especially the dynamic variation when data are sequentially collected. Being able to accurately represent variation is critical. In sequence-aware recommender systems (RS), where data are collected from sessions or transactions, besides the intrinsic features, user preferences for products varies over time. Item popularity also changes with time. We use the user-movie rating in the benchmark dataset MovieLens (\cite{harper2016movielens}) as an illustration example. Figure \ref{fig:movielens} (a) displays that for a particular movie, the number of ratings varies with time; Figure \ref{fig:movielens} (b) shows that for a certain user, the number of ratings also varies with time. This example reveals the users' behavior and item popularity may dynamically change based on factors such as the available time, interest shift, and environment changes. These dynamic changes suggest not relying too much on exploitation of past behavior in favor of exploration. However, research focusing on this aspect is still lacking; see Section \ref{sec:related_ref} for detailed reference review. \begin{figure}[h] \centering \begin{tabular}{cc} \includegraphics[scale=0.4]{img/movies0_bar_plot.png} & \includegraphics[scale=0.4]{img/users0_bar_plot.png}\\ ~~~~~$(a)$ & ~~~~~ $(b)$\\ % % \end{tabular} \caption{ $(a)$: the barplot shows the number of ratings versus time for movie ``The Perfect Storm'' which is released on June, 2000. $(b)$: the barplot shows the number of ratings versus time for the user with user\_id 423.}\label{fig:movielens} \end{figure} In this paper, we propose a novel dynamic variational embedding (DVE) method for sequence-aware data to address the aforementioned gap in quantifying variation. We assume that the embedding feature for each node consists of two parts: one is the intrinsic nature and one is the variational feature that captures temporal changes sequentially. Recurrent neural networks (RNN) have been shown to be successful at capturing the nuances of nodes' interactions in the short and long term (\cite{sutskever2014sequence}, \cite{lecun2015deep}). Therefore, we develop an RNN architecture to characterize the dynamic variance. We design an embedding feature that can characterize both short and long range dependence. A distinguishing feature of our method is that the individualized dynamic variance can be explicitly included in the model, providing a strong guidance in exploration. Applying DVE to sequence-aware recommender systems (RS), we further develop an end-to-end deep neural network (DNN) to study link prediction. Given the explosive growth of information available on the web, RS have been widely adopted by many online services, including e-commerce, and social media sites. Personalized RS is an essential demand for facilitating a better user experience. One of the most popular RS approaches is collaborative filtering (CF) (\cite{sarwar2001item}, \cite{schafer2007collaborative}) that aims to model the users' preference on items based on their previous behavior (e.g., ratings, clicks, buy). Among the various CF techniques, a mainstream is measuring the interactions between users and items through products of their latent features (\cite{koren2008factorization}). However, it has been shown in \cite{he2017neural} that such inner product-based models may not be sufficient to capture the complex structure of user interaction data. DNN is flourishing in recent years (\cite{sutskever2014sequence}, \cite{he2017neural} etc). It endows the model with a large level of flexibility and non-linearity to learn the interactions between the embedding features of users and items. In this paper, we built a sequence-aware RS by fully utilizing a neural collaborative filtering framework based on DVE. The main contributions of our work are summarized below. \begin{itemize} \item We propose a novel dynamic variational embedding (DVE) approach to learn nodes' intrinsic and variational features simultaneously. The dynamic variational feature is achieved by introducing a recurrent neural network (RNN) into the neural embedding architecture. This is crucial for facilitating exploration. \item We consider a sequence-aware recommender system, and show that handling temporal information plays a vital role in improving the accuracy of the RS. \item Based on DVE, we develop an end-to-end deep neural architecture for our sequence-aware recommender system, where user's and item's embedding features exhibit temporal dependencies, to study the link prediction. The whole neural architecture is constructed in two parts: one is the embedding layers for DVE, and one is the neural collaborative filtering layers to explore the non-linear interaction between users and items. \end{itemize} \vspace{-5pt} \section{Related Works}\label{sec:related_ref} One classical direction of embedding is factorization-based; examples include spectral embedding algorithms like IsoMap, LLE, Laplacian eigenmap in \cite{balasubramanian2002isomap}, \cite{de2002locally}, \cite{belkin2002laplacian}, and matrix factorization in (\cite{ahmed2013distributed}). Neural networks are also used in graph embedding in recent years. Deep neural networks have proven successful due in part to their ability to model complicated non-linear data representations. The neural collaborative filtering (NCF) proposed by \cite{he2017neural} fuses matrix factorization and one-hot embedding, and feeds them into a deep neural network framework, showing significant gains in accuracy in prediction. Recently, Graphsage \cite{hamilton2017inductive} proposes an inductive learning approach for node features based on graph convolutions, having wide applicability in massive graph problems. However, the above methods aim to provide single estimator, without characterizing variation. Latent space embedding is one approach to learn features with variation, i.e., using latent representations to characterize features of each node with Bayesian probabilistic models, including latent space models \cite{hoff2002latent}. A variety of sequence-aware recommender systems have been proposed in the literature. \cite{koren2009collaborative} developed a time-aware factor model to address the temporal changes in collaborative filtering. \cite{ying2018sequential} developed attention-based RS based on DNN. Again, these methods are lacking variation quantification compared with our DVE based recommender architecture. Variational autoencoders (VAEs), combining the deep latent variable model and variational learning technique, are popular in the application of recommender systems recently. \cite{li2017collaborative} proposes collaborative variational autoencoder (CVAE) approach to learn the item-based embedding in an unsupervised manner. \cite{liang2018variational} constructs a generative model with multinomial likelihood for each user’s preference on all items by assigning a low dimensional latent vector for the user's preference. The above approaches are either item-based or user-based unsupervised learning; while our approach is supervised learning, and can learn the variational features of the users and items simultaneously. Another crucial limitation of current VAE-based recommender learnings is their insufficiency in exploration, since the key idea of VAE (e.g.,\cite{liang2018variational}) is minimizing the KL distance between the input behavior and its latent representer, which only focuses on the exploitation of the previous behaviors. However, our DVE-based approach considers both the long-term feature and the dynamic variation for each user and item, thus enabling exploration. Furthermore, the computational and storage bottleneck of the above user-based VAEs become critical for RS with millions of users and items, since the input and the training target include the whole preference for each user. In contrast, the input of our approach includes only the individualized records at time $t$, such as (user\_id, item\_id, click (or score)) at $t$, i.e., the nonzero entries in the sparse preference matrix. Thus we enjoy relatively high computational efficiency. Our work is related to the study of NCF in \cite{he2017neural}, but distinguished from \cite{he2017neural} by the following aspects: (1) our embedding feature is random and dynamic by considering the temporal information; (2) we consider sequence-aware RS instead of static RS. \section{Method} The key idea behind our dynamic variational embedding (DVE) approach is that we assume the embedding features have both an intrinsic and variational nature. In the following, we first introduce neural variational embedding algorithm in which the embedding is learned in two parts: the (intrinsic) mean and its variance. Based on such structure, we further illustrate the construction of DVE, incorporating temporal changes into the variance by employing recurrent neural networks (RNN). \subsection{Neural Variational Embedding}\label{subsec:ve} Suppose we have $n$ nodes. We first express each node as a binarized sparse vector with one-hot encoding. Denote the input feature of the $i$th node as $u_i$. For simplicity, we only use the identity of the node as the input feature, i.e. $u_i$ is a binary vector with $i$th entry being $1$ and other entries being $0$. Note that $u_i$ can be easily extended to content-based or neighbor-based features. Denote the embedding feature for each node as $w_i$. Suppose $w_i$ follows the regression function as \begin{equation}\label{eq:embed_decom} w_i = W_1 u_i + z_{u_i}, \end{equation} where $W_1 \in \mathbb{R}^{R\times n}$ is the mean embedding matrix, $z_{u_i}\sim N(0, \sigma_{u_i}^2 I_R)$ with $I_R$ as an $R\times R$ identity matrix, and $R$ is the embedding dimension. Define $\mu_{u_i}= W_1 u_i$, i.e., the $i$th column of $W_1$. E.q. (\ref{eq:embed_decom}) says that our embedding feature consists of two parts: the mean $\mu_{u_i}$ and the random variation $z_i$ induced by $\sigma_{u_i}$. As shown in Figure \ref{fig:VE}, the mean embedding vector $\mu_{u_i}$ can be achieved via learning $W_1$; and we learn the variance $\sigma_{u_i}^2$ from the variance embedding vector through fully connected layers. That is, $$ \sigma_{u_i}^2 = g(W_3W_2u_i), $$ where $W_2$ and $W_3$ are weight matrices. To guarantee $\sigma_{u_i}^2\geq 0$, the activation function $g$ for the output layer can be chosen from the following candidates based on the performance. \begin{equation}\label{eq:active_function} g(x)= \begin{cases} \max\{0,x\}, \\ % |x|, & \\ % x^2. & % \end{cases} \end{equation} Then following (\ref{eq:embed_decom}), the embedding feature $w_i$ can be achieved by combining $\mu_{u_i}$ and $z_{u_i}$ generated from $N(0, \sigma_{u_i}^2I_R)$. \begin{figure}[h] \centering \includegraphics[width=0.60\textwidth]{img/VE.pdf} \caption{Variational embedding architecture.} \label{fig:VE} \end{figure} \subsection{Dynamic Variational Embedding} In sequence-aware data, the variation changes dynamically, which further leads to the dynamic embedding for each node. Denoting $w_i^{(t)}$ as the embedding feature of node $i$ at time $t$, we update (\ref{eq:embed_decom}) to the following temporal model \begin{equation}\label{eq:embed_dve} w_i^{(t)} = W_1 u_i^{(t)} + z_{u_i}^{(t)}, \end{equation} where $u_i^{(t)}$ is the input feature of the $i$th node at time $t$, and $z_{u_i}^{(t)}$, representing the variational part, is generated from $N(0, \sigma_{u_i}^{2(t)}I_R)$. We incorporate recurrent neural networks (RNN) to learn $\sigma_{u_i}^{2(t)}$, which is different from the variational learning in Section \ref{subsec:ve}. RNNs are powerful sequence models that take as their input not just the current input example they see, but also what they have perceived previously in time. However, it is well-known that vanilla RNNs suffer from the vanishing gradient problem. Long short-term memory units (LSTM) are a special kind of RNNs that retains similar structure to the vanilla RNN, but can solve the problem of vanishing and exploding gradients faced while training vanilla RNNs. In this part, we utilize the LSTM to train the dynamic variation of each node. As shown in Figure \ref{fig:DVE}, the variance embedding vector $W_2u_i^{(t)}$ is fed into a recurrent neural architecture. The output dense vector depends on the current history $h_{u_i}^{(t-1)}$ by means of a recurrent layer $h_{u_i}^{(t)}$: $$ h_{u_i}^{(t)} = RNN(h_{u_i}^{(t-1)}, W_2u_i^{(t)}). $$ The $h_{u_i}^{(t)}$ is then fed into the fully connected layers via the weight matrix $W_3$, and finally outputs the dynamic variance $\sigma_{u_i}^{2(t)}$ based on the activation function $g$ specified in (\ref{eq:active_function}). \begin{figure}[h] \centering \includegraphics[width=0.60\textwidth]{img/DVE.pdf} \caption{Dynamic variational embedding architecture.} \label{fig:DVE} \end{figure} After obtaining $\sigma_{u_i}^{2(t)}$, we generate $z_{u_i}^{(t)}$ from $N(0, \sigma_{u_i}^{2(t)} I_R)$, where $I_R$ is the identity matrix with dimension $R$. The final DVE of the $i$th node can be achieved by combining $\mu_{u_i}$ and $z_{u_i}^{(t)}$ by e.q. (\ref{eq:embed_dve}). \section{DVE-based Neural Collaborative Filtering } In this section, we apply the DVE to sequence-aware recommender systems, and construct a neural collaborative filtering architecture to learn the model parameters and the user-item interaction. We first provide a brief introduction of the graph notation in recommender systems. \subsection{Notations in Recommender Systems} Denote $G= (U,V,Y)$, where $U$ consists of $n$ users, $V$ consists of $m$ items, $Y= (Y^{(1)}, \cdots, Y^{(T)})$, and each $Y^{(t)}$ is an $n\times m$ incidence matrix, with each entry $y^{(t)}_{ij}$ denoting the value of the interaction between user $i$ and item $j$ at time $t$, where $i=1, \cdots, n$, $j=1, \cdots, m$, $0<t \leq T$. For example, in e-commercial recommender systems, $y^{(t)}_{ij} =0,1,2,3$ represents that user $i$ has no access/no response, click, add to cart and buy actions on item $j$ at time $t$, respectively. In recommender rating systems, $y^{(t)}_{ij}=0,1,\cdots, 5$ denotes the possible ratings of user $i$ on item $j$ at time $t$: $0$ denotes no access, $1$ denotes a poor rating and $5$ is the maximum value allowed. Denote $W^{(t)}= (w^{(t)}_1, \cdots, w^{(t)}_n)\in \mathbb{R}^{R\times n}$ as the embedding matrix of $n$ users at time t, with $w^{(t)}_i\in \mathbb{R}^{R\times 1}$ as the embedding feature of the $i$th user at time $t$. Similarly, define $Q^{(t)} = (q^{(t)}_1, \cdots, q^{(t)}_m)\in \mathbb{R}^{R\times m}$ as the embedding matrix of $m$ items at time $t$, with $q^{(t)}_j\in \mathbb{R}^{R\times 1}$ as the embedding feature of the $j$th item at time $t$. Define $u_i^{(t)}$ and $v_j^{(t)}$ as the input feature of user $i$ and item $j$ at time $t$, respectively. In fact, for user $i$, $u_i^{(1)} = \cdots = u_i^{(T)}= u_i$; for item $j$, $v_j^{(1)} = \cdots = v_j^{(T)}= v_j$, with $u_i$, $v_j$ encoded following Section \ref{subsec:ve}. The purpose of introducing the index ${(t)}$ here is to activate the current history in the RNN layer when learning DVE. Notations are summarized in Table \ref{table:notation}. \begin{table}[h] \small \centering % \begin{tabular}{c|p{0.3\textwidth}} \hline\hline {\bf{Notation}} & {\bf{Description}}\\ \hline U & the set of $n$ users\\ V & the set of $m$ items\\ $Y^{(t)}$ & the $n\times m$ incidence matrix at time $t$ \\ $W^{(t)}$ & the embedding matrix of users at $t$\\ $w_i^{(t)}$ & the embedding feature of user $i$ at $t$\\ $Q^{(t)}$ & the embedding matrix of items at $t$\\ $q_j^{(t)}$ & the embedding feature of item $j$ at $t$\\ $u_i^{(t)}$ & the input feature of user $i$ at $t$\\ $v_j^{(t)}$ & the input feature of item $j$ at $t$\\ \hline\hline \end{tabular} \caption{Notations.}\label{table:notation} \end{table} \subsection{Dynamic Neural collaborative filtering} Collaborative filtering predicts what items a user will prefer by discovering and exploiting the similarity patterns across users and items. Here we use the DVE layers to learn user/item embedding features. Inspired by \cite{he2017neural}, we construct the neural collaborative filtering (NCF) layers, and combine them with the DVE layers to learn the model parameters and the user-item interaction. Figure \ref{fig:NCF} illustrates the dynamic NCF architecture. As shown in Figure \ref{fig:NCF}, we fed the user/item embeddings based on DVE into a multi-layer neural architecture, and finally output the predicted score $\hat{y}_{ij}^{(t)}$. The training is performed by minimizing the loss function as specified in the following part. Given the embedding feature matrix $W^{(t)}$ and $Q^{(t)}$, the predicted score between user $i$ and item $j$ at time $t$ can be expressed as \begin{equation}\label{eq:est_y} \hat{y}_{ij}^{(t)} = f(W^{(t)}u_i^{(t)}, Q^{(t)}v_j^{(t)} | W^{(t)}, Q^{(t)}), \end{equation} where $f(\cdot)$ is the interaction function defined as \begin{equation*} f(W^{(t)}u_i^{(t)}, Q^{(t)}v_j^{(t)}) = \varphi_{out}\Big(\varphi_M\big(\dots \varphi_1(W^{(t)}u_i^{(t)}, Q^{(t)}u_j^{(t)})\big)\Big), \end{equation*} where $\varphi_{out}$ and $\varphi_M$, respectively, denote the mapping function for the output layer and the $M$-th neural collaborative filtering layer, and there are $M$ NCF layers in total. Therefore, $M$ determines the model's learning capacity. Note that $w_i^{(t)} = W^{(t)}u_i^{(t)}$ is user $i$'s embedding feature obtained via DVE, i.e., model (\ref{eq:embed_dve}). Similarly, $q_j^{(t)}=Q^{(t)}u_j^{(t)}$ is the item $j$'s embedding feature obtained via DVE with $ q_j^{(t)} = Q_1 v_j^{(t)} + z_{v_j}^{(t)}. $ \begin{figure}[h] \centering \includegraphics[width=0.70\textwidth]{img/NCF.pdf} \caption{Neural collaborative filtering architecture with DVE. } \label{fig:NCF} \end{figure} Commonly used feedbacks in RS include two categories: explicit (e.g., ratings, votes) and implicit (e.g., clicks, purchases). Explicit feedback data are often in the form of numeric ratings from users to express their preferences regarding specific items. In this case, we can view $y_{ij}^{(t)}$ as a continuous variable. We use squared loss to learn model parameters, and the loss function is defined as \begin{equation} \mathcal{L}_{sq} = \sum_{t=1}^T \sum_{(i,j)\in (U\cup V)^{(t)}} \big(y_{ij}^{(t)} - \hat{y}_{ij}^{(t)}\big)^2, \end{equation} where $(U\cup V)^{(t)}$ refers to the observed interaction between user and item nodes at time $t$. Implicit feedback data are easier to collect, it is also called one-class RS in which only positive implicit feedback can be observed. The target value $y_{ij}^{(t)}$ is $1$ if user $i$ and item $j$ have interaction at time $t$, and $0$ otherwise. For the binary response case, in order to guarantee $\hat{y}_{ij}^{(t)}\in \{0,1\}$, we impose a logistic model on the activation function for the output layer $\varphi_{out}$, i.e., $\varphi_{out}(x) =\frac{e^x}{1+e^x}$. Denote $\mathcal{Y}^{(t)}$ as the set of observed interactions in $Y$ at time $t$, and $\mathcal{Y}^{(t)-}$ as the set of negative instances, which can be no interactions or unobserved interactions. Define $\mathcal{Y} = (\mathcal{Y}^{(1)}, \cdots, \mathcal{Y}^{(T)})$, $\mathcal{Y}^{-} = (\mathcal{Y}^{(1)-}, \cdots, \mathcal{Y}^{(T)-})$, $W= (W^{(1)}, \cdots, W^{(T)})$, $Q = (Q^{(1)}, \cdots, Q^{(T)})$, also denote $\Theta$ as the model parameters in the neural architecture. Then the likelihood function can be written as $$ P(\mathcal{Y}, \mathcal{Y}^{-}|W, Q, \Theta) = \prod_{t=1}^T \prod_{(i,j)\in \mathcal{Y}^{(t)}}\hat{y}_{ij}^{(t)} \prod_{(i,j)\in \mathcal{Y}^{(t)-}} (1-\hat{y}_{ij}^{(t)}), $$ where $\hat{y}_{ij}^{(t)}$ is estimated by e.q.(\ref{eq:est_y}). The log-likelihood loss function can be written as $$ \mathcal{L} = \sum_{t=1}^T \sum_{(i,j) \in \mathcal{Y}^{(t)}\cap \mathcal{Y}^{(t)-}} \big(y_{ij}^{(t)} \log \hat{y}_{ij}^{(t)} + (1-y_{ij}^{(t)})\log(1-\hat{y}_{ij}^{(t)})\big). $$ In practice, when the interactions are sparse, we uniformly sample from the negative sets $\mathcal{Y}^{(t)-}$ at each time $t$, and control the sampling ratio to the range between $1:3$ and $1:5$. \section{Experimental Results} In this section, we implement our proposed DVE method on sequence-aware recommender systems, and compare with existing methods using one of the most popular public data sets: Movielens. We first compare our proposed method with several competitors which are designed for explicit data. We further exam its performance on implicit data, by transforming the ratings into 0 or 1 based on whether the user has rated the item or not. The numerical studies are run on a computing workstation with two Titan-V GPU processors and 64GB RAM. \subsection{Movielens data description} The Movielens-1M data set is collected by GroupLens Research and is downloaded from \url{http://grouplens.org/datasets/movielens}. It contains $1,000,209$ ratings of $3883$ movies by $6040$ users, and the rating scores range from 1 to 5. The data are collected from April 2000 to February 2003. The timestamps are recorded to show when a user rates a movie. We observe that the variation of the popularity of the movie and the preference of the user dramatically changes over time. For example, the number of viewers might be large in the first few months following its release date, then decrease after that. We plot the number of ratings versus time for the movie titled as ``The Perfect Storm'' in Figure \ref{fig:movielens}(a). It shows that the number of ratings is increasing from May to December of $2000$ and dropped to less than $20$ in $2001$. The strong temporal pattern motivates us to model the variance dynamically. Movies having features with large variance will tend to be recommended to a broader range of users, while lower feature variance narrows the recommendation range. \subsection{MovieLens data with explicit feedback} We directly use the rating as explicit feedback. The proposed method is compared with the following competitors designed for explicit feedback recently. \begin{itemize} \item \citet{agarwal2009regression} proposes a regression-based latent factor model. \item \citet{mazumder2010spectral} provides a soft-impute algorithm to replace the missing elements with those obtained from a soft-thresholded SVD. \item \citet{zhu2016personalized} proposes a likelihood method to seek a sparse latent factorization, from a class of overcomplete factorizations, possibly with a high percentage of missing values. \item \citet{he2017neural} establishes the general NCF framework based on one-hot embedding layer for latent features of each user and item. \item \citet{bi2017} proposes a group-specific method to use dependency information from users and items which share similar characteristics under the singular value decomposition framework. \end{itemize} We first order all the ratings based on their timestamps. Then we set the first $75\%$ as the training data set and set aside the last $25\%$ of ratings as the testing data set. The root mean square error (RMSE) of the testing set is reported in Table \ref{tab:1}. \begin{table}[h!] \centering \begin{tabular}{l|c} \hline \multicolumn{2}{c}{Dataset: Movielens-1m}\\ \hline Method & RMSE\\ \hline DVE (our proposed) & \textbf{0.891} \\ \citet{agarwal2009regression} & 1.197 \\ \citet{mazumder2010spectral} & 1.073 \\ \citet{zhu2016personalized}& 1.063\\ \citet{bi2017} & 0.964 \\ \citet{he2017neural} & 0.933 \\ \hline \end{tabular} \caption{Experimental results of Movielens-1M dataset with explicit feedback. }\label{tab:1} \end{table} Table \ref{tab:1} provides the prediction results on the testing set, and shows that our proposed method outperforms other methods significantly. The RMSE of the proposed method is 25.6\% less than \citet{agarwal2009regression}, 17.0\% less than \citet{mazumder2010spectral}, 16.2\% less than \citet{zhu2016personalized}, 7.6\% less than \cite{bi2017}, and 4.5\% less than \citet{he2017neural}. \subsection{Movielens data with implicit feedback} In this setting, we code the user-movie interaction as a binary variable in which $1$ indicates that the user rates the movie and $0$ indicates that the rating is missing. % We use leave-one-out evaluation to evaluate the performance of item recommendation; see \cite{he2017neural,bayer2017generic,he2016fast} etc. For each user, we hold-out his/her latest interaction as the test item and utilize the remaining data for training. To increase the computational efficiency, we randomly sample $100$ items that are not interacted with by the user, and rank the test item among the $100$ items. The evaluation is done on top-$k$ recommendation. The performance of a ranked list is judged by the overall {\it{top-$k$ Hit Ratio}} (HR@k) and overall {\it{top-$k$ Normalized Discounted Cumulative Gain}} (NDCG@k). The HR@k measures whether the test item is included in the top-$k$ list. NDCG@k gives more weight to the relevant items on top of the recommender list, and is defined as \begin{equation} NDCG@k = \frac{\sum_{i=1}^k r_i/\log_2(i+1)}{\sum_{i=1}^{k}1/\log_2(i+1)}, \end{equation} The performance of a ranked list is judged by the averaged HR@10 and NDCG@10 for all users. We compare with \cite{he2017neural} for their three methods: the generalized matrix factorization method (GM), the pure neural network framework with one-hot embeddings (MPL), and a fusion of the two (Neural-GM). We implement their algorithm using the docker image provided in \url{https://github.com/hexiangnan/neural_collaborative_filtering}. \begin{table}[h!] \centering \begin{tabular}{l|c|c} \hline \multicolumn{3}{c}{Movielens-1M with implicit feedback}\\ \hline Method & NDCG@10 & HR@10 \\ \hline Our proposed & \textbf{0.4211} & \textbf{0.6924}\\ \citet{he2017neural}-GM & 0.3676 & 0.6358 \\ \citet{he2017neural}-MPL & 0.3942 & 0.6737 \\ \citet{he2017neural}-Neural-GM & 0.4073 & 0.6790 \\ \citet{liang2018variational}-VAE& 0.0416 & 0.4481\\ \hline \end{tabular} \caption{Experimental results for Movielens-1M data set with implicit feedback.}\label{tab:s2} \end{table} Table \ref{tab:s2} shows that our proposed method outperforms the state-of-the-art methods \citet{he2017neural}-GM, \citet{he2017neural}-MPL and \citet{he2017neural}-Neural-GM by a large 3\% -15\% and 2\%-9\%, respectively. We also compare our proposed method with the VAE-based collaborative filtering studied in \cite{liang2018variational}. As shown in Table \ref{tab:s2}, the NDCG@10 is lower than $0.1$, and HR@10 is lower than $0.5$. In \cite{liang2018variational}, they use the evaluation strategy by holding out several users as the testing set. However, in this study, for each user, we hold out the latest interaction as the testing set for evaluation. The VAE-based approach has limitation in exploration under such evaluation strategy, since its input treats all the unobserved movies as $0$ and the VAE is designed to learn the representation of the input. Instead, our proposed method uses negative sampling to sample a small portion of the negative set, thus it turns out to have better performance in exploration for existing users. \section{Discussion} We propose a dynamic variational embedding framework and implement it for collaborative filtering with temporal information. Our method is simple and generic; it is not limited to the applications presented in this paper, but is designed to any embedding task. This work complements the mainstream embedding models by incorporating variation and dynamic changes, opening up a new avenue of research possibilities for wide range of embedding models. In the future, we will study the knowledge-based embedding to model auxiliary information, such as user reviews, user geographical information, and movie reviews. Individualized or itemized information could help us to better understand the uncertainty and dynamic pattern of the embeddings. \bibliographystyle{plainnat}
{'timestamp': '2020-09-21T02:18:18', 'yymm': '2009', 'arxiv_id': '2009.08962', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08962'}
arxiv
\section{Conclusion} \par Our work studies how adversarially perturbing feature statistics simulates domain shift in image data. We find that adversarial fine-tuning on features perturbed in this way improves robustness to data stylization and corruption without ever training on auxiliary data. Training with Adversarial Batch Normalization (AdvBN) is computationally cheap and can quickly make pre-trained models less brittle. We fine-tune a ResNet-50 with our algorithm and surpass the performance of state-of-the-art methods on both ImageNet-Instagram and Stylized-ImageNet. Adversarial feature statistics are a promising direction for creating models that generalize well to a variety of domains. \section{Adversarial Batch Normalization} \label{sec:AdvBN} We propose {\em Adversarial Batch Normalization} (AdvBN), a module that adversarially perturbs deep feature distributions such that the features confuse CNN classifiers. We iteratively compute adversarial directions in feature space by taking PGD steps on batch statistics. In the next section, we will train on these perturbed feature distributions in order to produce models robust to domain shifts. Consider a pre-trained classification network, \(g\), with $L$ layers. We divide \(g\) into two parts, $g^{1,l}$ and $g^{l+1, L}$, where $g^{m ,n}$ denotes layers $m$ through $n$. Now, consider a batch of data, $x$, with corresponding labels, $y$. Formally, the AdvBN module is defined by \begin{equation} \begin{array}{cccc} \text{BN}_{\text{adv}}(x;g,l, y) = \delta_{\sigma}'\cdot(f-\mu(f))+\delta_{\mu}' \cdot \mu(f) \text{, where f = g^{1,l}(x),\\ &\\ (\delta_{\mu}', \delta_{\sigma}') = \argmax_{(\delta_\mu, \delta_\sigma)} \mathcal{L}\bigg[g^{l+1, L}\bigg(\delta_\sigma \cdot (f-\mu(f))+\delta_{\mu} \cdot \mu(f)\bigg), y\bigg],\\ &\\ \text{subject to } \Vert \delta_{\mu}-1\Vert_{\infty} \leq \epsilon, \Vert \delta_{\sigma}-1 \Vert_{\infty}\leq \epsilon, \end{array} \end{equation} where the maximization problem is solved with projected gradient descent. Simply put, the AdvBN module is a PGD attack on batch norm statistics which can be inserted inside a network. Note that $\delta_\mu, \delta_\sigma$ are vectors with length equal to the number of channels in the output of layer $l$, and we multiply by them entry-wise, one scalar entry per channel, similarly to Batch Normalization. Additionally, note that this module acts on a per-batch basis so that features corresponding to an individual image may be perturbed differently depending on the batch the image is in. We formulate the perturbation by first subtracting out the mean so that $\delta_\mu\cdot\mu(f)$ is the new mean of the adversarial features, and $\delta_\mu$ directly controls the new mean. We choose $\delta_\mu\cdot \mu(f)$, rather than simply $\delta_\mu$, to represent the new mean of the perturbed features so that $\ell_\infty$ bounds and steps size do not need to depend on the mean of $f$. Intuitively, we permit the mean of adversarial features to vary more when the clean features have a mean of higher magnitude. \begin{figure}[b!] \centering \resizebox{\linewidth}{!}{ \includegraphics{figs/demo.pdf} } \caption{\textbf{Examples of perturbed ImageNet images generated by AdvBN with a decoder}. The first row contains the original versions from the ImageNet validation set.} \label{fig:demo1} \end{figure} \paragraph{Visualizing feature shifts} To verify our assumption that adversarially perturbing feature statistics corresponds to transforming the distribution in image space, we visualize the effects of AdvBN. We adopt the VGG-19 based autoencoder from \citet{huang2017arbitrary}. At the bottleneck of the autoencoder, we plug in an AdvBN module followed by a VGG-19 classifier \citep{vgg}. We visualize perturbations by feeding the AdvBN outputs to the decoder. In Figure~\ref{fig:demo1}, images crafted through this procedure are visibly different from the originals; semantic content in the original images is preserved, but the new images exhibit differences in color, texture, and edges. We draw two major conclusions from these visualizations which highlight the adversarial properties of these domains. The first one concerns textures: according to \citet{geirhos2018imagenet}, CNNs rely heavily on image textures for classification. Images from the adversarial domain, on the other hand, have inconsistent textures across samples. For example, the furry texture of a dog is smoothed in column 2, and the stripes disappear from a zebra in column 4, whereas visible textures appear in columns 6 and 8. The second conclusion pertains to color. Results in \citet{zhang2016colorful} suggest that colors serve as important information for CNNs. In the adversarial domain, we find suppressed colors (columns 1, 3) and unnatural hue (columns 5, 7). See Appendix A.3 for additional example images generated by this procedure. Figure \ref{fig:advsteps1} illustrates how the appearance of reconstructed images shifts as adversarial perturbations to feature statistics become larger. We use this visualization technique to process the entire ImageNet validation set and denote it as ImageNet-AdvBN in Figure~\ref{fig:datasets}. By evaluating different methods on this dataset, we observe that accuracy on ImageNet-AdvBN is consistently lower than that on the original ImageNet dataset. This degradation in performance validates the adversarial property of features generated by AdvBN. Experiments concerning performance on ImageNet-AdvBN are listed in Appendix A.2. \begin{figure}[h!] \centering \resizebox{\linewidth}{!}{ \includegraphics{figs/advstrength.pdf} } \caption{\textbf{The effect of adversarial strength on visualized examples}. $\epsilon = 0$ corresponds to images reconstructed by our autoencoder without AdvBN.} \label{fig:advsteps1} \end{figure} \section{Training with Adversarial Batch Normalization}\label{training} In this section, we use the proposed AdvBN module to train networks on the perturbed features. The goal of this adversarial training routine is to produce networks that both perform well on the data distribution on which they are trained and also generalize well to many new domains, all without having to obtain auxiliary data from new domains. We start with a pre-trained model, \(g = g^{l+1, L}\circ g^{1,l}\), and we fine-tune the subnetwork, \(g^{l+1, L}\), on clean and adversarial features simultaneously. To this end, we solve the following min-max problem, \begin{equation} \min_{\theta} \mathbb{E}_{(x,y)\sim \mathcal{D}} \bigg[ \mathcal{L}(g_{\theta}^{l+1,L}\circ \text{BN}_\text{adv}\circ g^{1,l} (x),y) + \mathcal{L}(g_{\theta}^{l+1,L}\circ g^{1,l} (x),y)\bigg], \end{equation} where $\mathcal{L}$ denotes cross-entropy loss, and $\mathcal{D}$ is the distribution of batches of size $n$. This optimization problem contains a maximization problem inside the $\text{BN}_\text{adv}$ layer. In order to maintain the network's performance on natural images, we adopt a similar approach to \citet{xie2019adversarial} by using auxiliary batch normalization in \(g^{l+1, L}\) for adversarial features; we use the original BNs when propagating clean features, and we use auxiliary ones for adversarial features. See Algorithm \ref{algo:adv1} for a detailed description of our method for fine-tuning the parameters of \(g^{l+1, L}\). \par Since we start with pre-trained models, we only need to fine-tune for $20$ epochs, yielding improved robustness with little additional compute. Moreover, we only modify the parameters of later layers, so we do not need to backpropagate through the first half of the network. See Appendix B for an analysis of training times using our method. In the following section, we measure the performance, on several datasets, of our model fine-tuned using adversarial training with AdvBN. \begin{algorithm}[ht] \KwIn{Training data, pretrained network \(g = g_{\theta}^{l+1, L}\circ g^{1,l}\), PGD bound \(\epsilon\), and PGD step size \(\tau\) } \KwResult{Updated network parameters, \(\theta\), of subnetwork \(g_{\theta}^{l+1, L}\) } \For{epoch = 1, \dots, N}{ Sample mini-batch \(x\) with label \(y\)\; Obtain feature map \(f = g^{1,l}(x)\)\; Initialize perturbation: \(\delta = (\delta_{\mu}, \delta_{\sigma}\))\; Let \(f_{adv} = f\)\; \For{adversarial step = 1, \dots, m}{ $f_{adv} \leftarrow \delta_{\sigma}\cdot (f - \mu(f)) + \delta_{\mu} \cdot \mu(f)$\; Update $\delta$: $\delta \leftarrow \delta + \tau \cdot sign(\nabla_{\delta} \mathcal{L}(g_\theta^{l+1,L}(f_{adv}), y))$\; $\delta \leftarrow$ clip $(\delta, 1-\epsilon, 1+\epsilon)$\; } $f_{adv} \leftarrow \delta_{\sigma}\cdot (f - \mu(f)) + \delta_{\mu} \cdot \mu(f)$\; Minimize the total loss w.r.t. network parameter: $\theta \leftarrow \argmin\limits_{\theta}\mathcal{L}(g_\theta^{l+1,L}(f_{adv}), y) + \mathcal{L}(g_{\theta}^{l+1,L}(f), y)$\; } \KwRet{$\theta$} \caption{Training with Adversarial Batch Normalization} \label{algo:adv1} \end{algorithm} \section{ImageNet-AdvBN Experiments} \subsection{Creation of the ImageNet-AdvBN dataset} We process the entire ImageNet validation set using the visualization technique introduced in Section~\ref{sec:AdvBN}. We consider two encoder architectures: one is the VGG-19 encoder we use for visualization, another consists of layers of a ResNet-50 up to \texttt{conv2\_3}. Both encoders are paired with the same decoder architecture from \citet{huang2017arbitrary}.The resulting datasets, denoted by ImageNet-AdvBN-VGG and ImageNet-AdvBN-ResNet respectively, contain 50000 images each. The data we synthesize for testing other models is generated using these autoencoders that contain the AdvBN module but on ImageNet validation data. AdvBN is conducted with 6 steps, stepsize $= 0.20$, $\epsilon = 1.1$, and a batchsize of $32$. We do not shuffle the ImageNet validation data when generating these batches. \subsection{Classification on ImageNet-AdvBN} \input{tables/AdvBN} Table~\ref{a:advbn} shows the classification performance of various models on the two ImageNet-AdvBN variants, denoted as Im-Adv-VGG and Im-Adv-ResNet respectively. We also test these models on ImageNet images that are reconstructed using our autoencoders, denoted as VGG Reconstructed and ResNet Reconstructed, for each autoencoder. The performance gap between ImageNet-AdvBN and Reconstructed ImageNet indicates that the degradation on ImageNet-AdvBN is not solely caused by the reconstruction loss due to the autoencoders we use. \subsection{Additional Example Images} We include more images from ImageNet-AdvBN-VGG in this section. Example images in Figure~\ref{fig:examples} are randomly chosen. We do not include the ImageNet-AdvBN-ResNet, because the resulting images are mostly in extreme contrast with small textures that are hard to observe. It is possible that features output from ResNet based encoders are more sensitive to AdvBN perturbations; another explanation is that the features we extract from ResNet-50 are relatively shallow features compared to their VGG counterparts. \begin{figure}[!ht] \centering \resizebox{\linewidth}{!}{ \includegraphics{figs/examples.pdf} } \caption{More example images. For each pair of adjacent columns, original versions are on the left, ImageNet-AdvBN-VGG is on the right.} \label{fig:examples} \end{figure} \section{Runtime Analysis} \subsection{Runtime of training with AdvBN} We evaluate the training time of our method on a workstation with 4 GeForce RTX 2080 Ti GPUs. We use the default settings for AdvBN on ResNet-50: an AdvBN module after the \texttt{conv2\_3} layer, a fixed AutoAugment policy, and 20 epochs of fine-tuning with 6-step PGD inside the AdvBN module. Fine-tuning is conducted on the ImageNet training set, containing 1.3 million images. Training in this setting takes approximately 40 hours with batchsize set to 256 . \subsection{Comparison with other methods concerning training budget} We use the same infrastructure above to evaluate the training time of other ResNet-50 models that appear in Table~\ref{crossDomain}. Training code for all other methods are obtained from official repository. For all methods, we use a batch size of $128$, because augmix\citep{hendrycks2019augmix} cannot run with a batch size of $256$ on our workstation due to limited GPU memory. The number of processes in the dataloader is set to be 16. The speed values in Table~\ref{speed} are averaged over 100 iterations. The estimated training duration is calculated by multiplying the speed and corresponding total number of iterations. Time spent on evaluation after each epoch is not considered in this estimation. \input{tables/speed} Training with AdvBN takes a long time per iteration because each iteration contains 6 PGD steps. The SIN~\citep{geirhos2018imagenet} runtime speed is estimated based on standard training, since the model architectures and training procedures of these two methods are the same, except that SIN is trained for half the epochs but twice the data and thus twice the number of iterations per epoch. Training SIN requires additional access to Stylized-ImageNet as training data, which takes 134GB disk space; the time for generating the Stylized-ImageNet dataset and the extra storage cost are not considered in Table~\ref{speed}. \section{Inference using models trained with AdvBN} Models containing Batchnorm layers will have two set of BN statistics in deeper layers that have been fine-tuned by AdvBN because we use auxiliary BNs introduced by \citep{xie2019adversarial} for propagating adversarial features crafted by the AdvBN module. During evaluation, we can choose either of the BN statistics to normalize features. The results we report in previous sections with regard to ImageNet, ImageNet-C and ImageNet-Instagram are obtained by using BN statistics corresponding to original features. We only use auxiliary BNs, which keep the batch statistics of adversarial features, to test performance on Stylized-ImageNet in Table~\ref{crossDomain}. We also use auxiliary BNs for evaluating performances on ImageNet-AdvBN and Reconstructed ImageNet in Table~\ref{a:advbn}. \section{Background} \subsection{Feature normalization} Feature normalization is an important component of modern neural networks that stabilizes training and improves model generalization. Let $f \in \mathbb{R}^{N \times C \times H \times W}$ denote feature maps output by a layer, where $N$ is the batch size, $C$ is the number of channels, and $H$ and $W$ represent the height and width of the feature maps, respectively. Different normalization methods compute the mean, $\mu$, and standard deviation, $\sigma$, over different dimensions of the feature maps. They use the derived feature statistics, often along with learned multiplicative and additive parameters, to produce normalized features, $f'$: \begin{equation} f' = \gamma\cdot\frac{f-\mu(f)}{\sigma(f)}+\beta, \end{equation} where $\gamma$ and $\beta$ are learnable parameters which re-scale and shift normalized features. For example, Batch Normalization (BN)~\citep{ioffe2015batch} estimates feature statistics along the $N, H, W$ dimensions. On the other hand, Instance Normalization (IN)~\citep{ulyanov2016instance} computes $\mu$ and $\sigma$ for each individual sample in the batch and only normalizes across the $H$ and $W$ dimensions. Although feature normalization was originally proposed to accelerate the training process~\citep{bjorck2018understanding}, previous work~\citep{huang2017arbitrary, li2016revisiting} has shown that feature statistics effectively capture information concerning the appearance of images. Motivated by this observation, we impose uncertainty on these statistics during training in order to obtain models that are less sensitive to non-semantic characteristics, thus generalizing to images with different appearances. \subsection{Adversarial training} Untargeted adversarial examples are generated by maximizing classification loss with respect to the input. One popular method, projected gradient descent (PGD), involves performing gradient ascent in the signed gradient direction and projecting the perturbation in order to enforce an $\ell_{\infty}$-norm constraint \citep{madry2017towards}. Adversarial training aims to solve the saddlepoint optimization problem, \begin{align} \min_{\theta}\mathbb{E}_{(X,y)\sim\mathcal{D}}\left[ \max_{\|\mathbf{\delta}\|_{p}<\epsilon}\mathcal{L}(g_{\theta}(X+\mathbf{\delta}),y) \right],\end{align} where $g_\theta$ is a model with parameter vector $\theta$, $X,y$ is a clean input and the corresponding label drawn from distribution $\mathcal{D}$, and $\mathcal{L}$ denotes cross-entropy loss. Adversarial training solves this problem by iteratively sampling a batch of data, perturbing the batch adversarially, and performing a parameter update on the new adversarial batch \citep{madry2017towards}. We harness adversarial training in order to create models robust to distributional shifts rather than the standard pixel-wise adversarial attacks. \iffalse \begin{algorithm}[h] \KwIn{Input \(x\), label \(y\), network \(g \), \(\ell_{\infty}\) bound \(\epsilon\), and step size \(\tau\);\\} \KwResult{Adversarial example \(x_adv\);\\ } Initialize \(\delta \sim \mathcal{U}(-\epsilon,\epsilon)\);\\ \For{adversarial step = 1, \dots, m}{ \(\delta \leftarrow \delta + \tau \cdot sign(\nabla_{\delta} \mathcal{L}(g(x+\delta), y))\);\\ \(\delta \leftarrow \text{clip}(\delta, -\epsilon, \epsilon)\);\\ } \KwRet{\(x_adv = x+\delta\)} \caption{PGD attack} \label{algo:PGD} \end{algorithm} \fi \section{Experiments} \subsection{Implementation} Our method begins with a torchvision ImageNet pre-trained ResNet-50~\citep{resnet}. We insert the AdvBN module at the end of the 2\textsuperscript{nd} convolutional stage. The model is fine-tuned following Algorithm~\ref{algo:adv1} for 20 epochs. The learning rate starts at 0.001 and decreases by a factor of 10 after 10 epochs with a batch size of 256. We use SGD with momentum 0.9 and weight decay coefficient $10^{-4}$. We augment inputs with a fixed AutoAugment~\citep{cubuk2019autoaugment} policy. Adversarial parameters are \(\tau=0.2\) and \(\epsilon=1.1\) with 6 repeats. \subsection{Generalization to ImageNet Variants} \paragraph{Datasets.} We compare our method to other methods designed to produce classification networks which generalize better. The datasets we consider are ImageNet \citep{imagenet_cvpr09} and its variants: \begin{itemize} \item \textbf{ImageNet-C}~\citep{hendrycks2019benchmarking} contains distorted images with 15 categories of common image corruption applied, each with 5 levels of severity. Performance on this dataset is measured by mean Corruption Error (mCE), the average classification error over all 75 combinations of corruption type and severity level, weighted by their difficulty. \item \textbf{ImageNet-Instagram}~\citep{instagram} is composed of ImageNet images filtered with a total of 20 different Instagram filters. This dataset contains 20 versions of each ImageNet image, each with a different filter applied. \item \textbf{Stylized-ImageNet}~\citep{geirhos2018imagenet} consists of images from the ImageNet dataset, each stylized using AdaIN~\citep{huang2017arbitrary} with a randomly selected painting. Textures and colors of images in this dataset differ heavily from the originals. \end{itemize} \paragraph{Models.} Our baseline model is the publicly available torchvision ResNet-50 pre-trained on ImageNet, denoted as ``Standard'' in Table~\ref{crossDomain}. All models we compare to, aside from SIN \citep{geirhos2018imagenet}, are not trained on any of the ImageNet variants that are used for evaluation. The PGD model is adversarially trained with the PGD attack on inputs and is provided by \citet{madrylab}. MoEx~\citep{li2020feature} changes feature moments inside networks but not in an adversarial manner. IBN-Net~\citep{ibnnet} improves the generalization of networks by combining batch normalization and instance normalization. AugMix~\citep{hendrycks2019augmix} is a data augmentation method that solves the distributional mismatch between training and testing data and increases classification robustness. SIN is a network trained on both Stylized ImageNet and ImageNet. We do not measure the accuracy of SIN on Stylized-ImageNet since it acquires knowledge of the target domain during training. Note that all models we use in our comparisons are the original versions released by the authors of the original work. \input{tables/crossDomain} \paragraph{Results.} As shown in Table~\ref{crossDomain}, the performance of baseline model significantly degrades on all three ImageNet variants, highlighting the brittleness of this high performance classification model when tested on novel distributions. Fine-tuning with AdvBN, on the other hand, substantially improves the performance of the standard ResNet-50 model. In particular, we achieve an 8.1\% accuracy gain on ImageNet-C through fine-tuning with AdvBN. On Stylized-ImageNet and ImageNet-Instagram, our model not only vastly improves upon the baseline model but also achieves the best performance among all methods with which we compare. The consistent performance boost across all three benchmarks demonstrates that adversarial training with AdvBN can effectively enhance robustness against various distributional shifts. Note that this AdvBN model has additional auxiliary BN layers. See Appendix C for details concerning inference. \subsection{Ablation Study} \paragraph{Where should the AdvBN module be placed within a network?} The proposed AdvBN module can be inserted after any layer in a deep network. In this part, we try inserting the AdvBN at deeper layers, \emph{i.e.}\@\xspace, $ \texttt{conv3\_4}$ and $\texttt{conv4\_6}$. From the results in Table~\ref{abaltion}, we observe that $\texttt{conv4\_6}$ yields the worst performance among all three ImageNet variants, indicating that using AdvBN at deeper layers is not as helpful as at shallower layers. We hypothesize two possible explanations for this phenomenon: (1) there are fewer trainable parameters when only very deep layers are fine-tuned; (2) features are more abstract in deeper layers, and perturbing the mean and standard deviation of high-level features can lead to extremely chaotic feature representations that are harmful for classification. \input{tables/ablation} \paragraph{Adversarial strength.} The strength of the adversarial attack in the adversarial training framework has a major impact on model performance \citep{madry2017towards}. We test a range of PGD parameters to demonstrate how the strength of AdvBN affects model performance. We measure strength by the perturbation bound $\epsilon$, where we fix $\tau$ to be 0.2 for all settings, and change the number of repeats for different bounds. The number of repeats $n$ for each $\epsilon$ is set to be $n = [\epsilon / 0.2] +1$. Results concerning the impact of adversarial strength are listed in Table~\ref{abaltion}. \paragraph{Multiplicative vs. additive perturbations.} We originally chose a multiplicative noise so that a single perturbation bound can be applied to various layers and architectures regardless of the range in which feature values lie. To adjust the perturbation bound for an additive noise for each batch of feature, we compute maximum mean and standard deviation values across channels, $\mu_{max}$ and $\sigma_{max}$. Then, in the projection step of the PGD attack, we project perturbations to the mean and standard deviation into the ranges $(-\epsilon \cdot \mu_{max}, \epsilon \cdot \mu_{max})$ and $(-\epsilon \cdot \sigma_{max}, \epsilon \cdot \sigma_{max})$, respectively. The model is denoted ``additive $\delta$'' in Table~\ref{abaltion}. This variant results in slightly degraded accuracy on each dataset. \paragraph{Data augmentation.} AdvBN performing in feature space can easily be combined with input space data augmentation. To determine what portion of the improvements we observed can be credited to AdvBN, we fine-tune a pre-trained ResNet-50 following the same routine as before but without the AdvBN module, adopting the same fixed AutoAugment policy along with all other hyperparameters. This method is denoted by AutoAugment$^{\ast}$ in Table~\ref{abaltion}. We see that fine-tuning with AutoAugment alone does not result in nearly as much improvement as the combined method on all datasets we consider; even performance on the original ImageNet dataset benefits from the AdvBN module. \subsection{Feature divergence analysis} We compare the features extracted by our network to those of a standard ResNet-50 trained on ImageNet. Following \citet{ibnnet}, we model features from each channel using a normal distribution with the same mean and standard deviation, and we compute the symmetric KL divergence between the corresponding distributions on the two datasets ($A$ and $B$). For two sets of deep features, $F_A$ and $F_B$, each with $C$ channels, the divergence $D(F_A || F_B)$ is computed using the formula, \begin{equation} \begin{array}{cc} D(F_A || F_B) = \frac{1}{C}\sum^{C}_{i=1}(KL(F^i_A||F^i_B) + KL(F^i_B || F^i_A)),\\ &\\ KL(F^i_A || F^i_B) = \log\frac{\sigma^i_B}{\sigma^i_A} + \frac{\sigma_A^{i^2} + (\mu^i_A - \mu^i_B)^2}{2\sigma_B^{i^2}} - \frac{1}{2}, \end{array} \end{equation} where $F^i$ denotes the features of $i$-th channel with mean $\mu^i$ and standard deviation $\sigma^i$. In Figure~\ref{fig:kldiv}, we compare the baseline model with our own on two pairs of datasets in the fine-tuned layers. Since ImageNet-Instagram contains 20 filter versions, we use the ``Toaster'' filter found in \citep{instagram} to cause the sharpest drop in classification performance. We find that the feature divergence in our network trained with AdvBN is substantially smaller on all layers in the fine-tuned subnetwork. In other words, the distribution of deep features corresponding to shifted domains is very similar to the distribution of deep features corresponding to standard ImageNet data. The small divergence between feature representations explains the effectiveness of AdvBN from a different angle and explains why our model generalizes well across datasets. \begin{figure}[!ht] \centering \resizebox{\linewidth}{!}{ \includegraphics{figs/feature_divergence.pdf} } \caption{\textbf{Feature divergence between pairs of datasets using features extracted by AdvBN and a standard ResNet50}.} \label{fig:kldiv} \end{figure} \subsection{Generalization on Semantic Segmentation} We now evaluate AdvBN in the context of semantic segmentation. We train a ResNet-50 based network with dilated convolutions~\citep{dilatedconv} on Cityscapes~\citep{Cordts2016Cityscapes} as our baseline model following the training protocol in~\citet{ibnnet}. Cityscapes comprises urban street scenes from various cities and contains 2975 images with fine annotations for training and 500 images for validation. To evaluate generalizability, we test the performance of the model on another dataset, GTA5~\citep{GTA5}. The GTA5 dataset consists of synthetic images extracted from computer games, which have similar street scene content as Cityscapes and compatible label categories. The GTA5 validation set we use contains 6382 densely annotated images. \input{tables/cityscapes} To apply AdvBN, we fine-tune the baseline model with AdvBN plugged in after layer \texttt{conv2\_3} on Cityscapes for 20 epochs with adversarial training parameters $\tau = 0.15$, $\epsilon=0.4$, and 4 repeats. In table~\ref{seg-cityscapes}, we observe a performance gain of 8.2\% in mean IoU on the GTA5 dataset compared to the baseline model. The pixel accuracy also improves by 11.3\%. Numbers on the left side of arrows denote performance on Cityscapes, and numbers on the right side of arrows denote performance on the GTA5 dataset. \section{Introduction} Robust optimization for neural networks has been a major focus of recent research. A mainstream approach to reducing the brittleness of classifiers is {\em adversarial training}, which solves a min-max optimization problem in which an adversary makes perturbations to images to degrade network performance, while the network adapts its parameters to resist degradation \citep{goodfellow2014explaining, kurakin2016adversarial, madry2017towards}. The result is a hardened network that is no longer brittle to small perturbations to input pixels. While adversarial training makes networks robust to adversarial perturbations, it does not address other forms of brittleness that plague vision systems. For example, shifts in image style, lighting, color mapping, and domain shifts can still severely degrade the performance of neural networks \citep{hendrycks2019benchmarking}. We propose adapting adversarial training to make neural networks robust to changes in image style and appearance, rather than small perturbations at the pixel level. We formulate a min-max game in which an adversary chooses {\em adversarial feature statistics}, and network parameters are then updated to resist these changes in feature space that correspond to appearance differences of input images. This game is played until the network is robust to a variety of domain shifts in image space including texture, color, brightness, \emph{etc}\@\xspace. The idea of adversarial feature statistics is inspired by the observation that the mean and variance of features maps encode style information, and thus, they enable the transfer of style information from a source image to a target image through normalization \citep{huang2017arbitrary,ulyanov2016instance}. Unlike standard approaches that rely on feature statistics from auxiliary images to define an image style, we use adversarial optimization of feature statistics to prepare classifiers for the worst-case style that they might encounter. We propose training with {\em Adversarial Batch Normalization} (AdvBN) layers. Before each gradient update, the AdvBN layers perform an adversarial feature shift by re-normalizing with the most damaging mean and variance. By using these layers in a robust optimization framework, we create networks which are resistant to any domain shift caused by feature statistics shift. An advantage of this method is that it does not require additional auxiliary data from new domains. We show that robust training with AdvBN layers hardens classifiers against changes in image appearance and style using a range of vision tasks including Stylized-ImageNet~\citep{geirhos2018imagenet} and ImageNet-Instagram~\citep{instagram}. \section{Related work} \paragraph{Adversarial training} Adversarial training and its variants \citep{goldblum2019adversarially2, madry2017towards, shafahi2019adversarial} have been widely studied for producing models that are robust to adversarial examples \citep{moosavi2016deepfool, intriguing}. Recent work considers adversarial training as data augmentation \citep{odds2019accuracy}. \citet{xie2019adversarial} finds that deep features corresponding to adversarial examples have different mean and standard deviation than those corresponding to natural images. This work takes advantage of the distributional discrepancy to improve performance on non-adversarial data. Our work also adopts the adversarial training framework to make models robust against other kinds of perturbations, but instead of crafting adversarial examples in image space, we craft adversarial feature distributions by perturbing feature statistics. \paragraph{Robustness to distributional shifts} While extensive effort has been made to improve the robustness of classifiers to adversarial examples, there are other kinds of robustness that deep neural networks must address in order for them to be reliable. Corrupted images and new domains pose major challenges to networks with standard training~\citep{geirhos2018imagenet, hendrycks2019benchmarking, instagram}. Performance degradation on these images can be attributed to shifts in data distributions \citep{distribution}. In order to produce networks which generalize well, one common practice is to perform data augmentation \citep{cubuk2019autoaugment, hendrycks2019augmix, yun2019cutmix}. However, the benefits of data augmentation are largely limited by the types of augmentations used during training \citep{geirhos2018generalisation}. Feature space augmentation \citep{li2020feature} replaces feature statistics corresponding to one sample with ones corresponding to another sample. Our work can be also considered as feature space augmentation, we instead consider a worst-case scenario in the context of feature space distributional shifts by adopting the adversarial training framework.
{'timestamp': '2020-09-23T02:02:04', 'yymm': '2009', 'arxiv_id': '2009.08965', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08965'}
arxiv
\section{Introduction} As neural networks are being adopted to solve real-world problems, while some parts of the network may be easy to develop, other unknown aspects such as hyperparameters, have no clear method of derivation. Ongoing research focuses on developing new network architectures and training methods. When developing neural networks, the question at hand is how to set the hyperparameter values to maximize results and set the training configuration. For network architecture design, important hyperparameters include the type of network, the number of layers, the number of units per layer, and unit type. For training configurations, important hyperparameters include learning algorithm, learning rate, and dropout ratio. All these hyperparameters interact with each other and affect the performance of neural networks. This interaction between hyperparameters can be referred to as epistasis. Thus they need to be tuned simultaneously to get optimum results.\\ The motivation behind this research is to replace tedious manual tuning of hyperparameters with an automatic method performed by computers. Current methods of optimization are limited to trivial methods like Grid search. Grid search is a simple method for hyperparameter optimization. However, as the number of hyperparameters increases, Grid search becomes time consuming and computationally taxing. This is because the number of lattice points increases in an exponential way with an increase in the number of hyperparameters \cite{qin2017evolution}. For example, if there are ten hyperparameters to be tuned and we only try five values for each parameter, and this alone requires more than 9 Million evaluations: \begin{math}5^{10} = 9765625\end{math}. For this reason, the grid search is not feasible for certain applications. To solve this, we look to a GA for a higher-performing and less computationally taxing solution. The use of a GA for neural network hyperparameter optimization has been explored previously in \cite{suganuma2017genetic, moriya2018evolution}. \\ We present an empirical study of GAs for neural network models in machine translation of natural language specifically Japanese to English. We describe the experiment setup in Section 2, our GA method in Section 3, and results in Section 4. The preliminary findings suggest that a simple GA encoding has the potential to find optimum network architectures compared to a random search baseline. \section{Experimental Setup} Genetic Algorithms (GA) are a class of optimization methods where each individual, a neural network, represents a solution to the optimization problem and the population is evolved in hopes of generating good solutions. In our case, each individual represents the hyperparameters of a neural machine translation system, and our goal is to find hyperparameters that will lead to good systems. The defining factor when measuring an individual's fitness is its BLEU score, a measurement of the individual's translation quality which is dependent on the individuals hyperparameters. The data set used for experimentation was limited to 150 individuals each consisting of 6 hyperparameters. We use a benchmark data set provided by \cite{zhang2020benchmarks} where a grid of hyperparameter settings and the resulting model BLEU scores are pre-computed for the purpose of reproducible and efficient hyperparameter optimization experiments. In particular, we use the Japanese-to-English data set which consists of various kinds of Transformer models (described later) trained on the WMT2019 Ro-bust Task \cite{li-EtAl:2019:WMT1}, with BLEU scores ranging from 9 to 16.\vspace{6pt} Every test was done over three trials each consisting of 1000 optimization iterations. One iteration involves a process, elaborated below, to arrive at the target BLEU score of 16. The higher the BLEU score the better. While testing, both the GA and the Baseline (random search) received the same initial population of 5, 10, 15, 20, or 25 individuals. Throughout experimentation, the goal was to arrive at one individual with a BLEU score, fitness, of 16 or higher. The fitness is a measure of the likelihood of the individual remaining in the population.\vspace{6pt} A practical limitation of the data set includes a possibility that a combination of hyperparameters found by the GA may not be represented in the data set. If the combination is non-existent, we assign a fitness value of 0 to that respective individual. This is imperative as we do not want a non-existant individual remaining in the population. By assigning the individual a fitness value of 0, it is guaranteed be replaced in the next breeding cycle. Furthermore, the possibility of two individuals with a fitness 0 is impossible as the population starts with individuals with representation in the data set. This is a benefit of an individual based measurement rather than a generational measure. Additionally, during experimentation, individuals were not added to the population if they have already been in the population, or if their genes exist in the current population. In traditional metrics, the entire current population is replaced by a new generation consisting of new offspring. In our implementation, only one offspring is generated, and that replaces the weakest individual. The performance of the GA and baseline algorithm is represented with a value based on the total amount of individuals added. This value increases every time an individual is added to the population. The performance of both algorithms is determined by averaging the performance value measured from all the iterations. An iteration consists of one optimization cycle. The performance value measured in individuals per iteration is displayed in the tables in section 4. \section{Method} The GA system used in this experiment is based on the natural selection process theorized by Darwin. This theory states that the stronger/fitter individuals survive while the weaker individuals do not. Thus over time, when the surviving stronger individuals reproduce, you get a population that as a whole carries genes that make them more resilient. However, Darwin only theorized this process in the natural world. The idea for using a GA in optimization problems and machine learning was thought of by Goldberg and Holland and expressed in \cite{goldberg1988genetic}. Throughout this experiment, we simulate their logic for machine translation neural network optimization. We begin with an initial population that "reproduces" until we get a group of individuals that collectively hold hyperparameters that perform better and one individual that is the "fittest" and meets the BLEU score target. The parts of the algorithm are represented through 3 objects: Individuals, Populations, and the Genetic Algorithm itself. The GA and Baseline algorithm were developed in the Python programming language. The GA and Baseline algorithm (random), elaborated later, are compared via an evaluator. This hierarchy, explained in \cite{whitley1994genetic}, and is represented visually below:\vspace{6pt} \begin{figure}[ht] \begin{center} \begin{forest} [Evaluator [Genetic Algorithm [Population [Individuals] ] ] [Random Selection [Population [Individuals] ] ] ] \end{forest} \caption*{Figure 1: Hierarchy of the Objects in Experimentation} \end{center} \end{figure} \subsection{Individual} Every individual consists of two defining characteristics: 1) the "chromosome", consisting of 6 hyperparameters, and 2) the fitness score, which is the BLEU value. An individual's chromosome can look like [10000.0, 4.0, 512.0, 1024.0, 8.0, 0.0006]. The fitness of the machine translation neural networks (a.k.a individual) is defined as the BLEU score or how well the neural network can translate from Japanese to English. BLEU score is measured by an algorithm for evaluating the quality of translation performed by the machine to that performed by a human. The BLEU score is calculated via a simple proportion. The two translations, the human translation, referred to as reference translation, and the translation done by the machine, the candidate translation. To compute, one counts up the number of candidate translation words, unigrams, that occur in any reference translation and the total number of words found in the reference translation \cite{papineni2002bleu}. Once we get the two values, we divide them to get a precision component of the BLEU score.\vspace{6pt} However, simple proportions are not the only thing used during calculation of BLEU score. Another property of BLEU score worth noting is the use of a brevity penalty, a penalty based on length. Since BLEU is a precision based method, the brevity penalty assures that a system does not only translate fragments of the test set of which it is confident, resulting in high precision \cite{koehn2004statistical}. Is has become common practice to include a word penalty component dependant on length of the phrase for translation. This is especially relevant for the BLEU score that harshly penalizes translation output that is too short. Finally, in this study, we use alternate notation for readability. A BLEU score of 0.289 is reported as a percent 28.9\%.\\\\\\\\ \begin{figure}[ht] \centering \begin{tabular}{ |l | c |} \hline \textbf{\# BPE subword units} (1k) & 10, 30, 50\\ \textbf{\# encoder/decoder layers} & 2, 4\\ \textbf{\# word embedding dimensions} & 256, 512, 1024 \\ \textbf{\# hidden units} & 1024, 2048 \\ \textbf{\# attention heads} & 8, 16\\ \textbf{initial learning rate} ($10^{-4}$) &3, 6, 10\\ \hline \end{tabular} \caption*{Table 1: Hyperparameter search space for the Tranformer NMT systems} \label{tab:datasets_hyps} \end{figure} Amongst the 150 individuals there are 7 target BLEU scores above the 16 goal: 16.04, 16.09, 16.02, 16.41, 16.03, 16.13, and 16.21. Ranges of hyperparameter values, referred to as Genes, are as follows: Fitness(9.86 - 16.41), Gene 1 (10,000, 30,000, or 50,000), Gene 2 (2.0 or 4.0), Gene 3 (256.0, 512.0, or 1024.0), Gene 4 (1024.0 or 2048.0), Gene 5 (8.0 or 16.0), and Gene 6 (0.001, 0.0003, or 0.0006). This information is shown above.\\ Additionally, a convolutional or recurrent model was not implemented for these translation networks. The networks in this study implemented transformers. On top of higher translation quality, the transformers requires less computation to train and are a much better fit for modern machine learning hardware, speeding up the training process immensely. In regards to the less computational power needed, the ease of training of transformers can be accredited to its lack of growth based on amount of words \cite{dehghani2018universal}. Specifically, a transformer is not recurrent meaning it does not need the translation of the previous word to translate the next. For example lets take the example a translation for German to English. Let's use the German sentence, Das Haus ist groß, meaning the house is big. In a Recurrent Neural Network (RNN), the network identifies das and the, and then uses that as a reference for the next word to translate Haus to house, etc. However, in a Transformer, we can treat each word as a separate object and for translation rather than the translation of the previous word, it uses the embedding value of all of the other words. Because they are treated independently, we can have the translation operation occur in parallel. So in this example every word das, Haus, ist, groß are all vectored and use the other words' embeddings. Additionally, a notable characteristic of a transformer is its use of an attention mechanism. The Attention mechanism allows for the network to direct its focus, and it pays greater attention to certain factors when processing the data resulting in a higher performing network. For these three main reasons, the lack of recurrence, the use of an attention mechanism, and the ability for parallel computation, transformers are a preferred choice as a network architecture in Machine Translation. The hyperparameters searched for in our Transformer models are shown in Figure 2. \subsection{Population} The population of individuals consist of three instance variables: the population itself, consisting of an initial x individuals implemented through an array, and two individuals that resemble the fittest and second fittest individuals in the population. For a population of 5 individuals it will look something like [Individual 1, Individual 2, Individual 3, Individual 4, Individual 5]. Examples of the fittest and second fittest individual follow: Fittest: Individual 1 can be represented as the fitness with BLEU score of 16.41, and second fittest: Individual 2 can be represented as second fitness with BLEU score of 16.04. For experimentation, however the algorithm stopped when the goal of 16 or above is reached, so the situation above would not occur. \subsection{Genetic Algorithm (GA)} In a broad sense, a genetic algorithm is any population-based model that uses various operators to generate new sample points. The GA system used during experimentation abides to most conventional characteristics of GA: a population, individuals, selection/mutation/crossover operations, etc. Our GA is comprised of three objects: the population, a list of all individuals, and an individual that acts as the child, referred as place holder. The population holds the individuals, the list of all individuals allows us to make sure that the child is not a repeated individual, and the individual allows for an object to store information on the offspring. The following describes the structure of the GA: First, an array of individuals with only the current population. The current population is defined as the population before the selection process, elaborated below. Second, it will contain a List of all the individuals that have been introduced to the population. We iterate through this list every time before adding an individual to make sure that the new individual, or placeholder, has not been introduced before. Place holder is an individual that is initially set to have values of 0: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]. During the crossover process, elaborated later, all the genes are changed to that of the offspring. Our implementation, however, differs from convention in two main ways: our implementation includes an Integer Representation rather than bit value, and an individual based measure for optimization rather than a generational measure. At the end of the process, a value that represents the total number of individuals added to the population added to the initial population size is returned.\vspace{6pt} \begin{center} The process the Genetic Algorithm goes through is depicted below: \begin{tikzpicture}[node distance=1.5cm] \node (io) [rectangle] {Genetic Algorithm}; \node (pro1) [rectangle, below of=io] {Selection}; \node (dec1) [rectangle, below of=pro1] {Crossover}; \node (pro2) [rectangle, below of=dec1] {Mutation}; \node (dec2) [rectangle, below of=pro2] {Check Validity of Individual}; \node (pro3) [rectangle, below of=dec2] {Add Individual}; \node (dec3) [rectangle, right of=dec1, xshift=2cm,yshift=-.75cm] {Not Valid}; \node (dec4) [rectangle, below of=pro3] {Check if target is reached}; \node (pro4) [rectangle, below of=dec4] {Optimization Complete}; \node (dec5) [rectangle, left of=pro2, xshift=-3cm,yshift=-.75cm] {Target not Reached}; \draw [->] (io) -- (pro1); \draw [->] (pro1) -- (dec1); \draw [->] (dec1) -- (pro2); \draw [->] (pro2) -- (dec2); \draw [->] (dec2) -- node {Valid} (pro3); \draw [->] (dec4) -- node {Target Reached} (pro4); \draw [->] (dec3) |- (pro1); \draw [->] (dec5) |- (pro1); \draw [->] (dec3) |- (pro1); \draw [-] (dec4) -| (dec5); \draw [->] (pro3) -- (dec4); \draw [-] (dec2) -| (dec3); \end{tikzpicture} \\The processes used during the GA, selection, crossover, and mutation, and their functionalities are elaborated on below. \end{center} \subsubsection{Selection} The selection process allowed for the GA to select two parents to mate to form a new offspring. The two parents are selected by weighted probability, proportional to their fitness. For example, lets take an initial population of 5 individuals with fitness values 10, 25, 15, 5, 45. The probability of selecting an individual is calculated by finding the sum of the fitness values, in this example 100, divided by the individuals fitness. Individual 1 has a 10\% of being selected, 10/100, Individual 2 has a 25\% chance, 25/100, etc. After repeating this process we get a list of percentages 10\%, 25\% , 15\% , 5\% , 45\%. As you can see, the percentages will always add up to 100. These values are then used to get an array with range values for each individual. In the aforementioned example, a list will look like [10, 35, 50, 55, 100]. These values are determined by adding the percentage value of an individual to that of all the previous individuals. From here, we select a random integer value from 0 to 100. This value is then correlated to an individual. For the above example with a population size of 5 Individual 1 is selected if the random value is less than 10, Individual 2 is selected if the value is greater than 10 and less than 35, Individual 3 if the value is greater than 50 and less than 55, etc. This approach is optimal as its adaptable based of size of population, and gives an accurate weighted representation. \subsubsection{Crossover} The crossover process simulates the breeding part of the natural selection process. Following selection, the selected two individuals are used to create an offspring. Initially, a random gene in the chromosome is selected as the "crossover point". Up to that point genes of the fittest, Parent 1 in Figure 2, are selected, and from that point to the end, genes of the second fittest, Parent 2 in Figure 2, are added. For a cross over point of 2, the example below depicts the cross over process. \begin{figure}[ht] \begin{center} \includegraphics[width=1\textwidth]{Crossover_Image.png} \caption*{Figure 2: Visual depicting the Crossover process} \end{center} \end{figure} \\ From here we now need to assign a fitness a value to the individual. Later we explain how we derived the 7 lists, for now just understand that we have 7 lists, one list with all potential values for each hyperparameter respectively, and another list for every fitness a value. These lists are ordered by individuals. For example the first index in all 7 lists correspond to individual one, the second index to individual 2, etc. We initially iterate through the entire first list, an array containing all values for the 150 individuals ordered, until we arrive at a match. In the example above this can be seen when we first arrive at the value of 10000. Then we store the index of the 10000 and see if that same index in list 2,3,4 etc also match the individuals gene. If all 6 genes correlate to values at one index, we assign a fitness value from the fitness list at the same index. Though an inefficient operator for assigning fitness, this approach makes the mutation operator easier. \subsubsection{Mutation} During the experiment, a mutation rate of 1/8, 12.5\%, was selected. When mutation occurs, an individual in the population is randomly selected, and one gene of that individual is also randomly selected. That gene is then given a new random value from the data set. Mutation process excludes the weakest Individual from being selected as that Individual would be replaced. If the weakest individual were not excluded, it would be replaced in during the addition of the offspring making the mutation irrelevant. Below is a mutation example with the mutation occurring on Gene 5. As shown, the mutation is resulting in an increased fitness. \begin{figure}[ht] \begin{center} \includegraphics[width=1\textwidth]{Mutation_Image.png} \caption*{Figure 3: Visual depicting the Mutation process} \end{center} \end{figure} \subsection{Evaluator} All of the below results are measured using an average of individuals needed to be added over 1000 iterations. Each iteration consists of a process of going through optimization until a target score of 16 is reached. As previously stated, both algorithms return a value that represents the number of individuals that were added to reach the goal. However, before returning the values, we add the initial population size to account for individuals in the initial population. These values are then stored in two lists one for each algorithm, one list for the GA and another for the Baseline algorithm. At the very of the end of the evaluator the average of both lists is used to arrive at performance measure of the algorithms. \subsection{Baseline (Comparison Algorithm)} As a measure of the quality of the GA, a baseline algorithm that optimizes by randomly selecting hyperparameters was used to compare. The baseline algorithm selected a random index value from 0 to one less than the size of the data set. From this, an individual is made with values from that index in every list from the initialization of data points, elaborated below. At the end of the process, a value that represents the total number of individuals added to the population added to the initial population size is returned. \begin{center} The process the Baseline Algorithm goes through is depicted below: \begin{tikzpicture}[node distance=1.5cm] \node (io) [rectangle] {Baseline Algorithm}; \node (pro1) [rectangle, below of=io] {Select Random Value}; \node (dec4) [rectangle, below of=pro1] {Get Individual that corresponds to the Random Value}; \node (dec1) [rectangle, below of=dec4] {Check Validity of Individual}; \node (pro2) [rectangle, below of=dec1] {Add Individual}; \node (dec2) [rectangle, right of=dec4, xshift=4.5cm] {Not Valid}; \node (pro3) [rectangle, below of=pro2] {Check if target is reached}; \node (dec3) [rectangle, below of=pro3] {Optimization Complete}; \node (pro4) [rectangle, left of=dec1, xshift=-5cm] {Target not Reached}; \draw [->] (io) -- (pro1); \draw [->] (pro1) -- (dec4); \draw [->] (dec4) -- (dec1); \draw [->] (dec1) -- node {Valid} (pro2); \draw [->] (pro2) -- (pro3); \draw [->] (pro3) -- node {Target Reached} (dec3); \draw [-] (dec1) -| (dec2); \draw [->] (dec2) |- (pro1); \draw [->] (pro3) -| (pro4); \draw [->] (pro4) |- (pro1); \end{tikzpicture} \end{center} \subsection{Initialization of Data Points} The initialization uses the python pandas library to create seven arrays that are representative of all possible Individual combinations. For example, all potential Gene 1 values are stored in an array. Similarly, there are arrays for the other genes and the fitness values. Additionally, these arrays store the fitnesses that are in order of fitness. Index 0 of all the lists correlate to the characteristics of individual 1, index 1 for individual 2, etc. These arrays are implemented to assign fitness values when a new off-springs are created, generate the initial population, and during the mutation operator. \section{Results} Every trial in the tables below consists of 1000 iterations. An iteration entails the repetition of the GA and Baseline processes, elaborated above, until the target goal is reached. Thus the average is calculated over an accumulative 3000 (per the tables below) iterations. We measure how long it takes for an algorithm to find the a good solution (i.e. $\ge 16$ BLEU), so the lower the better. \begin{center} \end{center} \begin{figure}[ht] \begin{center} \begin{tabular}{ |p{2.5cm}||p{2.5cm}|p{2.5cm}|p{2.5cm}| p{2.5cm}| } \hline \multicolumn{5}{|c|}{Genetic Algorithm's Results} \\ \hline Initial Population Size & Trial 1 (Average Number of Individuals Added)& Trial 2 (Average Number of Individuals Added)&Trial 3 (Average Number of Individuals Added) & Average\\ \hline 5&20.056&19.91&20.247&20.071\\ 10&21.011&20.739&20.392&20.714\\ 15&23.91&23.933&23.54&23.794\\ 20&27.555&28.019&27.267&27.614\\ 25&31.475&30.816&32.099&31.463\\ \hline \end{tabular} \end{center} \caption*{Table 2: Genetic Algorithm Results} \label{fig:1} \end{figure} \begin{figure}[ht] \begin{center} \begin{tabular}{ |p{2.5cm}||p{2.5cm}|p{2.5cm}|p{2.5cm}| p{2.5cm}| } \hline \multicolumn{5}{|c|}{Baseline Algorithm Results} \\ \hline Initial Population Size & Trial 1 (Average Number of Individuals Added)& Trial 2 (Average Number of Individuals Added)&Trial 3 (Average Number of Individuals Added)&Average\\ \hline 5&20.435&21.949&21.891&21.425\\ 10&23.513&22.545&23.29&23.116\\ 15&26.056&25.611&25.345&25.671\\ 20&28.332&28.292&28.365&28.330\\ 25&31.857&30.819&32.117&31.598\\ \hline \end{tabular} \end{center} \caption*{Table 3: Baseline Algorithm Results} \label{fig:2} \end{figure} \begin{figure}[h] \begin{center} \vspace{1em} \vspace{1em} \begin{tabular}{|p{4cm}||p{4cm}||p{4cm}|} \hline \multicolumn{3}{|c|}{Performance Difference} \\ \hline Initial Population Size & Winner & Difference in Performance\\ \hline 5 & Genetic Algorithm & 1.354\\ 10 & Genetic Algorithm & 2.402\\ 15 & Genetic Algorithm & 1.877\\ 20 & Genetic Algorithm & .716\\ 25 & Genetic Algorithm & .135\\ \hline \end{tabular} \end{center} \caption*{Table 4: Difference in Performance between GA and Baseline Algorithm:} \label{fig:3} \end{figure} \vspace{144pt}Using the average values, shown below, we can get a numerical representation of how much better a GA is. The average of the values showing difference in the performance shows that the GA can reach the desired goal with an average of 1.27 individuals fewer. The values in the table above were found by taking the average from the Baseline and subtracting the correlating GA value to find how many more individuals the Baseline needs on average. The value 1.27 was found by averaging all the values in the table below. Although saving 1.27 iterations is not large in the grander scheme of things, it is promising to see that GA gives consistent gains, implying that there are patterns to be exploited in the hyperparameter optimization process.\\\\\\\\\\ \section{Future Work} The study proves validity of a GA being implemented for hyperparameter optimization. Future work falls into three main categories: general, structural (changes how the system works), and behavioral changes (variations in individual methods implementations which can cause varying results). Additionally, there is the possibility for variations to be implemented for the Baseline algorithm. Lastly, we will explore results of the generational measure rather than the individual based. We realized that a plateua occurs as the population increases. This is due to the chance of picking individuals with lower fitness values increasing as the population increases for the GA. Therefore, as the initial population size increases, the GA's performance approaches that of the Baseline algorithm. \subsection{General Changes} When reflecting on the experiment as a whole, there are many key aspects that should be changed to further test the validity of a GA. One such example includes the range of Individuals represented in the data set. For example, in the data set above, many combinations of hyperparameters where not pre-trained so a fitness value was not assigned. This results in the GA iterating extra times due to non-existant individuals. Additionally, as previously mentioned, one goal of a GA is to outperform the grid search, a more primitive type of optimization. To further test the performance, a larger data set will need to be used to test the efficiency compared to grid search, a higher performing solution than random. Also, additional evaluation metrics can be used such as the populations average fitness and run time of the algorithm. Another potential change can be discounting individuals that are not represented. While impractical to have all combinations represented, the Baseline algorithm could not select a combination that was not represented while the GA could. For further comparison, not adding an individual to the population would decrease the individual count and enlarge the performance gap between the GA and Baseline Algorithm. \subsection{Structural Changes} An example of a structural change includes: Having mutation occur before selection. The mutation before selection can result in different weights of individuals during the selection process. This can result in varying fitness values which can ultimately change the entire optimization process. \subsection{Behavioral Changes} A glaring example of a behavioral change can be seen in how the individual that is being replaced is selected. Unlike Darwin's theory, the replaced individual was selected definitively during the experiment. The individual with the lowest fitness was replaced. Changing this to weighted probability similar to selecting the fittest and second fittest can affect the tuning process as hyperparameters work simultaneously. Two individuals with low fitness values can have a child that has a high fitness value due to the lack of direct correlation between individual hyperparameter values and BLEU score. Another example includes a two-point crossover operator rather than the one-point crossover currently implemented. A two-point cross over has the individuals exchange the genes that fall between these two points. \section{Conclusion} This work introduces an advanced GA for hyperparameter optimization and applies it to machine translation optimization. We demonstrate that optimization of hyperparameters via a GA can outperform a random selection of hyperparameters. Specifically, outperform is defined by the ability of the algorithm to arrive at the goal with less individuals added. Finally, we propose future research directions which are expected to provide additional gains in the efficacy of GAs. \section{Acknowledgements} I would like to thank and acknowledge Dr. Kevin Duh (JHU) for giving me the opportunity to pursue research with him. Thank you for the continuous support, patience, and motivation throughout the entire process. Additional thanks for the feedback and comments on this paper, and for the invaluable guidance regarding programming, resources for help, and much more.\\ Also, I am very appreciative of and grateful to my family and friends for their love, patience and support, without which this project would not have been possible.
{'timestamp': '2020-09-21T02:17:35', 'yymm': '2009', 'arxiv_id': '2009.08928', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08928'}
arxiv
\section{Introduction} \label{sec:intro} Quickest change detection (QCD) is the problem of sequentially detecting a change in the statistical properties of a signal. Given a sequence of independent and identically distributed (i.i.d.) observations $\{x_t:t\in\mathbb{N}\}$ with distribution $f$ up to an unknown change point $\nu$ and distribution $g\neq f$ after, the goal is to detect this change as quickly as possible, subject to false alarm constraints. Traditionally, applications of QCD can be found in manufacturing, in areas such as quality control\cite{lai1995sequential} where any change in the quality of products must be quickly detected. With the proliferation of low-cost sensors, QCD methods have also found applications in other areas such as fraud detection\cite{bolton02}, cognitive radio\cite{lai2008quickest} and power system line outage detection\cite{banerjee2014power}. As sensor and computing technology become increasingly ubiquitous and powerful, it becomes easier for an adversary to infer sensitive information, such as lifestyle preferences and location information, from available data. In many practical QCD applications, rather than having one distribution, the distribution that generates the signal in the post-change regime belongs to a finite set $G=\{g_1,\ldots,g_{|G|}\}$. In some applications, the distribution of some sensitive information $U$ may depend on the post-change distribution. Thus, knowing which distribution $g\in G$ generates the signal in the post-change regime may reveal some information about $U$. One example of such an application is occupancy detection. In an Internet of Things (IoT) based occupancy detection system, the occupancy sensor continuously measures attributes such as infrared radiation, temperature, humidity and carbon dioxide levels, to quickly detect when a room becomes occupied so that certain functions like turning on the air conditioning system can be automated. A baseline distribution can be used to model the fluctuation of these attributes with time when the room is empty. However, fluctuations in these attributes when the room is occupied can reveal the number of people and the activity conducted in the room, leading to privacy leakage if an adversary has access to the raw attribute signals. The goal of privacy-aware QCD is to sanitize the attribute signals so that the change from a vacant to an occupied room can still be detected, while preserving the privacy of the occupants in the room. In practice, we are unable to know the adversary's intent and hence would like to sanitize the signal so that the largest improvement an adversary can achieve, over all possible queries, is controlled. In other applications, $G$ may be partitioned into two sets, a private set $I_1$ and a public set $I_2$. We would like to sanitize the signal so that it is difficult for an adversary to deduce the distribution when a post-change distribution from the private set $I_1$ is generating the signal. On the other hand, we would like to retain the ability to deduce the distribution when a post-change distribution from the public set $I_2$ is generating the signal. One example of such an application is activity monitoring using wearables. In this application, we would like to quickly detect any change from a resting state to an active state. There are many possible active states such as walking, running, typing on a computer, and using a mobile phone. We would like to protect the privacy of some of these active states, like typing on a computer or using a mobile phone, while still being able to accurately track the other active states. Hence, the goal of privacy-aware QCD is to perform QCD while protecting the privacy of some active states and maintaining some distinguishability for the other active states. In this paper, we address the QCD problem with multiple post-change distributions while maintaining a privacy constraint for two different privacy metrics. For each of the privacy metrics, we propose a signal sanitization algorithm and a stopping time that is able to identify the critical change quickly while preserving a pre-determined level of privacy. \subsection{Related Work} In the QCD problem with a single post-change distribution, when the pre- and post-change distributions are fully specified and the change point $\nu$ is unknown but deterministic, the Cumulative Sum (CuSum) test, developed by Page \cite{page54}, is optimal as the false alarm rate goes to zero. For the case where the post-change distribution is not fully specified, the GLR CuSum test is asymptotically optimal for the case of finite multiple post-change distributions. For a comprehensive overview of the QCD problem, we refer the reader to \cite{tartakovsky2014sequential,poor2009quickest,LauTayVee:J19,LauTay:J19} and the references therein. In many applications, observations are obtained through measurements taken from several wireless sensors in the network and a fusion center decides if a change has taken place based on the information received from these sensors. Due to power and bandwidth constraints, the sensors are constrained to send messages belonging to a finite alphabet to the fusion center. This is an example in which the information for decision-making is \emph{decentralized}. The QCD problem with a decentralized framework was first introduced in \cite{veeravalli2001decentralized} and further studied in \cite{mei2005information,tartakovsky2008asymptotically,hadjiliadis2009one,banerjee2013decentralized} under various settings. All the aforementioned works on QCD do not consider any privacy constraints. Existing work on protecting or quantifying privacy can be divided into two main categories: \emph{data} privacy and \emph{inference} privacy\cite{WangTIT2016,SunTay:C17,SunTay:J20b}. Data privacy refers to the protection of the sensors' raw information from being obtained by the fusion center. In contrast, inference privacy refers to the protection from an adversary's attempt to deduce properties of an underlying distribution. Privacy metrics proposed to quantify data privacy include local differential privacy \cite{Dwork2006,xiong2016randomized,duchi2013local}, $k$-anonymity\cite{GupRao:J17} and homomorphic encryption \cite{Boneh2005}. On the other hand, privacy metrics proposed to quantify inference privacy include average information leakage\cite{salamatian2013hide,khouzani2019generalized}, mutual information privacy \cite{WangTIT2016,song2017tutorial}, information privacy\cite{CalFaw:C12,SunTay:C16,SunTayHe:J18,HeTayHua:J19,SunTay:J20a}, maximal leakage privacy\cite{issa2016operational,issa2017operational}, local differential privacy, hypothesis testing adversary privacy\cite{LiOechtering:J19}, and compressive privacy\cite{KunSPM2017,SonWanTay:J20}. We refer the reader to \cite{SunTay:J20b,WangTIT2016} for a comprehensive discussion on the relationship between data and inference privacy. In this paper, we use maximal leakage privacy, and sequential hypothesis testing adversary privacy, which is the sequential analog to the privacy metric proposed in \cite{LiOechtering:J19}, to quantify the gain which the adversary obtains through the observation of the signal. There are several works in the literature that present privacy-preserving frameworks for different signal processing tasks\cite{SunTay:J20a,rassouli2020,liao2017hypothesis,cummings2018differentially}. In \cite{cummings2018differentially}, the authors developed differentially private algorithms, which assume that the adversary knows all entries of the database except one, for the purpose of change-point detection. Unlike \cite{cummings2018differentially}, we consider a weaker form of privacy as this assumption may be too strong for some applications. Furthermore, we provide theoretical guarantees on the average run length to false alarm and the worst-case detection delay, which are more relevant to the QCD task as compared to guarantees on the accuracy of the estimated change-point provided by \cite{cummings2018differentially}, which are more suited for the change-point detection task. In \cite{rassouli2020}, the sanitization channel is designed for general signal processing tasks while preserving privacy, where the utility of the sanitized signal is measured using general information theoretic quantities such as mutual information, minimum mean-square error (MMSE), and probability of error. In \cite{liao2017hypothesis,SunTay:J20a}, the authors consider a fixed sample size problem of hypothesis testing while preserving privacy, where the utility of the sanitized signal is measured by the Bayes error or the Type II error of the test. \subsection{Our Contributions} In this paper, we consider the problem of optimizing QCD performance while preserving privacy. Furthermore, unlike the papers mentioned above, we consider sequential signals. It is thus possible for the adversary to obtain an arbitrarily large number of samples to improve his guess. Our main contributions are summarized as follows: \begin{itemize} \item We formulate the QCD problem with two privacy constraints, the maximal leakage privacy metric and the sequential hypothesis testing privacy metric. \item We show that the GLR CuSum stopping time together with a properly designed sanitization channel is asymptotically optimal. \item We propose relaxations and algorithms for both the centralized and decentralized versions of the QCD problem with privacy constraints. \end{itemize} A preliminary version of this paper was presented in \cite{lau2020quickest}. The rest of this paper is organized as follows. In \cref{sec:problem}, we present our signal model and problem formulation. We derive the asymptotic optimality of the GLR CuSum stopping time and formulate an optimization problem to design the optimal sanitization channel in \cref{sec:asym_opt}. We propose relaxations to the channel design problem in \cref{sec:relaxation} and present methods to solve the relaxed channel design problem in \cref{sec:centralized_algorithms}. We present the signal and sanitization model for the decentralized privacy-aware QCD problem in \cref{sec:iid} and propose methods to solve the corresponding relaxed channel design problem in \cref{sec:decentralized_algorithms}. Results from numerical experiments are presented in \cref{sec:numerical}. We conclude in \cref{sec:conclusion}. \section{Problem formulation}\label{sec:problem} Let $\mathcal{X}$ be a measurable space, where $\mathcal{X}$ is a finite alphabet. We consider a sequence of random variables $X_1, X_2, \ldots$ taking values in $\mathcal{X}$ and \gls{iid} according to different distributions before and after an unknown change point. Let $f$ be the pre-change distribution and $G=\{g_1,g_2,\ldots,g_{|G|}\}$ be the set of possible post-change distributions on $\mathcal{X}$ such that $f\neq g_i$ for all $i\in\{1,2,\ldots,|G|\}$. Let $I$ be a random variable on the indices of $G$ with distribution $p_I$.We assume that the sequence of random variables $X_1,X_2,\ldots$ satisfy the following: \begin{align}\label{eqn:signalmodel} \begin{cases} X_{t} \sim f \quad \text{i.i.d.\ for all $t< \nu$},\\ X_{t} \sim g_{i} \quad \text{i.i.d.\ for all $t\geq \nu$},\\ \end{cases} \end{align} where $\nu\geq 0$ is an unknown but deterministic change point, $i$ is the realization of the random variable $I$ which remains fixed for all $t\geq\nu$. We further assume that an adversary is interested in obtaining information about a random variable $U$, unknown to the data curator, which takes on values in a finite set $\mathcal{U}$, and that $U$ can be expressed as a randomized function of $I$, i.e., the identity of the post-change distribution informs us about $U$. We restrict our analysis to memoryless privacy mechanisms. A privacy mapping or sanitization channel $q$ maps an observation $X \in \mathcal{X}$ to a random variable $Y \in \mathcal{Y}$, where $\mathcal{Y}$ is a discrete alphabet such that $|\mathcal{Y}| \leq |\mathcal{X}|$. The sanitization channel $q$ can be represented by the conditional probability $\P(Y=y \ | X=x)$. Let $T_q$ be a column-stochastic matrix with $[T_q]_{y,x}=\P(Y=y){X=x}$ where $ [T]_{y,x}$ denotes the $(y,x)$ entry of a matrix $T$. Likewise, we represent a distribution $h$ on $\mathcal{X}$ as a column vector with $[h]_x=h(x)$ and similarly for a distribution on $\mathcal{Y}$. At each time $t$, we apply a sanitization channel $q$ to obtain $Y_t=q(X_t)$. The sanitized signal $Y_t$ is generated i.i.d.\ by the distribution $\widetilde{f}=T_{q}f$ in the pre-change regime and by the distribution $T_{q}g_i$ in the post-change regime, for some $1\leq i\leq |G|$. For a fixed $q$, we let \begin{align*} \widetilde{G}=\{T_{q}g_i\ :\ \text{$1\leq i\leq|G|$}\} \end{align*} to be the set of possible post-change distributions. Since the distributions $T_{q}g_i$ may not be distinct, we have $|\widetilde{G}|\leq |G|$. In this paper, we study the QCD problem with privacy constraints using two different privacy metrics. We assume that, at each time $t$, the adversary knows the pre-change distribution $f$, the set $G$ of post-change distributions, change-point $\nu$, the sanitization channel $q$, the current and all previous observations $Y^{1:t}=\{Y_1,Y_2,\ldots,Y_t\}$. The first privacy metric we consider is maximal leakage, first proposed in \cite{issa2016operational}, to quantify the amount of information leakage an adversary is able to gain from observing the signal $\{Y_t\ :\ t\in\mathbb{N}\}$, where $\mathbb{N}$ is the set of positive integers. Given two random variables $A \in\mathcal{A}$ and $B\in\mathcal{B}$, the maximal leakage from $A$ to $B$ is defined as \begin{align}\label{eqn:maxleak} \mathcal{L}_{\text{max}}(A\to B)=\sup_{U-A-B-\widehat{U}}\log\frac{\P(\widehat{U}=U)}{\max_{u\in\mathcal{U}}\P(U=u)}, \end{align} where $U - A - B - \hat{U}$ denotes a Markov chain and the supremum is taken over all such Markov chains. The quantity $\mathcal{L}_{\text{max}}(A\to B)$ can be interpreted as the maximum gain in bits (if $\log$ is base 2) an adversary can achieve in guessing $U$ by observing $B$, where $U$ is a randomized function of $A$. The expression in \eqref{eqn:maxleak} is equivalent\cite{issa2016operational} to \begin{align}\label{eqn:maximal_leakage_closed_form} \mathcal{L}_{\text{max}}(A\to B)=\log\left(\sum_{a\in \mathcal{A}}\max_{b\in\mathcal{B}}\P(B=b){A=a}\right). \end{align} Thus, at each time $t$, the maximum gain in bits an adversary can achieve in guessing $U$ is $\mathcal{L}_{\text{max}}(I\to Y^{\nu:t})$. The second privacy metric we consider is the \emph{sequential hypothesis testing privacy} metric. It quantifies the amount of gain an adversary is able to achieve by performing a sequential hypothesis test. Using this privacy metric, we are able to protect a subset of the post-change hypotheses from the inference of an adversary while ensuring the distinguishability of the rest of the post-change hypotheses. Given a sanitization channel $q$ and a partition $I_1\cup I_2$ of the index set of $G$ with $|I_1|>1$, such that $I_1$ is the set of indices of the post-change hypotheses to be protected, we define \begin{align*} \mathcal{K}_1(T_q)=\max_{i\in I_1} \min_{j\in I_1}\KLD{ T_qg_{i}}{T_qg_{j}},\\ \mathcal{K}_2(T_q)=\min_{i\in I_2} \min_{j\in I_1\cup I_2}\KLD{T_qg_{i}}{T_qg_{j}}, \end{align*} where $\KLD{\cdot}{\cdot}$ is the Kullback-Leibler (KL) divergence. Using standard results from sequential hypothesis testing\cite[Theorem 4.3.1]{tartakovsky2014sequential}, assuming that the adversary is willing to accept a misclassification rate of $\eta$, the expected number of samples required to identify a distribution with index in $I_1$ is \emph{at least} $|\log \eta|/\mathcal{K}_1(T_q)$ asymptotically as $\eta\to 0$. Similarly, the expected number of samples required to identify a distribution with index in $I_2$ is \emph{at most} $|\log \eta|/\mathcal{K}_2(T_q)$ asymptotically as $\eta\to 0$. For a fixed sanitization channel $q$, the QCD problem is to detect a change in distribution as quickly as possible by observing the sanitized signal $Y_1=q(X_1),Y_2=q(X_2),\ldots$, while keeping the false alarm rate low. In a typical sequential change detection procedure, at each time $t$, a test statistic $S(t)$ is computed based on the observations $Y_1,\ldots,Y_t$ up to time $t$, and the observer decides that a change has occurred at a stopping time $\tau=\inf\{t:S(t)>b\}$, which is the first $t$ such that $S(t)$ exceeds a pre-determined threshold $b$. The QCD performance of a stopping time $\tau$ can be quantified using the trade-off between two quantities, the average run length to false alarm, $\text{ARL}(\tau)$, and the expected worst-case average detection delay, $\text{EWADD}(\tau)$, defined as \begin{align*} \text{ARL}(\tau)&=\E{\infty}[\tau],\\ \text{EWADD}(\tau)&=\E[\text{WADD}_I(\tau)], \\ \text{WADD}_i(\tau)&=\sup_{\nu\geq 1}\esssup \E{\nu,i}[(\tau-\nu_c+1)^+|Y_1^{\nu_c-1}], \end{align*} where $\esssup$ is the essential supremum operator, $\E_{\nu,i}$ is the expectation operator assuming the change-point is at $\nu$ with post-change distribution $g_i$, and $\E_{\infty}$ is the expectation operator assuming the change does not occur. We should note that typically, there are several sanitization channels $q$ that satisfy a privacy constraint. As the pre and post-change distributions, $\{\widetilde{f}\}\cup\widetilde{G}$, vary with the sanitization channel $q$, we expect that the QCD performance varies with $q$ as well. It is then important for us to select the sanitization channel $q$ that provides the best QCD performance while satisfying the privacy constraint. Our privacy-aware QCD problem can be formulated as an optimization problem as follows: given a privacy admissible set $\mathcal{Q}$ and an average run length requirement $\gamma$, we seek a stopping time $\tau$, and a sanitization channel $q$ such that they are optimal solutions to the following problem: \begin{equation}\label{eqn:optimize_formulation} \begin{aligned} & \underset{\tau,q}{\text{minimize}} & & \text{EWADD}(\tau) \\ & \text{subject to} & & \text{ARL}(\tau)\geq\gamma,\\ & &&q\in \mathcal{Q} \end{aligned} \end{equation} where under the first privacy metric, the privacy admissible set $\mathcal{Q}$ is defined as \begin{align*} \mathcal{Q}=\{q\ :\ \sup_{0\leq\nu\leq t}\mathcal{L}_{\text{max}}(I\to Y^{\nu:t})\leq\epsilon\} \end{align*} for some given privacy budget $\epsilon>0$, and under the second privacy metric, \begin{align*} \mathcal{Q}=\{q\ :\ \mathcal{K}_1(T_q)\leq \epsilon_1,\ \mathcal{K}_2(T_q)\geq \epsilon_2\} \end{align*} for some given privacy budget $\epsilon_1$ and distinguishability level $\epsilon_2>0$. \section{Asymptotic optimality}\label{sec:asym_opt} In this section, we present the GLR CuSum stopping time for the privacy-aware QCD problem and study its asymptotic properties as $\gamma\to\infty$. First, we note that the minimization over the sanitization channel $q$ and stopping time $\tau$ can be decoupled in Problem~\cref{eqn:optimize_formulation}. For a fixed $q\in\mathcal{Q}$, we define the GLR CuSum stopping time $\omega_{q}$ and the GLR CuSum test statistic $S(t)$ as follows \begin{align*} &\ \ \ \omega_{q}=\inf\left\{t\ :\ S(t)\geq b\right\},\\ &\ \ \ S(t)=\max_{1\leq j\leq |\widetilde{G}|}S_j(t),\\ &\begin{cases} S_j(t)&=\max\left(S_j(t-1)+\log\frac{\widetilde{g}_j(y_t)}{\widetilde{f}(y_t)},0\right)\\ S_j(0)&=0, \end{cases}\text{for $1\leq j\leq |\widetilde{G}|$. } \end{align*} When the signal $\{\mathbf{X}_t\ :\ t\in\mathbb{N}\}$ is sanitized using the channel $q$, the GLR CuSum stopping time $\omega_{q}$ is asymptotically optimal\cite{lorden71} for the following problem: \begin{equation}\label{eqn:optimize_formulation_lorden} \begin{aligned} & \underset{\tau}{\text{minimize}} & & \text{EWADD}(\tau)\\ & \text{subject to} &&\text{ARL}(\tau)\geq\gamma, \end{aligned} \end{equation} with the asymptotic $\text{ARL}$-$\text{EWADD}$ trade-off given as \begin{align*} \text{EWADD}(\omega_{q})=\E[\frac{\log \gamma}{\KLD{T_{q}g_I}{T_{q}f}}](1+o(1)) \end{align*} as $\gamma\to\infty$, where the expectation is taken with respect to $I$. Let $q^*$ be an optimal solution to the following problem: \begin{equation}\label{eqn:optimize_formulation_asymptotic} \begin{aligned} & \underset{q}{\text{minimize}} & & \E[\frac{1}{\KLD{T_{q}g_I}{T_{q}f}}], \\ &\text{subject to} && q\in\mathcal{Q}. \end{aligned} \end{equation} Using similar arguments from \cite{tartakovsky2014sequential,lau2017optimal}, it can be shown that $\omega_{q^*}$ is asymptotically optimal for Problem~\cref{eqn:optimize_formulation} as $\gamma\to \infty$. We call Problem~\cref{eqn:optimize_formulation_asymptotic} the channel design problem and note that it is challenging to solve for several reasons. First, the objective function is neither concave nor convex. Second, it is difficult to obtain a closed form expression for the maximal leakage privacy constraint since the alphabet size of $Y^{\nu:t}$ increases quickly as $t\to\infty$. The sequential hypothesis testing privacy constraints are also neither concave nor convex. In the next section, we present relaxations of the constraint and objective function of Problem~\cref{eqn:optimize_formulation_asymptotic} to improve its computational tractability. \section{Relaxation of the Channel Design Problem}\label{sec:relaxation} \subsection{Relaxation of the Objective Function} In this subsection, we provide a relaxation of the objective function in Problem~\cref{eqn:optimize_formulation_asymptotic}. We propose to relax the objective function using Jensen's inequality: \begin{align*} \E[\frac{1}{\KLD{T_{q}g_I}{T_{q}f}}] \geq \frac{1}{\E[\KLD{T_{q}g_I}{T_{q}f}]} . \end{align*} By replacing the objective function with its lower bound, we obtain the following relaxed problem: \begin{equation}\label{eqn:optimize_formulation_asymptotic_relaxed_objective} \begin{aligned} & \underset{q}{\text{maximize}} & & \E[\KLD{T_{q}g_I}{T_{q}f}] \\ & \text{subject to} &&q\in\mathcal{Q}. \end{aligned} \end{equation} For a fixed post-change distribution $g_i$, with $1\leq i\leq N$, the expected rate of growth of $S(t)$ in the post-change regime is given as $\KLD{T_q g_i}{T_qf}$. Thus, we can interpret the new objective function as the expected rate of growth of $S(t)$ averaged over the different post-change distributions. Since the stopping time $\omega_{q}$ declares that a change has taken place when the test statistic $S(t)$ exceeds a pre-defined threshold $b$, this means that, heuristically, a larger expected rate of growth of $S(t)$ gives a smaller $\text{EWADD}$. This intuition agrees with the relaxed problem \cref{eqn:optimize_formulation_asymptotic_relaxed_objective} obtained by replacing the objective function with its lower bound ${1}/{\E[\KLD{T_{q}g_I}{T_{q}f}]}$ in Problem~\cref{eqn:optimize_formulation_asymptotic}. \subsection{Relaxation of Privacy Constraints} \subsubsection{Maximal Leakage privacy}\label{subsec:ml_constraint} In this subsection, we focus on the relaxation of the constraint $q\in\mathcal{Q}$ when the privacy metric is the maximal leakage privacy. Under the maximal leakage privacy metric, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective} becomes: \begin{equation}\label{eqn:optimize_formulation_asymptotic_relaxed_objective_ml} \begin{aligned} & \underset{q}{\text{maximize}} & & \E[\KLD{T_{q}g_I}{T_{q}f}] \\ & \text{subject to} &&\sup_{0\leq\nu\leq t}\mathcal{L}_{\text{max}}(I\to Y^{\nu:t})\leq\epsilon . \end{aligned} \end{equation} As it is difficult to obtain a closed form expression for the maximal leakage $\mathcal{L}_{\max}(I\to Y^{\nu:t})$, we approximate it using an upper bound which is easily computable. Let $J$ be a random variable on the indices of $\widetilde{G}=\{\widetilde{g}_1,\widetilde{g}_2,\ldots,\widetilde{g}_{|\widetilde{G}|}\}$, such that \begin{align*} \P(J=j){I=i}&=\begin{cases} 1 \quad\text{if $\widetilde{g}_j= T_{q}g_i$,}\\ 0\quad\text{otherwise.} \end{cases} \end{align*} Let $U$ be a randomized function of $I$. According to our signal model, we have the following factorization, \begin{align*} P_{J,I,Y^{\nu:t},U}&=P_{J,I,U}\ P_{Y^{\nu:t}|I,J,U}\\ &=P_{I,J,U}\ P_{Y^{\nu:t}| J}\\ &=P_I\ P_{J | I}\ P_{U |I}\ P_{Y^{\nu:t} | J}, \end{align*} where we use $P_X$ to denote the probability mass function (pmf) of $X$ and $P_{X|Y}$ to denote the conditional pmf of $X$ given $Y$. The following proposition provides the motivation to relax the privacy constraint in Problem~\eqref{eqn:optimize_formulation_asymptotic_relaxed_objective_ml} to $\mathcal{L}_{\text{max}}(I\to J)\leq \epsilon$. \begin{Proposition}\label{prop:upperbound_max_leakage} For any $t\in\mathbb{N}$, we have $\mathcal{L}_{\text{max}}(I\to Y^{\nu:t})\leq\mathcal{L}_{\text{max}}(I\to J).$ Hence, we have \begin{align*} \sup_{0\leq \nu\leq t}\mathcal{L}_{\text{max}}(I\to Y^{\nu:t})\leq\mathcal{L}_{\text{max}}(I\to J). \end{align*} \end{Proposition} \begin{IEEEproof} See \cref{sec:AppProp1}. \end{IEEEproof} Replacing the privacy constraint $ \sup_{0\leq \nu\leq t}\mathcal{L}_{\text{max}}(I\to Y^{\nu:t})\leq \epsilon$ in \cref{eqn:optimize_formulation_asymptotic_relaxed_objective_ml} with $\mathcal{L}_{\text{max}}(I\to J)\leq \epsilon$, we obtain the relaxed channel design problem: \begin{equation}\label{eqn:optimize_relaxed_formulation} \begin{aligned} & \underset{q}{\text{maximize}} & & \E[\KLD{T_{q}g_I}{T_{q}f}]\\ & \text{subject to} & & \mathcal{L}_{\text{max}}(I\to J)\leq\epsilon. \end{aligned} \end{equation} \cref{prop:upperbound_max_leakage} guarantees that any solution to Problem~\cref{eqn:optimize_relaxed_formulation} satisfies the original privacy constraint $\sup_{0\leq \nu\leq t}\mathcal{L}_{\text{max}}(I\to Y^{\nu:t})\leq\epsilon$. \subsubsection{Relaxation of the sequential hypothesis testing privacy constraint}\label{subsec:sht_constraint} In this subsection, we focus on the relaxation of the constraint $q\in\mathcal{Q}$ when the privacy metric is the sequential hypothesis testing privacy metric. Under the sequential hypothesis testing privacy metric, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective} becomes: \begin{equation}\label{eqn:optimize_formulation_asymptotic_relaxed_objective_sht} \begin{aligned} & \underset{q}{\text{maximize}} & & \E[\KLD{T_{q}g_I}{T_{q}f}] \\ & \text{subject to} &&\mathcal{K}_1(T_q)\leq \epsilon_1,\ \mathcal{K}_2(T_q)\geq \epsilon_2. \end{aligned} \end{equation} Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht} is non-convex as the constraints $\mathcal{K}_1(T_q)\leq \epsilon_1$ and $\mathcal{K}_2(T_q)\geq \epsilon_2$ are non-convex. This makes it difficult to have any theoretical guarantees of the global optimality of solutions found for Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht}. We focus on a restricted sanitization model in order to improve the computational tractability of Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht}. Let $\mathcal{C}=\{q_1,q_2,\ldots,q_n\}$ be a finite set of sanitization channels with column-stochastic matrices $T_1,\ldots,T_n$. At each time instance $t$, we assume that the observer obtains an observation $Y_t=(Z_t,A_t)$ where $Z_t=q_{A_t}(X_t)$ is a randomized function of the random variable $X_t$ under the sanitization channel $q_{A_t}$. We further assume that $\{A_t\}_{t\in\mathbb{N}}$ are i.i.d. generated with distribution $\phi$ on $\{1,2,\ldots,n\}$. Under the restricted sanitization model, rather than designing the sanitization channel $q$, we design the distribution $\phi$ that samples a sanitization channel $q_{A_t}$ from $\mathcal{C}$ at each time instance $t$ and use $q_{A_t}$ to sanitize the signal. For a fixed set of sanitization channels $\mathcal{C}=\{q_1,q_2,\ldots,q_n\}$ and a fixed distribution $\phi$, the asymptotic $\text{ARL}$-$\text{EWADD}$ trade-off of the GLR CuSum stopping time under the restricted sanitization model can be derived, using similar arguments from \cite{lau2017optimal}, to be \begin{align*} \text{EWADD}(\omega_{q})=\E[\frac{\log \gamma}{\sum_{c=1}^n\phi(c)\KLD{T_c g_I}{T_c f}}](1+o(1)), \end{align*} as $\gamma\to\infty$. Furthermore, we have \begin{align*} \E[\KLD{T_{q}g_I}{T_{q}f}]=\sum_{c=1}^n \phi(c)\E[\KLD{T_{c}g_I}{T_{c}f}]. \end{align*} Thus, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht} becomes \begin{equation}\label{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} \begin{aligned} & \underset{\phi}{\text{maximize}} & & \sum_{c=1}^n \phi(c)\E[\KLD{T_{c}g_I}{T_{c}f}] \\ & \text{subject to} &&\max_{i\in I_1} \min_{j\in I_1}\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\leq \epsilon_1,\\ & & &\sum_{c=1}^n \phi(c)=1,\\ & & &\phi(c)\geq 0, \quad\text{$c\in\{1,\ldots,n\}$,}\\ & & &\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\geq \epsilon_2\\ & & &\text{for $i\in I_2$ and $j\in I_1\cup I_2$}. \end{aligned} \end{equation} Since $\KLD{T_{c}g_I}{T_{c}f},\KLD{T_{c}g_i}{T_{c}g_j}$ can be pre-computed for all $c\in\{1,\ldots,n\}$ and $i,j\in \{1,\ldots,|G|\}$, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} without the constraint \begin{align*} \max_{i\in I_1} \min_{j\in I_1}\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\leq \epsilon_1 \end{align*} is a linear program. In the next section, we show that Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} can be expressed as a mixed-integer linear program (MILP). \section{Algorithms for Privacy-Aware QCD}\label{sec:centralized_algorithms} In this section, methods that provide globally and locally optimal solutions for Problems~\cref{eqn:optimize_relaxed_formulation,eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} are presented. \subsection{Maximal Leakage Privacy}\label{subsec:algorithms_ml} \subsubsection{Exact Method} From \eqref{eqn:maximal_leakage_closed_form}, $2^{\mathcal{L}_{\text{max}}(I\to J)}$ is an integer since the conditional probability $\P(J=j){I=i}\in\{0,1\}$ is an integer. Hence, the constraint $\mathcal{L}_{\text{max}}(I\to J)\leq \epsilon$ in Problem~\cref{eqn:optimize_relaxed_formulation} is equivalent to \begin{align}\label{eqn:L(IJ)=m} \sum_j\max_i\P(J=j){I=i}\leq m, \end{align} where $m=\lfloor2^\epsilon\rfloor$. There are at most $\stirling{|G|}{m}\leq m^{|G|}$ different conditional pmfs $P_{J|I}$ satisfying \eqref{eqn:L(IJ)=m}, where the Stirling number of the second kind $\stirling{a}{b}$ counts the number of ways to partition a set of $a$ labeled objects into $b$ nonempty unlabeled subsets\cite{riordan2012introduction}. For each conditional pmf $P_{J|I}$, we solve the following problem: \begin{equation}\label{eqn:N=1,epsilon>0,cases} \begin{aligned} & \underset{q}{\text{maximize}} & & \E[\KLD{T_{q}g_i}{T_{q}f}] \\ & \text{subject to} & & T_{q}g_i=\widetilde{g}_j \\ & & &\text{for all $i,j$ such that $\P(J=j){I=i}=1$}.\\ \end{aligned} \end{equation} For a fixed conditional pmf $P_{J|I}$, Problem~\eqref{eqn:N=1,epsilon>0,cases} is maximizing a convex function over a convex bounded polytope. Therefore, an extreme point achieves the maximum value, and we are able to solve Problem~\eqref{eqn:N=1,epsilon>0,cases} by enumerating over the finite number of extreme points of the convex bounded polytope defined by the linear constraints of \eqref{eqn:N=1,epsilon>0,cases}. A globally optimal solution for Problem~\cref{eqn:optimize_relaxed_formulation} can be obtained by enumerating over all conditional pmfs $P_{J|I}$ represented by a zero-one matrix satisfying \eqref{eqn:L(IJ)=m}, and solving Problem~\eqref{eqn:N=1,epsilon>0,cases} for each of these conditional pmfs. However, we still need to solve at least exponentially many convex maximization problems with respect to the number of post-change distributions $|G|$, since $\stirling{|G|}{m}\sim\frac{m^{|G|}}{m!}$ as $|G|\to \infty$. This may be computationally undesirable when $|G|$ is large. \subsubsection{Augmented Lagrangian Method} We further relax the channel design problem by relaxing the discrete constraint \eqref{eqn:L(IJ)=m}. This relaxation allows the application of the augmented Lagrangian method for cases where the exact method is computationally undesirable. The constraint \eqref{eqn:L(IJ)=m} is equivalent to $ |\{T_qg_i \ :\ 1\leq i\leq |G|\}|\leq m. $ In order to count the number of distinct elements in the set $\{T_qg_i \ :\ 1\leq i\leq |G|\}$, we can use the following continuous approximation,\begin{align*} &|\{T_qg_i \ :\ 1\leq i\leq |G|\}|\\ &=1+\sum_{i=2}^{|G|}\prod_{j=1}^{i-1} \mathbf{1}_{T_qg_i\neq T_qg_j}\\ &\approx 1+\sum_{i=2}^{|G|}\prod_{j=1}^{i-1} \left(\frac{1}{2}+ \frac{1}{\pi}\arctan (k\|T_qg_i-T_qg_j\|_1)\right), \end{align*} where $k$ is a chosen to be large and $\|\cdot\|_1$ refers to the $L_1$ norm. Putting this back into Problem~\cref{eqn:optimize_relaxed_formulation}, we obtain the following continuous optimization problem: \begin{equation}\label{eqn:optimize_continuous_relaxed_formulation} \begin{aligned} &\underset{q}{\text{maximize}}\ \E[\KLD{T_{q}g_n}{T_{q}f}] \\ & \text{subject to} \\ & \sum_{i=2}^{|G|}\prod_{j=1}^{i-1} \left(\frac{1}{2}+ \frac{1}{\pi}\arctan (k\|T_qg_i-T_qg_j\|_1)\right)\leq m-1, \end{aligned} \end{equation} for which an augmented Lagrangian Solver\cite{pyopt-paper,conn2013lancelot} can be used to obtain locally optimal solutions\cite{fernandez2012local}. \subsection{Sequential Hypothesis Testing Privacy}\label{subsec:algorithms_sht} In this subsection, we show that Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} is equivalent to a MILP. First, we require the following proposition. \begin{Proposition}\label{prop:equiv_conditions} For distribution $\phi$ on $\{1,\ldots,n\}$, $\phi$ satisfies \begin{align}\label{eqn:equiv_prop_1} \max_{i\in I_1} \min_{j\in I_1}\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\leq \epsilon_1 \end{align} if and only if there exist functions \begin{align*} \xi&:I_1\to \mathbb{R},\\ \delta&:I_1\times I_1 \to\{0,1\} \end{align*} such that \begin{align} &\xi(i)\leq \epsilon_1,\label{eqn:eqn:equiv_prop_2_1}\\ &\sum_{j\in I_1}\delta(j,i)=1,\label{eqn:eqn:equiv_prop_2_2}\\ &\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\geq \xi(i),\label{eqn:eqn:equiv_prop_2_3}\\ &\sum_{c=1}^n\phi(c)\KLD{T_cg_a}{T_cg_j}\leq \xi(i)+(1-\delta(j,i))M,\label{eqn:eqn:equiv_prop_2_4} \end{align} where $M=\max_{c\in\{1,\ldots,n\}}\max_{i,j\in I_1}\KLD{T_cg_i}{T_cg_j},$ and $i,j\in I_1$. \end{Proposition} \begin{IEEEproof} See \cref{sec:AppProp2}. \end{IEEEproof} By \cref{prop:equiv_conditions}, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} is equivalent to the following MILP: \begin{align}\label{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_MILP} &\underset{\phi}{\text{maximize}} \ \sum_{c=1}^n \phi(c)\E[\KLD{T_{c}g_I}{T_{c}f}] \nonumber\\ &\text{subject to} \nonumber\\ & \sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\geq \epsilon_2 \nonumber\\ & \quad\quad\text{for $i\in I_2$ and $j\in\{1,\ldots,|G|\}$},\nonumber\\ & \xi(i)\leq \epsilon_1\quad\text{ for $i\in I_1$},\nonumber\\ & \delta(j,i)\in\{0,1\}\text{ for $i,j\in I_1$},\\ & \sum_{c=1}^n \phi(c)=1\nonumber\\ & \phi(c)\geq 0 \quad\text{$c\in\{1,\ldots,n\}$,}\nonumber\\ & \sum_{j\in I_1}\delta(j,i)=1\text{ for $i\in I_1$},\nonumber\\ & \sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\geq \xi(i) \ \text{for $i,j\in I_1$},\nonumber\\ & \sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\nonumber\\ & \quad\quad\leq \xi(i)+(1-\delta(j,i))M\quad\text{for $i,j\in I_1$}.\nonumber \end{align} A global optimal solution to Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_MILP} can be obtain using branch-and-bound methods on a linear program solver\cite{cvx}. \section{Decentralized QCD with Independent Sensor observations}\label{sec:iid} We assume that the sequence of random variables $X_1,X_2,\ldots$ satisfy the observations obtained at each sensor at any time instance are independent before the change point, and conditionally independent given $I$ after the change point. The observation obtained by the $k$-th sensor at time $t$, $X_{k,t}$, taking values in $\mathcal{X}$, satisfy the following: \begin{align}\label{eqn:iidsignalmodel} \begin{cases} X_{k,t} \sim f_k \quad \text{i.i.d. for all $t< \nu$},\\ X_{k,t} \sim g_{k,i} \quad \text{i.i.d. for all $t\geq \nu$},\\ \end{cases} \end{align} for $k\in\{1,\ldots,K\}$. The observations $X_{1,t},\ldots,X_{K,t}$ are mutually independent, $\nu\geq 0$ is an unknown but deterministic change point and $i$ is the realization of the random variable $I$ which remains fixed for all $t\geq\nu$. We denote the marginal distribution of $X_{k,t}$ under $f$ and $g_i$ as $f_k$ and $g_{k,i}$ respectively. For the task of privacy-aware decentralized QCD, we apply a memoryless privacy mechanism locally at each sensor $k$ for $k\in\{1,\ldots,K\}$. For each sensor $k$, a local privacy mapping or sanitization channel $q_k$ maps the observation $X \in \mathcal{X}$ obtained at sensor $k$ to a random variable $Y \in \mathcal{Y}$, where $\mathcal{Y}$ is a discrete alphabet such that $|\mathcal{Y}| \leq |\mathcal{X}|$. The local privacy mechanism $q_k$ can be represented by a conditional probability $\P(Y=y \ | X=x)$. Let $T_{q_k}$ be a column-stochastic matrix with $[T_{q_k}]_{y,x}=\P(Y=y){X=x}$ where $ [T_{q_k}]_{y,x}$ denotes the $(y,x)$ entry of the matrix $T_{q_k}$. Likewise, we represent a distribution $h$ on $\mathcal{X}$ as a column vector with $[h]_{x}=h(x)$ and similarly for a distribution on $\mathcal{Y}$. At each time $t$ and sensor $k$, we apply the local sanitization channel $q_k$ to obtain $Y_{k,t}=q_k(X_{k,t})$. The sanitized signal $Y_{k,t}$ is generated i.i.d.\ by the distribution $T_{q_k} f_k$ in the pre-change regime and by the distribution $T_{q_k} g_{k,i}$ in the post-change regime, for some $1\leq i\leq |G|$. For a fixed set of sanitization channels $\{q_1,\ldots,q_K\}$, we let $\widetilde{G}_{\{q_1,\ldots,q_K\}}=\{\widetilde{g}_1,\ldots,\widetilde{g}_{|G|}\}$ to be the set of possible post-change distributions where $\widetilde{g}_j$ is the post-change distribution generating the sanitized signal by applying the set of sanitization channels $\{q_1,\ldots, q_K\}$ to the observations generated by $g_i$ for some $i\in\{1,\ldots,|G|\}$. \subsection{Algorithms for Decentralized Privacy-Aware QCD}\label{sec:decentralized_algorithms} For the task of decentralized privacy-aware QCD , the sanitization channels are only allowed to use local observations to achieve sanitization of the signal. This introduces additional constraints on the structure of the sanitization channel $q$. In this section, we present algorithms for solving Problems~\cref{eqn:optimize_relaxed_formulation,eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} for the task of decentralized privacy-aware QCD. \subsection{Maximal Leakage Privacy}\label{subsec:decen_algorithms_ml} In this subsection, we present the Local Exact Method which solves Problem~\cref{eqn:optimize_relaxed_formulation} exactly and has computational complexity that scales linearly with respect to the number of sensors $K$. First, for each conditional pmf $P_{J|I}$ satisfying $ \P(J=j){I=i}\in\{0,1\} $ for all $1\leq i\leq |G|$, $1\leq j \leq |\widetilde{G}|$ and $\mathcal{L}(I\to J)\leq \epsilon$, we solve the following problem: \begin{equation}\label{eqn:cases} \begin{aligned} & \underset{q_k}{\text{maximize}} & & \E[\KLD{T_{q_k} g_{k,I}}{T_{q_k} f_k}] \\ & \text{subject to} & & T_{q_k} g_{k,i}=\widetilde{g}_j \quad \text{for all $i,j$},\\ & & & \text{such that $\P(J=j){I=i}=1$}, \end{aligned} \end{equation} for $k\in\{1,\ldots,K\}$. Similar to Problem~\eqref{eqn:N=1,epsilon>0,cases}, Problem~\eqref{eqn:cases} is maximizing a convex function over a convex bounded polytope. Therefore, we are able to solve Problem~\eqref{eqn:cases} by enumerating over the finite number of extreme points on the convex bounded polytope. Next, for each $k\in\{1,\ldots,K\}$, we let $q_k^*(P_{J|I})$ be an optimal solution to Problem~\eqref{eqn:cases} corresponding to the conditional probability distribution $P_{J|I}$ and solve the following problem: \begin{equation}\label{eqn:cases_2} \begin{aligned} P_{J|I}^*=&\underset{P_{J|I}}{\text{argmax}} & &\sum_{k=1}^K \E[\KLD{T_{q_k^*(P_{J|I})} g_{k,I}}{T_{q_k^*(P_{J|I})} f_k}] \\ & \text{subject to} & & \P(J=j){I=i}\in\{0,1\}\quad\text{for all $i,j$},\\ & & & \mathcal{L}(I\to J)\leq \epsilon. \end{aligned} \end{equation}There is a maximum of $\stirling{|G|}{m}$ conditional distributions $P_{J|I}$ that satisfy $\mathcal{L}(I\to J)\leq \epsilon$ where $m=\lfloor2^\epsilon\rfloor$ and $\stirling{a}{b}$ is the Stirling number of the second kind\cite{riordan2012introduction}. Thus, a solution for Problem~\eqref{eqn:cases_2} can be obtained by enumerating over the finite set of conditional probabilities $P_{J|I}$. In the next proposition, we show that the set of sanitization channels obtained by the Local Exact method above is an optimal solution to Problem~\cref{eqn:optimize_relaxed_formulation} under the decentralized QCD setting. \begin{Proposition}\label{prop:optimality} Suppose the observations follow the signal model described in \eqref{eqn:iidsignalmodel}. Under the decentralized QCD setting, $\{q_1^*(P_{J|I}^*),\ldots,q_k^*(P_{J|I}^*)\}$ is an optimal solution to Problem~\cref{eqn:optimize_relaxed_formulation}. In particular, if $g_{1,i}=g_{2,i}=\ldots=g_{K,i}$ for $i\in\{1,\ldots,|G|\}$ then $\{q_1^*(P_{J|I}^*),\ldots,q_1^*(P_{J|I}^*)\}$ is an optimal solution to Problem~\cref{eqn:optimize_relaxed_formulation}. \end{Proposition} \begin{IEEEproof} See \cref{sec:AppProp3}. \end{IEEEproof} \subsection{Sequential Hypothesis Testing Privacy}\label{subsec:decen_algorithms_sht} Similar to the general case, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht} for the decentralized privacy-aware QCD problem is non-convex as the constraints $\mathcal{K}_1(T_q)\leq \epsilon_1$ and $\mathcal{K}_2(T_q)\geq \epsilon_2$ are non-convex. We use a restricted sanitization model to improve the computational tractability of Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht}. However, in the decentralized version of the problem, each sensor is allowed to select its sanitization channel independent of the rest of the sensors. Let $\mathcal{C}_k=\{q_{k,1},q_{k,2},\ldots,q_{k,n}\}$ be a finite set of local sanitization channels at sensor $k$ with column-stochastic matrices $T_{k,1},\ldots,T_{k,n}$. At each time instance $t$, we assume that sensor $k$ obtains an observation $Y_{k,t}=(Z_{k,t},A_{k,t})$ where $Z_{k,t}=q_{A_{k,t}}(X_{k,t})$ is a randomized function of the random variable $X_{k,t}$ under the sanitization channel $q_{A_{k,t}}$. We further assume that $\{A_{k,t}\}_{t\in\mathbb{N}}$ are i.i.d. generated with distribution $\phi_k$. Under the restricted sanitization model, rather than designing the sanitization channel $q$, we design the distribution $\phi_k$ that samples the sanitization channel $q_{A_{k,t}}$ from $\mathcal{C}_k$ at each sensor $k$ and time instance $t$. We then apply $q_{A_{k,t}}$ to $X_{k,t}$ to locally sanitize the signal. Using similar arguments from \cite{lau2017optimal}, the asymptotic $\text{ARL}$-$\text{EWADD}$ trade-off of the GLR CuSum stopping time under the restricted sanitization model is given as \begin{align*} &\text{EWADD}(\omega_{q})\\ &=\E[\frac{\log \gamma}{\sum_{k=1}^K\sum_{c=1}^n\phi_k(c)\KLD{T_{q_{k,c}} g_{k,I}}{T_{q_{k,c}} f_k}}](1+o(1)), \end{align*} as $\gamma\to\infty$. We also have \begin{align*} &\E[\KLD{T_{q}g_I}{T_{q}f}]\\ &=\E[\sum_{k=1}^K\sum_{c=1}^n\phi_k(c)\KLD{T_{q_{k,c}} g_{k,I}}{T_{q_{k,c}} f_k}]. \end{align*} Thus, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht} becomes \begin{equation}\label{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized_decent} \begin{aligned} & \underset{\phi}{\text{maximize}} & & \sum_{k=1}^K\sum_{c=1}^n \phi_k(c)\E[\KLD{T_{q_{k,c}} g_{k,I}}{T_{q_{k,c}} f_k}] \\ & \text{subject to} &&\max_{i\in I_1} \min_{j\in I_1}\sum_{k=1}^K\sum_{c=1}^n\phi_k(c)\KLD{T_{q_{k,c}}g_{k,i}}{T_{q_{k,c}}g_{k,j}}\leq \epsilon_1,\\ & & &\sum_{k=1}^K\sum_{c=1}^n \phi_k(c)=1\\ & & &\phi_k(c)\geq 0, \quad\text{$c\in\{1,\ldots,n\}$ and $k\in\{1,\ldots,K\}$}\\ & & &\sum_{k=1}^K\sum_{c=1}^n\phi_k(c)\KLD{T_{q_{k,c}}g_{k,i}}{T_{q_{k,c}}g_{k,j}}\geq \epsilon_2\\ & & & \quad \text{for $i\in I_2$ and $j\in \{1,\ldots,|G|\}$}. \end{aligned} \end{equation} Using similar arguments from \cref{prop:equiv_conditions}, Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized_decent} is equivalent to the following MILP, \begin{align}\label{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_MILP_decent} & \underset{\phi}{\text{maximize}}\ \sum_{k=1}^K\sum_{c=1}^n \phi_k(c)\E[\KLD{T_{q_{k,c}} g_{k,I}}{T_{q_{k,c}} f_k}] \\ & \text{subject to} \nonumber\\ & \xi(i)\leq \epsilon_1\quad\text{ for $i\in I_1$},\nonumber\\ & \delta(j,i)\in\{0,1\}\text{ for $i,j\in I_1$},\nonumber\\ & \sum_{k=1}^K\sum_{c=1}^n \phi_k(c)=1\nonumber\\ & \phi_k(c)\geq 0 \quad\text{$c\in\{1,\ldots,n\}$ and $k\in\{1,\ldots,K\}$} \nonumber\\ & \sum_{j\in I_1}\delta(j,i)=1\text{ for $i\in I_1$},\nonumber\\ & \sum_{k=1}^K\sum_{c=1}^n\phi_k(c)\KLD{T_{q_{k,c}}g_{k,i}}{T_{q_{k,c}}g_{k,j}}\nonumber\\ & \quad\quad\leq \xi(i)+(1-\delta(j,i))M\quad \text{for $i,j\in I_1$}.\nonumber\\ & \sum_{k=1}^K\sum_{c=1}^n\phi_k(c)\KLD{T_{q_{k,c}}g_{k,i}}{T_{q_{k,c}}g_{k,j}}\geq \epsilon_2\nonumber\\ & \quad \text{for $i\in I_2$ and $j\in \{1,\ldots,|G|\}$},\nonumber\\ & \sum_{k=1}^K\sum_{c=1}^n\phi_k(c)\KLD{T_{q_{k,c}}g_{k,i}}{T_{q_{k,c}}g_{k,j}}\geq \xi(i) \nonumber\\ & \quad\quad \text{for $i,j\in I_1$}.\nonumber \end{align} A global optimal solution to Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_MILP_decent} can be obtained using branch-and-bound methods on a linear program solver\cite{cvx}. \section{Numerical Experiments}\label{sec:numerical} In this section, we present numerical results of experiments of the various methods introduced under the different signal models. The simulations were performed using MATLAB R2017a on a laptop with Intel(R) Core(TM) i7-6500U [email protected] and 16.0GB RAM. \subsection{Privacy-Aware QCD} \subsubsection{Maximal Leakage Privacy} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{compare_exact_al_method.pdf} \caption{Trade-off between the privacy budget $\epsilon$ and the expected KL divergence $\E[\KLD{T_{q}g_n}{T_{q}f}]$ for the Exact and augmented Lagrangian method } \label{fig:compare_exact_al_method} \end{figure} In this subsection, we present numerical results for the privacy-aware QCD task under the maximal leakage privacy metric. We consider the signal model with pre-change distribution $f$, set of possible post-change distribution $G=\{g_1,g_2,\ldots,g_5\}$ where $f$ and $G$ are randomly generated, uniform prior $p_I$ on the post-change distributions and $\mathcal{X}=\mathcal{Y}=\{1,2,\ldots,7\}$. Using algorithms described in \cref{subsec:algorithms_ml}, we solve the relaxed channel design problem~\cref{eqn:optimize_relaxed_formulation} exactly and problem \cref{eqn:optimize_continuous_relaxed_formulation} using the augmented Lagrangian method. First, we present results to illustrate the trade-off between the privacy budget $\epsilon$ and the expected KL divergence. In \cref{fig:sanitized5,fig:sanitized1,fig:sanitized3}, we plot the pmf of the original distributions, sanitized distributions when $\epsilon=\log_2 1$ and sanitized distributions when $\epsilon=\log_2 3$, respectively. In \figref{fig:compare_exact_al_method}, the expected KL divergence obtained by each of the methods is plotted against the privacy budget $\epsilon$. When the privacy budget $\epsilon=\log_2 5\approx 2.3$, the privacy constraint $\mathcal{L}_{\text{max}}(I\to J)\leq \epsilon$ becomes redundant as it is trivially satisfied. Problem~\eqref{eqn:optimize_formulation} then reduces to a standard QCD problem without any sanitization of the observations. It should be noted that two graphs intersect the y-axis at a positive value rather than at zero. This is because when our privacy budget $\epsilon$ is zero, we only remove all information that allows us to identify the post-change distributions. Thus, it is possible to distinguish the post-change distributions from the pre-change distribution in some cases. As the augmented Lagrangian method only guarantees local optimality, the channel obtained by solving Problem \cref{eqn:optimize_continuous_relaxed_formulation} achieves a lower value of the objective function as compared to the channel obtained by solving Problem~\cref{eqn:optimize_relaxed_formulation}. Next, we plot the compute time required for each of the methods against the privacy budget $\epsilon$ in \figref{fig:compare_exact_al_method_time}. The results indicate that the augmented Lagrangian method requires significantly lesser compute time compared to the Exact method. It should be noted that the compute time required by the Exact Method is directly proportional to $\stirling{|G|}{m}$. The peak observed in \figref{fig:compare_exact_al_method_time} corresponds to $\stirling{|G|}{m}$ achieving its maximum at $m=3$ when $|G|=5$. \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{pmf_sanitied_5.pdf} \caption{Pmf of pre- and post-change distributions.} \label{fig:sanitized5} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{pmf_sanitied_1} \caption{Pmf of pre- and post-change sanitized distributions for $\epsilon=\log_2 1$.} \label{fig:sanitized1} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{pmf_sanitied_3} \caption{Pmf of pre- and post-change sanitized distributions for $\epsilon=\log_2 3$.} \label{fig:sanitized3} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{compare_exact_al_method_time.pdf} \caption{Comparison of the time taken to solve the relaxed channel design problem for the Exact and augmented Lagrangian method.} \label{fig:compare_exact_al_method_time} \end{figure} \subsubsection{Sequential Hypothesis Testing Privacy} In this subsection, we present numerical results for the centralized QCD task under the sequential hypothesis testing privacy metric. We consider the signal model with pre-change distribution $f$, set of possible post-change distribution $G=\{g_1,g_2,\ldots,g_6\}$ with $I_1=\{1,2,3\}$ and $I_2=\{4,5,6\}$, a uniform prior $p_I$ on the post-change distributions, $\mathcal{X}=\mathcal{Y}=\{1,2,3,4\}$ and the set of deterministic functions from $\mathcal{X}$ to $\mathcal{Y}$ as the finite set of sanitization channel $\mathcal{C}$. We generate $f$ and $G$ randomly. Using algorithms described in \cref{subsec:algorithms_sht}, we solve the relaxed channel design problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} by solving the MILP in Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_MILP}. By the data processing inequality $\mathcal{K}_1(T_q)\leq \max_{i\in I_1}\min_{j\in I_1}\KLD{g_i}{g_j}=0.9387$ and $\mathcal{K}_2(T_q)\leq \min_{i\in I_2}\min_{j\in I_1\cup I_2}\KLD{g_i}{g_j}=0.0855$, thus we focus our attention to the region where $0\leq \epsilon_1\leq 0.9387 $ and $0\leq\epsilon_2\leq 0.0855$. In \cref{fig:original_seq,fig:sanitized_seq}, we plot the pmf of the original distributions, sanitized distributions when $\epsilon_1=0.0012, \epsilon_2=0.0024$, respectively. We compare the trade-off between the privacy $\epsilon_1$ of $I_1$ in $G$ and the expected KL divergence in \figref{fig:compare_privacy_vs_kl} and the trade-off between the distinguishability $\epsilon_2$ of $I_1$ in $G$ and the expected KL divergence in \figref{fig:compare_distinguishability_vs_kl}. In both \figref{fig:compare_privacy_vs_kl} and \figref{fig:compare_distinguishability_vs_kl}, we observe that the average KL divergence increases as $\epsilon_1$ increases and $\epsilon_2$ decreases which is consistent with the behaviour expected of the optimal value of Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized}. \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{pmf_seq_testing_original.pdf} \caption{Pmf of pre- and post-change original distributions.} \label{fig:original_seq} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{pmf_seq_testing_sanitized.pdf} \caption{Pmf of pre- and post-change sanitized distributions for $\epsilon_1=0.0012$ and $\epsilon_2=0.0024$.} \label{fig:sanitized_seq} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{privacy_vs_kl} \caption{Trade-off between the privacy budget $\epsilon_1$ and the expected KL divergence for different distinguishability levels $\epsilon_2$.} \label{fig:compare_privacy_vs_kl} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{distinguishability_vs_kl} \caption{Comparison of trade-off between the distinguishability $\epsilon_2$ of $I_2$ in $G$ and the expected KL divergence for different privacy $\epsilon_1$ of $I_1$ in $G$.} \label{fig:compare_distinguishability_vs_kl} \end{figure} \subsection{Decentralized Privacy-Aware QCD} \subsubsection{Maximal Leakage Privacy} In this subsection, we present numerical results for the decentralized QCD task under the maximal leakage privacy metric. We consider the signal model described in \eqref{eqn:iidsignalmodel}. We generate $f_k$ and $g_{k,i}$ randomly such that $g_{k_1,i}=g_{k_2,i}$ for all $k_1,k_2\in\{1,\ldots,K\}$ and $i\in\{1,\ldots,5\}$, use a uniform prior $p_I$ on the post-change distributions and let $\mathcal{X}=\mathcal{Y}=\{1,2,\ldots,5\}$. \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{privacy_util_tradeoff_max_leak_decent} \caption{The trade-off between the expected KL divergence and the privacy budget $\epsilon$ for different number of sensors.} \label{fig:privacy_util_tradeoff_decent} \end{figure} \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{privacy_util_tradeoff_max_leak_decent_vs_sensors.pdf} \caption{The expected KL divergence achieved by the solved sanitization channel for different number of sensors.} \label{fig:privacy_util_tradeoff_decent_linear} \end{figure} We solve the relaxed channel design problem~\cref{eqn:optimize_relaxed_formulation} using the Local Exact method described in \cref{subsec:decen_algorithms_ml} for different number of sensors $K$. In \figref{fig:privacy_util_tradeoff_decent}, we plot the trade-off between the expected KL divergence and the privacy budget $\epsilon$ for different number of sensors $K$. In \figref{fig:privacy_util_tradeoff_decent_linear}, we plot the expected KL divergence for the privacy budget $\epsilon=0,1,\log_2 5$ as the number of sensors vary between $1$ and $150$. The results from the experiments indicate that for the case where the signal observed at each of sensors are identically distributed, the expected KL divergence grows linearly with respect the number of sensors $K$. Next, we compare the compute time taken to solve Problem~\eqref{eqn:optimize_relaxed_formulation} using the Exact method and the Local exact method. We solve the relaxed channel design problem~\cref{eqn:optimize_relaxed_formulation} with a privacy budget of $\epsilon=1$ using the Exact method described in \cref{subsec:algorithms_ml} and the Local Exact method described in \cref{sec:iid}. \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{time_vs_sensors} \caption{Comparison of compute time for the Exact and Local Exact method.} \label{fig:compare_exact_method} \end{figure}In \figref{fig:compare_exact_method}, we plot the compute time required to solve Problem~\eqref{eqn:optimize_relaxed_formulation} against the number of sensors $K$ for the Exact method and the Local exact method respective. The simulation result indication that the compute time required by Exact method increases exponentially with respect to the number of sensors $K$ while the compute time required by the Local Exact method remains reasonably low. \subsubsection{Sequential Hypothesis Testing Privacy} In this subsection, we present numerical results for the decentralized QCD task under the sequential hypothesis testing privacy metric. We consider the signal model described in \eqref{eqn:iidsignalmodel}. We generate $f_k$ and $g_{k,i}$ randomly such that $g_{k_1,i}=g_{k_2,i}$ for all $k_1,k_2\in\{1,\ldots,K\}$ and $i\in\{1,\ldots,6\}$, use a uniform prior $p_I$ on the post-change distributions, partition the index set of $G$ into $I_1=\{1,2,3,4\}$ and $I_2=\{5,6\}$, and let $\mathcal{X}=\mathcal{Y}=\{1,2,3\}$. \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{privacy_util_tradeoff_sequential_hypo_decent_vs_sensors.pdf} \caption{The trade-off between the expected KL divergence and the privacy budget $\epsilon$ for different number of sensors.} \label{fig:privacy_util_tradeoff_decent_sht} \end{figure} We solve the relaxed channel design problem~\cref{eqn:optimize_relaxed_formulation} using by solving the MILP described in \cref{subsec:decen_algorithms_sht} for the privacy budget $\epsilon_1=0.025,\epsilon_2=0.05$. In \figref{fig:privacy_util_tradeoff_decent_sht}, we present the simulation results to illustrate the relationship between the number of sensors and the expected KL divergence under the decentralized signal model. As the number of sensor increases, the privacy constraint $\mathcal{K}_1(T_q)\leq\epsilon_1$ becomes more difficult to satisfy and the distinguishably constraint $\mathcal{K}_2(T_q)\geq \epsilon_2$ becomes easier to satisfy. Thus, we do not expect that the expected KL divergence to grow linearly with the number of sensors. The simulation indicates that the expected KL divegerence does not increase linearly with the number of sensors $K$. Next, we present the relationship between the average compute time required to solve Problem~\eqref{eqn:optimize_relaxed_formulation} and the number of sensors $K$. We randomly generate 500 sets of distributions satisfying $g_{k_1,i}=g_{k_2,i}$ for all $k_1,k_2\in\{1,\ldots,K\}$ and $i\in\{1,\ldots,6\}$. For each set of distribution, we randomly sample $\epsilon_1$ with uniform probability in the interval $[0,\max_{i\in I_1}\min_{j\in I_1}\KLD{g_i}{g_j}]$ and $\epsilon_2$ with uniform probability in the interval $[0,\min_{i\in I_2}\min_{j\in I_1\cup I_2}\KLD{g_i}{g_j}]$. In the event when the sampled $\epsilon_1,\epsilon_2$ makes Problem~\eqref{eqn:optimize_relaxed_formulation} infeasible, we resample $\epsilon_1,\epsilon_2$. The compute time taken to solve the MILP for each set of distributions is recorded and the relationship between the average compute time and the number of sensors is present in \figref{fig:compare_seq_hypo_time}. The simulation results suggests that the average compute time increases with respest to the number of sensors $K$ in a super-linear manner. This may be a potential challenge for applications when the number of sensors is large. \begin{figure}[!htbp] \centering \includegraphics[width=8cm]{compare_decent_seq_hypo_time} \caption{Relationship between average compute time and the number of sensors $K$ .} \label{fig:compare_seq_hypo_time} \end{figure} \section{Conclusion and future work}\label{sec:conclusion} In this paper, we have proposed a framework for privacy-aware QCD using two different privacy metrics for both centralized and decentralized QCD tasks. We also proposed optimization problems for which the solution provides a sanitization channel where the GLR CuSum stopping time is asymptotically optimal under each of the scenarios. We derived relaxations to the channel design problem and provided algorithms to obtain exact solutions to the relaxed channel design problem. For the maximal leakage privacy metric, a continuous relaxation for the channel design problem is proposed so that locally optimal solutions can be obtained when the exact solutions are computationally intractable. An algorithm that scales linearly with the number of sensors is also proposed for the decentralized QCD tasks when the signal recieved at the sensors are mutually independent. One drawback of the proposed signal and sanitization model for privacy-aware QCD under maximal leakage privacy metric is the discreteness of the privacy constraint $\mathcal{L}_{\text{max}}(I\to J)$. Using a randomization of multiple possible sanitization channels, the privacy constraint $\mathcal{L}_{\text{max}}(I\to J)$ is able to achieve a continuous interval of values. The optimization problem related to this new channel design problem is, however, much harder to solve and is a potential direction for future work. For the sequential hypothesis testing privacy metric, a modified sanitization model is proposed to relax the channel design problem into a MILP for both centralized and decentralized QCD tasks. One interesting direction of future work can be done to determine the pairs $(\epsilon_1,\epsilon_2)$ where Problem~\cref{eqn:optimize_formulation_asymptotic_relaxed_objective_sht_linearized} is feasible. It will also be interesting to design an algorithm with computation complexity that grows sub-linearly with the number of sensors for the decentralized QCD task with the sequential hypothesis testing privacy metric. \appendices \section{Proof of \cref{prop:upperbound_max_leakage}}\label[appendix]{sec:AppProp1} We define the following matrices $\Delta\in\mathbb{R}^{G\times\mathcal{U}}$, $\Theta\in\mathbb{R}^{\mathcal{Y}^{t-\nu+1}\times\widetilde{G}}$, $\Lambda\in\mathbb{R}^{\widetilde{G}\times G}$, $\Phi_0\in\mathbb{R}^{U\times\mathcal{Y}^{t-\nu+1}}$ and $\Phi_1\in\mathbb{R}^{U\times\widetilde{G}}$ such that \begin{align}\label{eqn:matrices_1} &[\Delta]_{i,u}= P_{U|I}(u\ |\ i)P_I(i),\nonumber\\ &[\Theta]_{y^{\nu:t},j}=P_{Y^{\nu:t}|J}(y^{\nu:t}\ |\ j),\\ &[\Lambda]_{j,i}==P_{J|I}(j\ |\ i),\nonumber \end{align} and \begin{align}\label{eqn:matrices_2} [\Phi_0]_{u,y^{\nu:t}}&=\begin{cases} 1\quad\text{if $u=\argmax_{u\in\mathcal{U}}P_{\mathcal{U},Y^{\nu:t}}(u,y^{\nu:t})$,}\\ 0\quad\text{otherwise.} \end{cases}\\ [\Phi_1]_{u,j}&=\begin{cases} 1\quad\text{if $u=\argmax_{u\in\mathcal{U}}P_{\mathcal{U},J}(u,j)$,}\\ 0\quad\text{otherwise.} \end{cases}\nonumber \end{align} For a fixed random variable $U$ that is a randomized function of $I$, we have \begin{align}\label{eqn:demoninator_ml_1} &\sum_{y^{\nu:t}}\max_{u\in\mathcal{U}}P_{\mathcal{U},Y^{\nu:t}}(u,y^{\nu:t})\nonumber\\ &=\sum_{y^{\nu:t}}\max_{u\in\mathcal{U}}\sum_{j=1}^{|\widetilde{G}|}\sum_{i=1}^{|G|}P_{J,I,Y^{\nu:t},\mathcal{U}}(j,i,y^{\nu:t},u)\nonumber\\ &=\sum_{y^{\nu:t}}\max_{u\in\mathcal{U}}\sum_{i=1}^{|G|}P_{\mathcal{U}|I}(u\ |\ i)P_I(i)\nonumber\\ &\quad\quad\quad\left(\sum_{j=1}^{|\widetilde{G}|}P_{Y^{\nu:t}|J}(y^{\nu:t}\ |\ j)P_{J|I}(j\ |\ i)\right). \end{align} Similarly, we have \begin{align}\label{eqn:demoninator_ml_2} \sum_{j=1}^{|\widetilde{G}|}\max_{u\in\mathcal{U}}P_{\mathcal{U},J}(u,j)&=\sum_{j=1}^{|\widetilde{G}|}\max_{u\in\mathcal{U}}\sum_{y^{\nu:t}}\sum_{i=1}^{|G|}P_{J,I,Y^{\nu:t},\mathcal{U}}(j,i,y^{\nu:t},u)\nonumber\\ &=\sum_{j=1}^{|\widetilde{G}|}\max_{u\in\mathcal{U}}\sum_{i=1}^{|G|}P_{\mathcal{U}|I}(u\ |\ i)P_{I}(i) P_{J|I}(j\ |\ i). \end{align} From \cref{eqn:matrices_1,eqn:matrices_2}, we can see that \cref{eqn:demoninator_ml_1,eqn:demoninator_ml_2} can be expressed using matrix operations \begin{align*} &\sum_{j=1}^{|\widetilde{G}|}\max_{u\in\mathcal{U}}P_{\mathcal{U},J}(u,j)=\text{Trace}\left(\Lambda\Delta\Phi_1\right),\\ &\sum_{y^{\nu:t}}\max_{u\in\mathcal{U}}P_{\mathcal{U},Y^{\nu:t}}(u,y^{\nu:t})=\text{Trace}\left(\Theta\Lambda\Delta\Phi_0\right), \end{align*} Furthermore, $\Phi_1$ is a solution to the following problem, \begin{align*} \Phi_1=\argmax_{\Gamma}\text{Trace}(\Lambda\Delta\Gamma), \end{align*} where the maximization is taken over all column stochastic matrices $\Gamma$. Since $\Phi_0,\Theta$ are column stochastic matrices, we have \begin{align*} \text{Trace}\left(\Lambda\Delta\Phi_0\Theta\right)\leq \text{Trace}\left(\Lambda\Delta\Phi_1\right), \end{align*} and thus \begin{align*} \sum_{y^{\nu:t}}\max_{u\in\mathcal{U}}P_{\mathcal{U},Y^{\nu:t}}(u,y^{\nu:t})\leq\sum_{j=1}^{|\widetilde{G}|}\max_{u\in\mathcal{U}}P_{\mathcal{U},J}(u,j). \end{align*} Hence, for a fixed random variable $U$ that is a randomized function of $I$, we have \begin{align*} \frac{\sum_{y^{\nu:t}}\max_{u\in\mathcal{U}}P_{\mathcal{U},Y^{\nu:t}}(u,y^{\nu:t})}{\max_{u\in\mathcal{U}}P_{\mathcal{U}}(u)}\leq\frac{\sum_{j=1}^{|\widetilde{G}|}\max_{u\in\mathcal{U}}P_{\mathcal{U},J}(u,j)}{\max_{u\in\mathcal{U}}P_{\mathcal{U}}(u)}. \end{align*} Using the following equations\cite{issa2016operational}, \begin{align*} \mathcal{L}_{\text{max}}(I\to Y^{\nu:t})&=\sup_U \frac{\sum_{y^{\nu:t}}\max_{u\in\mathcal{U}}P_{\mathcal{U},Y^{\nu:t}}(u,y^{\nu:t})}{\max_{u\in\mathcal{U}}P_{\mathcal{U}}(u)},\\ \mathcal{L}_{\text{max}}(I\to J)&=\sup_U \frac{\sum_{j}\max_{u\in\mathcal{U}}P_{\mathcal{U},J}(u,j)}{\max_{u\in\mathcal{U}}P_{\mathcal{U}}(u)}. \end{align*} to compute maximal leakage, where the supremum is taken over all randomized functions $U$ of $I$, we have \begin{align*} \mathcal{L}_{\text{max}}(I\to Y^{\nu:t})\leq\mathcal{L}_{\text{max}}(I\to J). \end{align*} The proof is now complete. \section{Proof of \cref{prop:equiv_conditions}}\label[appendix]{sec:AppProp2} $(\Rightarrow)$ Suppose the distribution $\phi$ on $\{1,\ldots,n\}$ satisfies \cref{eqn:equiv_prop_1}. Define $\xi:I_1\to \mathbb{R}$ and $\delta:I_1\times I_1 \to\{0,1\}$ such that \begin{align*} \xi(i)&=\min_{j\in I_1}\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\quad\text{for $j\in I_1$},\\ \delta(j,i)&=\begin{cases} 1\quad\text{if $j=\argmin \sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}$},\\ 0\quad\text{otherwise.}\\ \end{cases} \end{align*} We can check that $\xi$ and $\delta$ as defined satisfy \cref{eqn:eqn:equiv_prop_2_1,eqn:eqn:equiv_prop_2_2,eqn:eqn:equiv_prop_2_3,eqn:eqn:equiv_prop_2_4}. $(\Leftarrow)$Now suppose that there exist functions $\xi:I_1\to \mathbb{R}$ and $\delta:I_1\times I_1 \to\{0,1\}$ such that the distribution $\phi$ on $\{1,\ldots,n\}$ satisfies \cref{eqn:eqn:equiv_prop_2_1,eqn:eqn:equiv_prop_2_2,eqn:eqn:equiv_prop_2_3,eqn:eqn:equiv_prop_2_4}. Fix $i\in I_1$. From \eqref{eqn:eqn:equiv_prop_2_3}, we have \begin{align*} \sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\geq \xi(i), \end{align*} for each $j\in I_1$. Taking minimum over $j\in I_1$, we obtain \begin{align*} \min_{j\in I_1}\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\geq \xi(i). \end{align*} From \eqref{eqn:eqn:equiv_prop_2_2}, we have \begin{align*} \sum_{j\in I_1}\delta(j,i)=1. \end{align*} Since $\delta(j,i)\in\{0,1\}$, there exists a unique $j'$ such that $\delta(j',i)=1$. Putting this together with \cref{eqn:eqn:equiv_prop_2_4}, we obtain \begin{align*} \min_{j\in I_1}\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}=\xi(i). \end{align*} By \cref{eqn:eqn:equiv_prop_2_1}, we obtain\begin{align*} \max_{i\in I_1} \min_{j\in I_1}\sum_{c=1}^n\phi(c)\KLD{T_cg_i}{T_cg_j}\leq \epsilon_1. \end{align*} The proposition is proved. \section{Proof of \cref{prop:optimality}}\label[appendix]{sec:AppProp3} Let $q_1^\dagger,\ldots,q_K^\dagger$ be an optimal solution to Problem~\eqref{eqn:optimize_relaxed_formulation} under the decentralized QCD setting, $P_{J|I}^\dagger$ be the corresponding conditional probability distribution of $J$ given $I$, and $\mu^\dagger$ be the corresponding optimal value. Since the observations obtained by the sensors are mutually independent, we have \begin{align*} \E[\KLD{\widetilde{g}_I}{\widetilde{f}}]=\sum_{k=1}^K\E[\KLD{T_{q_k}g_{k,I}}{T_{q_k}f_{k}}]. \end{align*} By our construction of $q^*_k(P_{J|I}^\dagger)$, we have \begin{align} \label{eqn:prop2_1_1} \begin{split} &\E[\KLD{T_{q_k^*\left(P_{J|I}^\dagger\right)} g_{k,I}}{T_{q_k^*\left(P_{J|I}^\dagger\right)} f_k}] \\ &\quad\geq \E[\KLD{T_{q_k^\dagger} g_{k,I}}{T_{q_k^\dagger} f_k}], \end{split} \end{align} for each $k\in\{1,\ldots,K\}$. Let $\mu^*$ be the value achieved by the cost function in Problem~\eqref{eqn:optimize_relaxed_formulation} corresponding to $\{q_1^*(P_{J|I}^*),\ldots,q_k^*(P_{J|I}^*)\}$ and we obtain \begin{align} &\mu^*=\sum_{k=1}^K\E[\KLD{T_{q_k^*\left(P_{J|I}^*\right)} g_{k,I}}{T_{q_k^*\left(P_{J|I}^*\right)} f_k}]\label{eqn:prop2_1}\\ &\quad\geq \sum_{k=1}^K\E[\KLD{T_{q_k^*\left(P_{J|I}^\dagger\right)} g_{k,I}}{T_{q_k^*\left(P_{J|I}^\dagger\right)} f_k}]\label{eqn:prop2_2}\\ &\quad\geq\sum_{k=1}^K \E[\KLD{T_{q_k^\dagger} g_{k,I}}{T_{q_k^\dagger} f_k}]=\mu^\dagger\label{eqn:prop2_3} \end{align} where the inequality from \eqref{eqn:prop2_1} to \eqref{eqn:prop2_2} is a consequence of our choice of $P_{J|I}^*$ in \eqref{eqn:cases_2} and the inequality from \eqref{eqn:prop2_2} to \eqref{eqn:prop2_3} is obtained by summing \eqref{eqn:prop2_1_1} over $k\in\{1,\ldots,K\}$. Since $P_{J|I}^*$ also satisfies \begin{align*}\mathcal{L}(I\to J)\leq\epsilon,\end{align*} $\{q_k^*(P_{J|I}^*),\ldots,q_k^*(P_{J|I}^*)\}$ is also an optimal solution to Problem~\eqref{eqn:optimize_relaxed_formulation}. The proof is now complete. \bibliographystyle{IEEETran}
{'timestamp': '2020-09-21T02:18:18', 'yymm': '2009', 'arxiv_id': '2009.08963', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08963'}
arxiv
\section{Motivation and Background} After three decades of continuous growth~\cite{woodall_measuring_2017}, the Web has become an integral part of our society. It is designed as an open and transparent system, but more recently algorithmic systems that neglect these principles populate the Web. Exemplary of these systems are recommender systems, which have different impacts ranging from societal discourses (e.g., the British EU referendum or the U.S. presidential election of 2016) to profane details of everyday life, such as when choosing a product or service, a place to spend the holidays, or consuming personalized entertainment products. On the whole range of their usage, recommender systems are often interpreted as algorithmic decision support systems that frequently include discussions on bias (e.g.,~\cite{oneil_weapons_2016}). One of these frequently raised issues is that of \emph{algorithmic bias}, where specific groups of people based on gender, ethnicity, class or ideology are systematically discriminated by algorithmic decisions~\cite{baeza-yates_bias_2018}. These discussions indicate a growing discomfort with the algorithmic advances both used in and facilitated by the Web. To this end, ongoing design discourses urge engineers to consider explaining the presence and function of algorithms to end users~\cite{kuang_next_2017}. Lawmakers, too, are increasingly called upon to respond to issues such as algorithmic bias. Exemplary of the latter is the General Data Protection Regulation (GDPR) by the European Union, which seeks to curtail violations of data privacy and unregulated profitisation from user data. Selbst and Powles go so far as to say that the GDPR effectively guarantees a ``right to explanation'' of algorithmic processes to end users~\cite{selbst_meaningful_2018}. This right to explanation is understood as an explicit challenge to the discipline of Human-Computer Interaction (HCI); to be met with concrete means of representing and explaining algorithmic processes. In HCI, this challenge aligns with the discourse of \textit{algorithm awareness}. Hamilton and colleagues define algorithm awareness as the extent to which a user is aware of the existence and functioning of algorithms in a specific context of use~\cite{hamilton_path_2014}. However, the scope of the term algorithm awareness is not yet clearly defined, partially a result of the lack of experimental results associated with the discourse. As a consequence, it is unresolved whether algorithm awareness is the result of unearthing new methods of interaction, novel forms of representation, finding means of explaining algorithmic processes, or all of these aspects taken together. Similarly, its methodological perspective is vaguely defined. Are algorithm-aware designs, for example, a result of a critical technical practice~\cite{sengers_reflective_2005}, or are they a new form of human-centered design? If algorithm awareness as a principle is to contribute to an understanding of web-based algorithmic systems today (and tomorrow), these methodological shortcomings need to be addressed. In our research, we focus on one specific aspect from the discourse of algorithm awareness, the aspect of algorithm representation. We first discuss related work from the areas of HCI, Computer-Supported Collaborative Work (CSCW), and Science and Technology Studies (STS). We argue that algorithm awareness should be understood within the context of human-technology relations since algorithmic systems increasingly impact how we see the world. We then introduce a use case which allows for studying different representations for algorithm awareness because of its open design. The use case is situated in the peer production system Wikidata, in which the completeness recommender Recoin is being used by editors to receive recommendations for their next edits. As opposed to commercial web-based systems, the design principles of Wikidata give as access to all necessary information available regarding Recoin's engineering and usage. We can, thus, reflect on the various decisions made during Recoin's development and can suggest different modes of representing the algorithmic system by considering the dimensions of explainability and interactivity. Our research makes the following contributions: We provide experimental results to be used in the continuing development of the discourse on algorithm awareness. This concerns insights on design measures, namely textual explanation of algorithmic logic and interactive affordances, respectively. Our results suggest that the provision of more interactive means for exploring the mechanism of the algorithm for users has significant potential, but that more research is needed in this area. As for conducting experiments in this context, we provide first methodological insights, which suggest that measures of comprehension, fairness, accuracy and trustworthiness employed in the field are not yet exhaustive for the concerns of algorithm awareness. Our qualitative insights provide a first indication for further measures. The study participants, for example, were less concerned with the details of understanding an algorithmic calculation than with who or what is judging the result of the algorithm. In the following section, we discuss existing research from three perspective. First, we discuss the role of automation in peer production communities which leads to an increased usage of algorithmic systems in this context. Second, we review existing approaches that attempt to make these algorithmic systems transparent. Third, we combine these insights to argue for the urgency of researching algorithm awareness. This theoretical section is followed by a detailed introduction to Recoin, our use case, including its technical design as well as how it connects specifically to the topic at hand. Subsequently, we showcase our experiment, in which we detail the setup, design, results and analyses involved in our experimental study. Then, we proceed to discuss our insights. Finally, we conclude by outlining future work, in which we seek to undertake qualitative studies into how the evaluated modes of representation affect the relations between humans and algorithmic systems. \section{Related Work} \label{sec:relatedwork} \paragraph{\textbf{Automation in Peer Production Communities}} In contrast to the predominant commercial platforms on the Web, peer production communities, such as Wikipedia, OpenStreetMap, or Linux, provide a valuable alternative for people to share their ideas, experiences, and their collaboratively created knowledge openly~\cite{Benkler:2002vn,Benkler:2006pi}. In these communities automation is an integral component in order to handle especially "mindless, boring and often reoccurring tasks" \cite{Mueller-Birn:2013uq}. In Wikipedia, for example, various forms of algorithmic support exist; recommender systems, such as the SuggestBot help people to find suitable tasks~\cite{Cosley:2007fk}, neural networks, such as employed by ClueBots help to revert obvious vandalism~\cite{carter2008cluebot}, or semi-automated user interfaces, such as Snuggle help editors to socialize more efficiently with newcomers~\cite{Halfaker:2014ky}. Wikidata as Wikipedia's sister project profited from existing experiences in these automation efforts, thus, tools for vandalism detection were highly sophisticated from the beginning~\cite{Sarabadani:2017ia}. However, depending on how this automation is being used, the outcome goes in both directions. The unreflected use of automation can suppress participation of good-faith newcomers~\cite{Halfaker:2012uq}, and on the other hand, recommender systems on Wikipedia can significantly improve editor engagement and content creation~\cite{wulczyn2016growing}. Existing research shows, how the openness of peer production systems, such as the various Wikimedia projects (Wikipedia, Wikidata, etc.) enable researchers to investigate the manifold facets of automation in a real-world setting, and simultaneously support these projects in their goals of providing free high quality content. \paragraph{\textbf{Approaches to Algorithm Awareness}} With regards to related discourses such as on Fairness, Accountability and Transparency (FAT)~\cite{kohli_translation_2018} or Explainable Artificial Intelligence (XAI)~\cite{gunning_explainable_nodate}; algorithm awareness is more aligned to the study of lay's persons experiences of algorithmic systems. As with FAT and XAI, the concerns of the discourse are illustrative of pressing socio-cultural, economic and political needs. However, and similarly to FAT and XAI, algorithm awareness so far suffers from the lack of a methodological definition. Both in terms of design and engineering, implementation of algorithm-aware designs is challenged by two fundamental issues which can be derived from Hamilton and colleagues definition~\cite{hamilton_path_2014}: (1) the perceivability of an algorithm (e.g., results, logic, data) and (2) an actionable mode of representation that leads to informed usage. So far, the context of conducted algorithm awareness studies differs greatly. Studies have included, for example, both attempts at reverse-engineering web-based systems such as the Facebook's newsfeed~\cite{eslami_feedvis:_2015} as well as manipulating online peer grading systems~\cite{kizilcec_how_2016}. In the former, Eslami specifies that an algorithm-aware design should provide an actionable degree of transparency to algorithmic processes in order to promote a more informed and adaptive use of a specific system by its users~\cite{eslami_understanding_2017}. In her study, Eslami operationalizes the approach of \textit{seamful design}\footnote{The term seamful design is created as opposite concept to seamless design, where the algorithmic system fades into the background of human's perception.} to display results of the Facebook newsfeed algorithm that usually do not get displayed. In the latter, Kizilcec proposes another dimension to algorithm awareness ~\cite{kizilcec_how_2016}: the question of how much transparency of an algorithmic system is actually desirable to ensure understandability and usage. For his study, Kizilcec exposes participants in a peer-graded massive open online course to three kinds of transparency when confronted with their course grades. For each kind of transparency, he asked participants to rate their comprehension of the user interface and to what extent they evaluate the provided information as fair, accurate and trustworthy. These measures provide a first set of measures to empirically study how humans understand algorithmic systems. His results suggest a medium degree of transparency (in this case, textually disclosing the result and logic) as most effective. A high transparency (of the result, the underlying logic and raw peer grading data), he finds, is in fact detrimental to trust in the algorithmic system -- whether or not the received grade was lower than expected. A particular focus in algorithm awareness, as well as in XAI and FAT, are the concrete means by which humans may become more informed about algorithmic systems. A frequently deployed solution is the use of textual explanation of algorithmic processes or outputs across all discourses, featuring in contexts such as social media~\cite{rader_explanations_2018}, aviation assistants~\cite{lyons_engineering_2016}, online advertising~\cite{eslami_communicating_2018}, classification algorithms in machine learning~\cite{ribeiro_why_2016} and in online peer grading as discussed above~\cite{kizilcec_how_2016}. The prevalence of this solution may be interpreted as a clear indication for textual explanation being most suitable for establishing algorithm awareness. Within the aforementioned studies, various versions of textual explanations were studied comparatively. For example, even though Kizilcec questioned how much information a user may require, his various conditions of transparency all feature textual, explanatory solutions only~\cite{kizilcec_how_2016}. This may be considered a gap in the discourse. Returning to Hamilton and colleagues, the complexities of contemporary algorithmic systems do not only pose the question of how much humans may need to understand, but also in what way~\cite{hamilton_path_2014}. This suggests, for example, that experimenters should also explore differences between textual explanation of algorithmic logic and interactive, non-declarative solutions in the same context. \paragraph{\textbf{Urgency for Algorithm Awareness}} Due to the increase of automation on the Web, finding means for a better understanding of algorithms both by experts and lay users is particularly urgent. With algorithms, existing biases may become amplified substantially. In the discourse on recommender systems, bias has been observed as a challenge early on, and a major line of recommender systems research investigates how to avoid popularity bias, i.e., providing recommendations that are already known to satisfy a large number of users~\cite{fleder2007recommender,fleder2009blockbuster}. More recently, several works investigate the explainability of recommender systems~\cite{zhang2014explicit,he2015trirank}. Even open peer production systems such as Wikidata need to be seen in this context. That is, if there is a pre-existing bias in a knowledge base such as Wikidata, a recommender system may cause this bias to become self-perpetuating. Additionally, encoded bias may spread into the outputs of Wikidata APIs--thereby opaquely influencing the standard in domains that rely on Wikidata services. In his overview of bias on the Web, Baeza-Yates concludes that an awareness of bias (whether algorithmic or cultural) is the primary precondition for designers and engineers to mitigate potentially negative effects on users~\cite{baeza-yates_bias_2018}. The developer perspective as advanced by Baeza-Yates suggests that an engineering solution may be found with the potential to eliminate bias, whether by way of analyzing biased tendencies in the data used by a Web platform or running of extensive A/B-testing of subgroups \cite{kohavi_controlled_2009}. However, as repeatedly noted by Wiltse and Redstr\"om, the complexity of algorithmic systems in the modern Web troubles this suggestion. In their words, the Web is populated not by clear developer-client relations, but by \textit{fluid assemblages}, i.e. socio-technical configurations that change in various context of use \cite{redstrom_press_2015,wiltse_wicked_2015}. Bias, therefore, is not necessarily a definitive phenomenon for either human or machine. Accordingly, counting on purely technical solutions to eliminate bias needs to be up for debate. Instead, and as called for by various researchers from algorithm awareness, FAT and XAI, empirical studies that provide insights into how algorithmic systems (and the biases encoded therein) may be made more transparent. In the next section, we introduce the context of the open peer production system Wikidata, in which our use case, Recoin -- a property recommender-system -- is used. \section{Recoin: Property Recommender} Wikidata is an open peer production system~\cite{Vrandecic:2014hl}. Its structured data is organized in entities, where two types of entities exist: items and properties. Items represent real-world objects (individuals) or abstract concepts (classes). Each item is described by statements; for example, the entity \texttt{Q1076962} represents the human \textit{Chris Hadfield}. Each item is described by statements that follow a \textit{subject-predicate-object} structure (e.g., \textit{Chris Hadfield} (\texttt{Q1076962}) ''is instance of'' (\texttt{P31}) ''human'' (\texttt{Q5})). Thus, a property, i.e. predicate, describes the data value, i.e. object, of a statement. In October 2018, the community has more than 200k registered contributors with 19K active on a monthly base. They have created more than 570m statements on more than 50m entities. Even though Wikidata was founded to serve as a structured data hub across all Wikimedia projects, today, it is utilized for many other purposes; for example, researchers apply Wikidata as authoritative for interlinking external datasets, such as for gene data~\cite{burgstaller2016wikidata} or digital preservation data~\cite{thornton2017modeling}, or companies use Wikidata's knowledge graph for improving their search results, such as Google or Apple. A significant issue for Wikidata's community is consequently the quality of the data. Data quality is a classical problem in data management, however, in peer production settings such as in Wikidata, data quality assessment is complicated because of the continuous, incremental data insertions by its users, the distributed expertise and interest of the community, and the absence of a defined boundary in terms of its scope. Over the past years, the community has introduced many tools that address this challenge, that range from visualizing constraint violations to de-duplication tools and translation tools. One of these tools is Recoin that we present in more detail in the next section. \subsection{Technical Design} Recoin is a recommender system for understanding and improving the completeness of entities in Wikidata~\cite{ahmeti2017assessing,balaraman2018recoin}. A main motivation for implementing Recoin is Wikidata's openess, since it allows anyone to add nearly any kind of entities - items and properties. The latter led to a huge space of possible properties (4,859 properties as of July 2nd, 2018), with many applying only to a very specific context (e.g., ''possessed by spirit'' (\texttt{P4292}) or ''doctoral advisor'' (\texttt{P184})). Consequently, even experienced editors in Wikidata may lose track of which properties are relevant and important to a given item which might hinder them to improve data quality in Wikidata~\cite{razniewski2017doctoral}. Recoin is a gadget - an interface element - on Wikidata\footnote{Further information is available at \url{https://www.wikidata.org/wiki/Wikidata:Recoin}.}. A visual indicator informs a person about the relative completeness of an item and, moreover, it provides an editor with concrete recommendations about potentially missing properties on this item. Figure~\ref{fig:recoin}) shows the gadget on an item page on Wikidata. A visual indicator (icon on the top right) shows a color-coded progress bar that has five levels ranging from empty to complete. On the top of an item page, the recommendations are provided in an expandable list that shows up to ten of the most relevant missing properties. The idea of relative completeness is motivated by the situation that in absolute terms, measuring the completeness of an item is impossible in an open setting. The relative completeness, thus, considers completeness in relation to other, similar items. The relatedness function of Recoin considers two items as similar if they share the same class\footnote{An exception are items that are instance a of the class \emph{human}. In this case, the class ''occupation'' is used.}. The visual indicator of Recoin should not be understood as an absolute statement, i.e. level 5 (=complete) means, that all possible statements a given on the item page, but should rather be interpreted as a comparative measure, i.e. the statements on this item are more complete than on similar items. The completeness levels in Recoin are based on thresholds that are manually determined. It considers the average frequency of the 5 most frequent properties among the related ones to consider an item as \emph{most complete} (0\%-5\% average frequency), \emph{quite complete} (5\%-10\% average frequency), and so on. Furthermore, each user is shown 10 recommendations in order to avoid an overwhelming user experience. \begin{figure}[t] \begin{center} \includegraphics[width=6cm]{recoin} \caption{Recoin for the astronaut Chris Hadfield.} \label{fig:recoin} \end{center} \end{figure} \subsection{Need for Algorithm Awareness} \label{sec:needalawarness} As of September 25, 2018, Recoin is enabled by 220 editors on Wikidata\footnote{Further information are provided on the following page \url{https://www.wikidata.org/wiki/Special:GadgetUsage}.}, who created, based on Recoin's recommendations, 7,062 statements on 4,750 items. Even though Recoin is a straightforward approach for improving data quality on Wikidata, editors are hesitating to apply Recoin. Moreover, after persons used Recoin, they have raised a number of concerns. Based on existing discussions on Recoin's community page\footnote{\url{https://www.wikidata.org/wiki/Wikidata_talk:Recoin}} and on the mailing list, we identified three typical issues. Editors, for example, posed questions regarding the \textit{scope of the recommender}: \emph{``Not sure if Recoin looks at qualifiers \& their absence; if not, might this be something to think about?''}. The information provided by Recoin hindered editors to understand which data was being used to compute the recommendations. In another case, an editor was wondering about Recoin's underlying algorithm: \emph{``Something weird going on on Jan Jonker (Q47500903), stays on least complete.''}. In this case, the unchanging visual indicator of Recoin caused the user to \textit{question the functionality} of Recoin. Another user was concerned about the provided recommendation and its suitability for specific items: \emph{``How is Property:P1853 "Blood type" on this list, is that relevant (or even desirable) information for most people?''}. The user was not able to include its personal preferences - world view - in Recoin's recommendation. However, the third typical issue exemplified by Wikidata's editors raises a more genuine concern over the \textit{impact of Recoin on an already biased knowledge base} (e.g., the predominance of the English language~\cite{kaffee_glimpse_2017}). One editor stated: \emph{ ``This tool has its attractions but it does entrench cultural dominance even further as it stamps "quality" on items. The items with the most statements are the ones that are most likely to get good grades. Items from Indonesia let alone countries like Cameroon or the Gambia are easily substandard.''}.\footnote{The corresponding thread can be found on Wikidata's mailing list archive~\url{https://lists.wikimedia.org/pipermail/wikidata/2017-December/011576.html}.} On a surface read, this quote further substantiates the misunderstood nature of Recoin's function, as it is not intended as a unilateral absolute grading of the completeness of a particular item, but rather as a comparative tool that recommendations depend on the activities of the editors on similar items. However, and much more significant, the concern raised about cultural dominance is a very contemporary problem in algorithmic system design. Recoin fails to address this concerns by its current design and mediated function. In other words, the cultural bias in the recommended properties, even if not intended, seem to affect the usage of Recoin. Based on these insights, we wanted to better understand how a re-design of Recoin that considers algorithm awareness by focusing on explainability and interactivity can address the aforementioned issues. As opposed to existing research in this context, for example carried out by Eslami et al.~\cite{eslami_feedvis:_2015}, we do not require methods such as reverse engineering to understand the algorithmic system we are dealing with on a technical level. This knowledge is key to understanding the intricacies of the Web platforms today; as the ways in which an algorithm operates within a larger socio-technical context arguably also shapes the extent to which humans can or should be aware of it. Therefore, with an openly available recommender system in an open peer production system, we can conduct experiments that are closely tied to the actual practice of Wikidata editing activities, i.e., we can reflect on the technical and the social system similarly. In the following section, we introduce our experimental setup that help us to examine the impact of varying degrees of explainability and interactivity of the UI of the recommender system on humans. Following the concept of Recoin, our experiment featured a task of data completion. By measuring the interactions of participants with various designs during a data completion task and by eliciting self-reports, we sought to understand which design measures increased task efficiency while at the same time were most effective in increasing understanding of the algorithmic system. \begin{figure}[t] \begin{center} \includegraphics[width=6cm]{recoin-x} \caption{Recoin with Explanation \textit{(RX)}.} \label{fig:recoin-x} \end{center} \end{figure} \section{Experimental Setup} Informed by previous research, we designed two alternative UIs where each represents another degree of explainability and interactivity. Each user interface extends or replaces the previous version by specific design elements. In the following, we differentiate the original Recoin design (R1), the textual explanation design (RX), and the interactive redesign (RIX). The RX design is mainly inspired by previous work, from which we adapted the explanation design~\cite{kizilcec_how_2016}. The RIX design follows an interactive approach, where the user can interact with the outcome of the algorithm, thus, can explore how the algorithm outcome changes based on specific settings. The three UI designs are used in five experimental conditions (C1 to C4), supplemented by a baseline where participants only used the regular Wikidata interface. We explain these conditions in more detail in one of the following paragraphs. Based on these designs, participants should solve the same task across all conditions: adding data to a Wikidata item. We recruited 105 participants via Amazon Mechanical Turk (MTurk)\footnote{For more information please check \url{https://www.mturk.com/}.}, whereby each participant had a minimum task approval rate of 95\%, and a minimum amount of HITs of 1,000. Each participant received USD 3.50 (equivalent to USD 14.00 hourly wage) for full participation. We recruited only U.S. participants to reduce cultural confounds. We randomly and evenly distributed participants over our five conditions (i.e. 21 participants), also ensuring that no participant could re-do the task or join another condition by associating participants with qualifications. Each participants was given 10 minutes for task completion. In each condition, participants went through the same general procedure during task completion. At first, we provided a brief on-boarding, then we provided a task briefing. After the study participant carried out the task, she had to fill out an explicative self-report which contained the dimensions comprehension, fairness, accuracy and trust. Additionally, all participants obtained a task completion score, which we correlated with server activity to ensure that our final study corpus featured no invalid contributions. All data and results of our study will be available under an open license\footnote{Omitted for review.}. In the following, we outline the design decisions that have led to our three designs for Recoin in more detail. Then, we describe the task and the experimental design. \subsection{Design Rationales} In the following, we describe each UI approach of the recommender Recoin in more detail. For each user interface, we provide a corresponding visual representation. \subsubsection{Recoin User Interface R1} The original design of Recoin (cp. Figure~\ref{fig:recoin}) was primarily informed by existing UI design practices in Wikipedia. The status indicator icon was chosen to mirror the article quality levels on Wikipedia, such as "Good article" or "Featured article" \footnote{For more information we refer to \url{https://en.wikipedia.org/wiki/Wikipedia:Good_articles} and \url{https://en.wikipedia.org/wiki/Wikipedia:Featured_articles}.}. The used progress bar was motivated by existing visualizations in Wikipedia projects.\footnote{Examples are \url{https://www.wikidata.org/wiki/Wikidata:WikiProject\_Q5/lists/riders\_and\_their\_horse} and \url{https://www.wikidata.org/wiki/Wikidata:Wikivoyage/Lists/Embassies}.} Some parameters to represent the results of the Recoin recommender were determined without further considerations, such as the thresholds that represent the five levels of completeness. \begin{figure}[t] \begin{center} \includegraphics[width=8.2cm]{recoin-ix} \caption{Recoin Interactive Redesign \textit{(RIX)}.} \label{fig:recoin-ix} \end{center} \end{figure} \subsubsection{Recoin User Interface RX} Textual explanation of algorithmic logic is a wide-spread measure in the related work, and has been deployed in contexts such as social media~\cite{rader_explanations_2018}, aviation assistants~\cite{lyons_engineering_2016}, on-line advertising~\cite{eslami_communicating_2018} and classification algorithms in machine learning~\cite{ribeiro_why_2016}. For our design of RX, we drew inspiration from Kizilcec, who tested three states of transparency to understand algorithm awareness in on-line peer grading~\cite{kizilcec_how_2016}. Since the algorithm's function can be compared to Recoin (i.e., a rating algorithm), we adapted the format of Kizilcec's best solution and added a textual explanation to Recoin's user interface that describes the logic behind Recoin's calculation (cp. Figure~\ref{fig:recoin-x}). \subsubsection{Recoin User Interface RIX} Our interactive user interface (RIX, cp. Figure~\ref{fig:recoin-ix}) is based on insights gained from user feedback from Recoin's current users (cp. Section~\ref{sec:needalawarness}) and from the philosophy of technology as discussed by Verbeek~\cite{verbeek_what_2006}. Concerning the latter, we posit that Recoin \textit{actively} transforms the relationship an editor has with Wikidata and the entities therein. Through Recoin, Wikidata items that formerly were objects containing knowledge are now also objects that are rated. Technically, this rating is not an indication of absolute qualities, but one of community-driven standards, i.e. how the Wikidata community currently views a specific class of items. However, as illustrated in the various responses to Recoin, this mediation is not adequately communicated by Recoin's current design. Furthermore, in reflecting on Recoin with the original developers, we found that the comparative parameter of dividing the relevancy of the top five properties was arbitrarily chosen. In line with Mager~\cite{mager_internet_2018}, we consider transparency for this result of developer decision-making as essential. We operationalized these insights for RIX by considering how the community-driven aspect of Recoin could not only be displayed, but made interactively explorable. To this end we (1) included a reference to the class of the displayed entity (e.g., ''astronaut'' in our running example) in the drop-down title. This was designed to convey that this particular item is rated based on its class. Next, we augmented the drop-down itself extensively. We (2) substituted the relevance percentage with a numerical explanation for each suggested property (e.g., a relevance for the property 'time in space' of 67.03\% means that 549 out of 819 astronauts have this property). In contrast to a percentage, it was our intuition that relating to the class would highlight the community-driven aspect of Recoin. To strengthen this aspect further, we (3) included a range slider which allows filtering properties based on their prominence in the class (i.e., compare this entity based on their occurrence in a minimum/maximum of \textit{n} astronauts). Finally, we offered a way for directly interacting with Recoin's calculation: we (4) allowed our participants to reconfigure the relevancy comparison by (de-)selecting individual properties. Thereby, we wished to show that relevancy can be a dynamic, community-driven attribute in this algorithmic system. \begin{figure}[t] \begin{center} \includegraphics[width=8cm]{anon_briefing} \caption{Briefing page, with material added and resources for manually carrying out Recoin's functions and tutorial.} \label{fig:briefing} \end{center} \end{figure} \subsection{Task} For the study participants, we defined a typical editing task on Wikidata. We presented each study participant with a copy of Wikidata's user interface, to provide a most realistic task setting. First, the participants received a brief on-boarding for Wikidata, and, depending on the condition, for Recoin as well. Participants then proceeded to the task briefing page (cp. Figure~\ref{fig:briefing}). The participants were asked to add further properties and data to a Wikidata item. Additionally, we supplied participants with a short video tutorial that explained how properties can be added to an item on Wikidata. In each condition, the Wikidata item to be edited was \textit{Chris Hadfield}, a Canadian astronaut\footnote{The original page is provided here: \url{https://www.wikidata.org/wiki/Q1076962}.}. This item was chosen because it has a number of missing statements that are easily retrievable, and on the other hand, the item describes an astronaut who is probably well-known by our study participants which are U.S. based. Additionally, the occupation of astronauts was thought to be relatively neutral, as opposed to, for example, politicians or soccer players. We provided study participants with source material for the task composed of comparatively relevant and irrelevant pieces of information about \textit{Hadfield}. We also supplied a link to a very detailed Wikidata item with the same occupation, the US-American astronaut \textit{Buzz Aldrin}\footnote{\url{https://www.wikidata.org/wiki/Q2252}.}, and a link to a Wikidata query of the occupation ''astronaut''\footnote{Please check \url{http://tinyurl.com/ycnh3q37}.}, both with the intention to allow study participants to compare the given item with other items, i.e. we encouraged our participants to perform the functionality of Recoin manually. In addition, we provided a short video tutorial on how to add statements to Wikidata items. Following the task briefing, participants could choose to commence the task, which lead to the reconstructed Wikidata page for \textit{Hadfield}. Within a 10 minute limit, participants could then add statements to the item. We randomly assigned each participant to one of the conditions. Once the 10 minutes passed, participants were alerted that time was up, and that they should proceed to the self-report. Here, participants were confronted with a grade (from A-F) of their task. This grade was calculated through the difference in completeness before and after participants added information to the Wikidata item (e.g., when a participant additions increased the relative completeness of \textit{Hadfield} by more than 20\% but less than 30\%, they received a "B"). In correspondence to this grade, participant's were asked to rate their comprehension (5-point Likert scale), feelings of accuracy, fairness and trust (7-point Likert scale) of the recommender system. Again, due to substantial methodological and contextual similarities to Kizilcec's online study~\cite{kizilcec_how_2016}, we adopted the aforementioned measures to our study. Participants were also asked to expand on their ratings using free text fields. Upon submitting their ratings, participants were returned to the MTurk platform. \begin{table}[t] \begin{tabularx}{\columnwidth}{XL{6cm}} \toprule \textbf{Relevance} & Difference of the completeness value of the item before and after task completion. \\ \hline \textbf{Usage} & Number of times the recommender Recoin was used during task completion. \\ \hline \textbf{Compre\-hension} & To what extent do you understand how your task has been graded? \textit{(1) No understanding at all to (5) Excellent understanding.} \\ \hline \textbf{Fairness} & How fair or unfair is your grade? \textit{(1) Definitely unfair to (7) Definitely fair.} \\ \hline \textbf{Accuracy} & How inaccurate or accurate is the grade? \textit{(1) Very inaccurate to (7) Very accurate.} \\ \hline \textbf{Trust} & How much do you trust or distrust Wikidata to fairly grade your task? \textit{(1) Definitely distrust to (7) Definitely trust.}\\ \bottomrule \end{tabularx} \caption{Overview of measures employed in our online experiment.} \label{measure-table} \end{table} \subsection{Study Design} We conducted a between-subject study with five conditions. In the following, we define each condition and explain each measure we collected during the study. \subsubsection{Conditions} The first three conditions (baseline, C1, C2) were designed to test usage and understanding of the current version of Recoin, i.e. R1. We then proceeded to test the collected baseline against textual explanation (C3 with RX) as found in related work \cite{kizilcec_how_2016,gunning_explainable_nodate,phillips_interpretable_2018} and a redesign motivated by the shortcomings found therein (C4 with RIX). By comparing the results of the conditions, we aimed to gather insights on how design impacted human understanding of Recoin's function. All conditions are described in more detail next, followed by a description of the collected measures. \begin{itemize} \item \textit{Baseline}: Participants can add data on a Wikidata item \textit{without} Recoin being present in the user interface. \item \textit{Condition 1}: Participants can add data on a Wikidata item \textit{with} Recoin (R1) being present in the user interface. \item \textit{Condition 2}: C1 but Recoin is mentioned during the on-boarding process. \item \textit{Condition 3}: C2 but Recoin (RX) with explanation interface. \item \textit{Condition 4}: C2 but Recoin (RIX) with interactive interface. \end{itemize} \subsubsection{Task Measures} \textbf{Relevance}: As the improvement of data quality is the primary goal of Recoin, we wanted to ensure that we understood how each condition affected the change in completeness; independent of the quantity of contributions. Thus, we defined the metric \textit{relevance} as our dependent variable. Relevance is defined as the difference of the completeness values of Recoin before and after a participant added properties to the item. \textbf{Recoin Usage:} As a recommender system, it is particularly important to understand how each condition (aside from the baseline) affected the number of times Recoin was used directly to add information to an item. This is expressed by the measure \textit{usage} which serves as a dependent variable. \textbf{Time:} We fixed the time participants can add properties to an item to ensure that our conditions are comparable. The measure \textit{time} serves as our control variable. \textbf{Demographics:} All study participants were recruited via MTurk. While we assume that the majority of participants are US-Americans, we did not further specify our demographics. Thus, as is typical, demographics were our covariates. \begin{figure}[t] \begin{center} \includegraphics[width=7cm]{anon_questionnaire} \caption{Questionnaire after adding properties that lead to an increase in relevance of 25\%.} \label{fig:questionnaire} \end{center} \end{figure} \subsubsection{Self-Report Measures} Upon completion of the task, participants were directed to a self-report page (cp. Figure~\ref{fig:questionnaire}). The page prominently featured a grading of the participant task performance, which was calculated by normalizing the average comparative relevance, i.e. Recoin's assessment, of each contribution per participant. We graded the participants performance in their task (A-F) in order to elicit a reaction to the task even if participants did not notice, use or understood Recoin. We purposefully designed this grading to encourage study participants to reflect on the task, for example a participant may receive the grade F despite many additions to the item. Furthermore, we included ratings with the four factors from previous research on algorithm awareness~\cite{kizilcec_how_2016}: comprehension (5-point Likert scale), accuracy, fairness and trustworthiness (7-point Likert scale) of the algorithmic system. These measures should be strongly correlated according to the procedural justice theory in the related work. Low ratings of all measures, for example, would stem from violated expectations in an outcome~\cite{kizilcec_how_2016}. We asked all participants in addition, to expand on their ratings via text-fields for collecting qualitative data as well. \begin{table}[t] \begin{tabularx}{\columnwidth}{XC{1.5cm}C{2cm}C{2cm}} \toprule \textbf{Condition} & \textbf{\# All Edits} & \textbf{\# Recoin Usage} & \textbf{SD Recoin Usage}\\ \midrule \textbf{Baseline} & 249 & - & - \\ \textbf{C1} & 319 & 61 & 3.10 \\ \textbf{C2} & 382 & 91 & 8.56 \\ \textbf{C3} & 301 & 55 & 3.50 \\ \textbf{C4} & 281 & 71 & 4.25 \\ \bottomrule \end{tabularx} \caption{Number of edits, i.e. contributions in each condition, with the number of Recoin usage and standard deviation.} \label{edittable} \end{table} \subsection{Hypotheses} For our hypotheses, we were interested in testing the impact of Recoin on data completeness. Having provided participants with equal opportunities to add relevant data to the item \textit{Hadfield}, we examined whether Recoin improves the completeness of an item or not. Based on our analysis of the status quo (cp. Section~\ref{sec:needalawarness}), we did not expect study participants to actively use Recoin which lead to the following hypothesis: \textbf{$H_{1}$:} Using Recoin does not lead to significantly higher relevance in terms of data completeness. Based on the discussed literature on algorithm awareness, we assume that an user interface that conveys explainability and interactivity of the underlying recommender system leads to higher usage rates: \textbf{$H_{2}$:} The interface design of Recoin impacts the number of time participants used Recoin. Furthermore, we assumed that the effectiveness of algorithm aware designs would be captured most succinctly by the comprehension measure, which would accordingly allow us to distinguish the impact of the RX and RIX designs. Given the results of textual explanation employed in related work (cp. Section~\ref{sec:relatedwork}), we therefore hypothesized that: \textbf{$H_{3}$:} A textual explanation of the algorithmic logic leads to higher comprehension than the interactive redesign. Finally, to gain insights on methodological procedure, we sought to test the experimental self-report measures employed by Kizilcec~\cite{kizilcec_how_2016}. According to this research, the self-report measures should exhibit a high degree of correlation (Cronbach's $\alpha$ = 0.83). We therefore hypothesized: \textbf{$H_{4}$:} The correlation of self-report measures for textual explanation solutions will equally hold for testing the interactive solution. \subsection{Results} \begin{table}[b] \begin{tabularx}{\columnwidth}{XC{0.9cm}C{0.7cm}C{0.95cm}C{0.7cm}C{0.7cm}C{0.8cm}} \toprule \textbf{Condition} & \textbf{Grade} & \textbf{Rel.} & \textbf{Comp.} & \textbf{Fair.} & \textbf{Acc.} & \textbf{Trust} \\ \midrule \textbf{Baseline} & C & 11 & 2 & 4 & 4 & 4 \\ \textbf{C1} & C & 15 & \textbf{3} & 4 & 5 & 4 \\ \textbf{C2} & C & 19 & \textbf{3} & 5 & 5 & \textbf{5} \\ \textbf{C3} & \textbf{B} & 20 & \textbf{3} & 4 & 4 & 4 \\ \textbf{C4} & \textbf{B} & \textbf{21} & \textbf{3} & \textbf{6} & \textbf{6} & \textbf{5} \\ \bottomrule \end{tabularx} \caption{Median values for (1) task performance: \textit{Grades} dependent on the increase of \textit{Relevance}; (2) self-report: \textit{Comprehension} (1 - 5), \textit{Fairness}, \textit{Accuracy} and \textit{Trust} (1-7).} \label{mediantable} \end{table} We recruited 21 participants for each condition ($n = 105$). Overall, we received 1,532 edits (cp. Table~\ref{edittable}), with participants in the \textit{C2}-condition providing the most. In the \textit{C4}-condition, our interactive redesign, participants used Recoin most frequently, with more than half (61.09\%) of participants adding data via the Recoin interface at least once. This condition also included the most relevant contributions, with a median increase in completeness for the Hadfield item of 21\%. The median values of task performance, i.e., received grade and average increase in completeness, as well as the ordinal Likert-scales from the participant self-report, i.e., comprehension, fairness, accuracy and trust, can be seen in Table~\ref{mediantable}. We expected only a small amount of qualitative data. However, we found that displaying a grade in the self-report provided a highly effective trigger. Overall, 82 of our 105 participants chose to expand on their self-reported ratings via the provided text fields. This allowed us to probe participant statements for insights on specific subjective perspectives. In the following, we show the results of our analysis for each hypothesis by using the Kruskal-Wallis test for ordinal data and ANOVA for numerical data. We report the results of the algorithm awareness measures with Spearman correlation tests. Finally, we provide findings of our qualitative analysis of participant statements. \begin{figure}[t] \begin{center} \includegraphics[width=7cm]{Rel_Rplot07} \caption{Boxplot of the mean increase of completeness per condition.} \label{fig:rel-con} \end{center} \end{figure} \subsubsection*{$H_{1}$: Using Recoin does not lead to significantly higher relevance in terms of data completeness.} We reject this hypothesis. An increase of comparative relevance for the Hadfield item is highly dependent on using Recoin at least once ($p_{rel,rec} < 0.001$). Additionally, when looking at the increase of comparative relevance per participant as a function of the numbers of additions made via Recoin, we can see that the most significant difference occurs around 7 additions made (\textit{p\textsubscript{rel,numUse}} = 0.02). This shows that Recoin is highly efficient, as adding a majority of the ten recommended properties should lead to the highest increase in relevance. \subsubsection*{$H_{2}$: The interface design of Recoin impacts Recoin usage.} Even though the redesign (C4) slightly outperformed the other conditions in terms of the goal of the set task, we could not find any significant difference for the number of additions made via Recoin between C1, C2, C3, or C4 ($p = 0.74$). Therefore, we cannot confirm this hypothesis with statistical significance. \subsubsection*{$H_{3}$: Textual explanation of the algorithmic logic leads to higher comprehension than the interactive redesign.} We could not find statistically significant differences between ratings of comprehension between condition C4 (RX) and C5 (RIX) (\textit{p\textsubscript{comp,con}} = 0.98). Therefore, this hypothesis is not confirmed. \begin{table}[b] \begin{tabularx}{\columnwidth}{XC{0.9cm}C{0.9cm}C{0.9cm}C{0.9cm}C{0.9cm}} \textbf{Condition} & \textbf{Baseline} & \textbf{C1} & \textbf{C2} & \textbf{C3} & \textbf{C4} \\ \midrule \textbf{Cronbach's $\alpha$} & 0.79 & 0.75 & 0.67 & 0.65 & 0.51 \\ \end{tabularx} \caption{Cronbach's $\alpha$ for questionnaire measures across all conditions.} \label{crotable} \end{table} \subsubsection*{$H_{4}$: The correlation of self-report measures for textual explanation solutions will equally hold for testing the interactive solution.} We had to reject this hypothesis as well. Reacting to the large variance in C4 (cp. Figure~\ref{fig:rel-con}), we tested the validity of the questionnaire measures. As opposed to previous research~\cite{kizilcec_how_2016}, the self-reported measures are not correlated, instead they differ significantly (cp. Table~\ref{crotable}). This especially concerns C4, our redesign (RIX), where variance was very high (Cronbach's $\alpha = 0.51$). \begin{table}[t] \begin{tabularx}{\columnwidth}{XXXXX} \textbf{Factor} & \textbf{Comp.} & \textbf{Fair.} & \textbf{Acc.} & \textbf{Trust} \\ \hline \textbf{Comp.} & - & 0.19 & 0.15 & \textbf{0.33}$^*$ \\ \textbf{Fair.} & 0.19 & - & \textbf{0.40}$^*$ & \textbf{0.60}$^*$ \\ \textbf{Acc.} & 0.15 & \textbf{0.40}$^*$ & - & 0.16 \\ \textbf{Trust} & \textbf{0.33}$^*$ & \textbf{0.60}$^*$ & 0.16 & - \end{tabularx} \caption{Spearman correlation coefficients and p-values for C2-C4 for self-report measures \textit{Comp.=Comprehension}, \textit{Fair.=Fairness}, \textit{Acc.=Accuracy} and \textit{Trust} with $^*$ for $p < 0.05$.} \label{corrtable} \end{table} \begin{figure}[] \begin{center} \includegraphics[width=8cm]{C4-correlation-metrics} \caption{Spearman correlation coefficient matrix for C4 with $^*$ for $p < 0.05$; $^{**}$ for $p < 0.005$.} \label{fig:c4-corr} \end{center} \end{figure} As a reaction to the high variance, we conducted Spearman's correlation tests for the ordinal Likert scales used in the participant self-report measures. The most statistically significant correlative finding from our data is that trust and fairness share a medium to strong positive relationship in our experiment. This is shown across all conditions (\textit{r\textsubscript{t,f} = 0.65, p < 0.01}), as well as between those wherein Recoin was introduced during onboarding (C2, C3, C4) (\textit{r\textsubscript{t,f} = 0.60, p < 0.01}) (cf. table \ref{corrtable}). The predominant relationship of trust and fairness was reaffirmed for C2 and C3, the original design and the additional textual explanation respectively, as the strongest and most significant relationship (C2: \textit{r\textsubscript{t,f} = 0.73, p < 0.01}; C3: \textit{r\textsubscript{t,f} = 0.63, p < 0.01}). A further relationship of fairness and accuracy was found for C2 and C3, as a medium positive relationship (C2: \textit{r\textsubscript{f,a} = 0.52, p = 0.01}; C3: \textit{r\textsubscript{f,a} = 0.53, p = 0.01}). When participants used the interactive design of Recoin (RIX in C4), two different relationships emerged (cp. Figure~\ref{fig:c4-corr}). We found that the relationship between comprehension and fairness was strongest (\textit{r\textsubscript{c,f} = 0.61, p < 0.01}), closely followed by the relationship comprehension and trust (\textit{r\textsubscript{c,t} = 0.57, p = 0.01}). Surprisingly, the strong relationships found across all conditions were not present for the interactive design (cp. Figure~\ref{fig:c4-corr}). \subsubsection{Qualitative Analysis} Due to the high variance encountered in C4, and the unexpected lack of correlation between our self-report measures, we also expanded our analysis to participant statements. Accordingly, we sampled participant statements in order to probe specific subjective viewpoints. In this section, we showcase some preliminary insights. \subsubsection*{Base Trust in Open Knowledge Platforms} A recurring theme, when participants chose to expand on their rating of trust, was a certain \textit{base trust} in open knowledge platform. This occurred even when no explanation element was provided, and also when participants received a poor grade in the condition that did not feature Recoin (Baseline): \begin{quotation} \emph{``Considering there was not a good definition of how we would be judged, it is tough to know if the judging was actually fair or unfair. However, I tend to trust Wikipedia so Wikidata is probably trustworthy.''} Baseline-P18; graded \textit{D} \end{quotation} This \textit{base trust} was also extended to the algorithm specifically, as long as it abides by platform standards: \begin{quotation} \emph{``I assume that an algorithm is used to grade the task, in which case I assume that it's free of bias, which is why I do trust Wikidata a good deal when it comes to fairness. Provided, the algorithm itself works as it's supposed to.''} C2-P15; rated \textit{Trust} at \textit{6 (High)} \end{quotation} \subsubsection*{High task efficiency may not indicate algorithm awareness} The qualitative data also suggests that task efficiency in terms of the algorithm does not necessarily indicate algorithm awareness. On the contrary, the only participant that offered a fundamentally accurate account of Recoin received the second lowest grade possible: \begin{quotation} \emph{``My only theory is that it's graded based on the relevance of entries made in regards to his occupation (astronaut) while most of my entries concerned his family, his awards and etc, rather than his activity as an astronaut.''} C2-P15; graded \textit{D} \end{quotation} The commentary of a well-performing participant (graded \textit{B}) furthermore suggests that there may be a difference in understanding algorithmic logic and understanding the integration into the algorithmic system: \begin{quotation} \emph{``It seems odd that I would be the one putting in the data and it is grading me considering why couldn't it just put the data in itself if it is accurate enough to grade.''} C1-P17; rated \textit{Accuracy} at \textit{6 (Very accurate)} \end{quotation} Finally, and in a similar fashion, a participant formulated the key question they had to the algorithmic system as follows: \begin{quotation} \emph{``I understand that the relevance is graded, I'm not sure exactly how relevance is judged.''} C2-P2; rated \textit{Comprehension} at \textit{2 (Low Understanding)} \end{quotation} In summary, the unexpectedly high variance in the C4 condition, combined with the difference in correlative relationships across conditions, as well as our qualitative data, allow us to gather relevant insights for further research. In the next section, we will discuss limitations to our experiment, before concluding with the contributions as well as the implications for future work. \section{Discussion} First, we found no significant differences between the conditions in terms of average increases in completeness. However, this also suggests that the solution of textual explanation found in related work is not an inherently clear choice for algorithm awareness. This indicates that the design decisions for algorithm awareness are still methodologically unrefined. Additionally, we sought to understand if our alternative to textual explanation, one taking an interactive and non-declarative approach, could be measured according to the existing self-report measures as suggested by previous research~\cite{kizilcec_how_2016}. We found that the measures ''Comprehension'', ''Fairness'', ''Accuracy'' and ''Trust'' were not equally distributed across our experimental conditions. On the contrary, divergent correlative relationships emerged. The status quo design (R1) as well as the addition of textual explanation design (RX) featured the same strong relationships of trust and fairness as well as fairness and accuracy. In contrast, our redesign (RIX) did not exhibit these relationships, but rather suggested that comprehension was most influential. This was shown in the medium to strong correlation between comprehension and fairness as well as comprehension and trust. We therefore posit that expanding on these self-report measures for algorithm awareness is another, distinct area requiring further research. Moreover, the qualitative data we gathered also included insightful statements made by our participants. The phenomenon of \textit{base trust} that we encountered in participant statements is relevant for future algorithm awareness studies. If verified, it needs to be taken into account in cases where researchers may wish to abstract from platforms to look at specific problems. In a broader context, experiments on transparency in algorithmic systems, especially in recommender systems, are frequently undertaken in order to minimize or even eliminate bias. However, as also found by Ekstrand and Tian in experimenting with various recommendation algorithms~\cite{ekstrand_all_2018}, a complete solution to the problem of bias is improbable. That is to say: bias is inevitable, and is a result of humans and technology interacting. This position is echoed in the work of the philosopher of technology Verbeek, who argues that technology fundamentally \textit{mediates} human relations to a particular ''world'', i.e., groups of other humans, values, practices etc.~\cite{verbeek_what_2006}. Biases, especially those commonly not aware of, play an instrumental role here. The solution, then, may not be finding the best measure for an elimination of bias, but rather finding the most actionable measure for making bias transparent. Our experimental results align with this assertion insofar that participants had issues with understanding the algorithmic system not on the basis of whether or not something is correctly calculated, but rather who or what has the \textit{agency} for judging the result (e.g., the platform itself, the algorithm as a contained unit, peer review etc.). This, along with a lack of significant differences between conditions, indicates that our intuition to design for an interactive mediation of the community-driven basis for Recoin was useful. Therefore, we posit that promoting algorithm awareness by interactivity is a promising research area. Our study has a number of limitations that should be considered. As opposed to other work (e.g. \cite{gunning_explainable_nodate}), our research focuses on non-technical experts. Furthermore, by recruiting our study participants over MTurk, it can be easily asserted that the demographics of the platform predispose the experiment to cultural bias. Additionally, online experiments in general are limited in two ways. On the one hand, observation of the subtleties of human-technology relations is not possible, such as the non-linguistic ways in which interaction expresses itself and decision-making occurs. On the other, by using MTurk we did not study Wikidata editors, but novices which might have never before come into contact with Wikidata. This means that, while we certainly could infer insights on algorithm awareness and human-technology relations, studying the lived practice of Wikidata editors may reveal other or even contradictory results. \section{Conclusion} Our research was motivated by a wish to deepen our understanding of existing design parameters for algorithm awareness. We used the recommender system Recoin, employed in the online peer production system Wikidata, as a use case for our online experiments. In five different conditions, we provided the study participants with a varying degree of explanations and interactivity while using the recommender system. We were able to gather experimental data on the effect of various algorithm aware design measures, and to reflect on the validity of measures used in related work. However, our experiments alone are not yet exhaustive enough for us to reason more substantially about what human awareness means when algorithms are involved. Partly, this is due to the lack of longitudinal, qualitative data gathered from extensive and sustained use of Recoin. The participants of our experiments were predominantly unaware of Wikidata, and the task itself was both brief and controlled in terms of the knowledge that was provided. Wikidata lives and breathes from enthusiasts and domain experts that contribute extensively in their areas of interest. Thus, in future work, we seek to conduct studies that complement these results by probing individual and subjective use over time. This will allow us to understand more deeply, for example, how algorithm aware designs impact the relation between the Wikidata editors and the platform. From such studies, we plan to expand our framework to other use cases. Thereby, we hope to contribute to the urgent need for understanding how the increasingly ubiquitous algorithmic systems shape everyday life for and from the Web. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-09-22T02:02:31', 'yymm': '2009', 'arxiv_id': '2009.09049', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09049'}
arxiv
\section{Executive Summary} \subfile{sections/ExecSummary.tex} \pagebreak \section{Introduction}\label{sect:Intro} \subfile{sections/Introduction.tex} \pagebreak \section{The Features of Wargames} \label{sect:GameFeatures} \subfile{sections/WargameFeatures.tex} \pagebreak \section{Recent Progress in Deep Reinforcement Learning}\label{sect:DeepRL} \subfile{sections/DeepRL.tex} \pagebreak \section{Other Game AI techniques}\label{sect:OtherAlgos} \subfile{sections/OtherAlgorithms.tex} \pagebreak \section{Algorithms for Wargames}\label{sect:algoSummary} \subfile{sections/AlgorithmsForWargames.tex} \pagebreak \section{Platforms}\label{sect:Platforms} \subfile{sections/Platforms.tex} \pagebreak \section{Recommendations/Next Steps} \label{sect:Recommendations} \subfile{sections/Recommendations.tex} \pagebreak \small \bibliographystyle{abbrv} \subsection{Forward Model}\label{sect:ForwardModel} The forward model of a game takes the current state and the current set of actions, and transitions to the next state. Every computer game has such a model; without it the game would not function. However, in order to use the model in statistical forward planning and model-based reinforcement learning algorithms we need it to be both fast and easily copied. The model needs to be easily copied so that hypothetical actions can be applied to a copy of the game rather than the live game; this can be technically demanding due to the need to be very careful about which parts of state need to be deep-copied and is less bug-prone with heavy use of immutable data types. Speed is important for SFP algorithms in order to run many simulations for each decision to be made in the live game. For model-based RL, speed is less important but also useful due to the high sample complexity of these methods. With a copyable forward model a number of statistical planning-based algorithms are usable, such as Monte Carlo Tree Search (MCTS)~\cite{Browne_Powley_Whitehouse_Lucas_Cowling_Rohlfshagen_Tavener_Perez_Samothrakis_Colton_2012}, Combinatorial Multi-Armed Bandits (CMAB)~\cite{Ontanon_2017}, and Rolling Horizon Evolutionary Algorithms (RHEA)~\cite{Perez_Samothrakis_Lucas_Rohlfshagen_2013}. These are reviewed in Section~\ref{sect:SFP}, and are especially useful if there is room for `thinking' time between each move, anything from 40 milliseconds to a couple of minutes. A fast non-copyable forward model is still useful for a subset of AI techniques, most notably Deep Reinforcement Learning. In this case the game can only be run end-to-end from a configured starting point, and planning algorithms from a mid-point cannot be used. But each of these end-to-end runs can be treated as a single iteration to generate data for RL algorithms. For example OpenAI's state of the art Dota2 player is trained using Dota2 games that run at approximately half normal speed (for local optimisation reasons) with no copyable forward model~\cite{berner2019dota}. If we do have a copyable fast forward model then Expert Iteration is a technique that DeepMind used in AlphaZero to great effect, and which combines Deep RL with MCTS. This has also been helpful in other games such as Hearthstone~\cite{Swiechowski_Tajmajer_Janusz_2018} and Hanabi~\cite{Goodman_2019}, and is discussed in Section~\ref{sect:OtherAlgos}. Linked to the existence of a forward model is that in any game we have access to a semantic representation of the game state (unit positions, current capabilities, sighted enemies, terrain details etc.). In this case it is generally preferable to use these as input features for any technique, including Deep RL, and not pixel-based screen shots. This avoids the overhead of learning an implicit semantic representation from pixels and means that the AI technique can focus on learning an optimal plan directly. The prevalence of pixel-based inputs in the academic literature even when a forward model is available is due to the underlying goal of Artificial General Intelligence (AGI) that learns from raw sensory input. This is not relevant to wargames. Pixel-input is also much used in the literature due to the focus on self-driving technology, for which there is no forward model and raw sensory input is all that is available. Again, this is not relevant to wargames. \subsection{Unit-based techniques}\label{sect:unitTechniques} There are two distinct aspects of the use of units in wargames that lead to slightly different groups of techniques. These are: \begin{enumerate} \item \textbf{Compositional/Factorisation} techniques. These consider that rather than trying to come up with a single policy or plan across all available units it is quicker to come up with a plan for each unit individually. A set of individual unit plans/policies will be less effective than a global plan, but is much less computationally demanding and may be more akin to the way that unit operate in `reality'. \begin{itemize} \item{Combinatorial Multi-armed bandits (CMAB). Where multiple units can be given simultaneous orders each underlying unit action can be selected independently (a unit-based `arm'), and these amalgamated into a global `arm'~\cite{Ontanon_2017, Barriga_Stanescu_Buro_2017}. The global level allows for dependencies between units to be learned. } \item{Multi-Agent Reinforcement Learning (MARL) that learns a policy for each unit independently. The idea again is to benefit from the fact that the state space at least partially factorises into components for each unit, and learning these factorisations will be faster than the joint policy~\cite{Tan_1993}.} \item{Decentralised POMDPs~\cite{oliehoek2012decentralized, Amato_Oliehoek_2015}. This is an alternative way of phrasing the problem using a unit-based factorisation, however the literature generally focuses on problem-solving in a non-adversarial environment such as Fire Brigade units co-operating to extinguish a fire~\cite{Paquet_Bernier_Chaib-draa_2004}. Units are generally, but not always, homogeneous, with the benefit coming from learning an `easier' policy for a generic individual unit instead of a more complicated global policy.} \item Search a game-tree for each unit individually, and then amalgamate these results~\cite{Lisy_Bosansky_Vaculin_Pechoucek_2010}. A similar reduction of the combinatorial problems of many units is to group units together into smaller sub-groups, for example based on proximity or unit type, and only regard interactions in planning actions within each sub-group. \end{itemize} \item \textbf{Hierarchical} techniques. These consider decision-making at multiple levels, and is a natural fit for many aspects of wargaming. A higher-level strategic policy makes decisions about broad goals and transmits these goals to the lower-level units, which seek the best local way to implement them. This hierarchy can theoretically have many levels, but two is usually enough in the literature. \begin{itemize} \item Hierarchical approaches that set a high-level goal (e.g. `Attack', or `Defend Position'), then grouping of units to a sub-goal, and at the lowest level those specified units planning/learning to achieve their sub-goal~\cite{Stanescu_Barriga_Buro_2014, Churchill_Buro_2015}. Different algorithms can be used at each level in the hierarchy, varying between heuristic (expert) rules, Deep RL, tree-based search and others. This decomposition of the overall task reduces the inherent combinatorial explosion, with lower levels using a reward function to achieve a goal specified by the previous level. \item A similar approach can be used to decide which evaluation function to use in MCTS (or any search algorithm), for example by using Hierarchical Task Networks as the higher planning level to select which evaluation function to use in MCTS at the lower execution level~\cite{Neufeld_Mostaghim_Perez-Liebana_2019}. \item In the work of \cite{Ontanon_Buro_2015} in an RTS game, 19 high-level `tasks' (e.g. harvest resources, or rush player) and 49 low-level `methods' are used in hierarchical planning. By using A* pathfinding and `methods' as the lowest level in planning rather than primitive actions (such as `move north one hex') this technique leverages domain knowledge and performs well compared to MCTS or other methods. \item FeUdal Networks use Deep Reinforcement Learning with a `Manager' network setting a high-level goal, and then `Worker' network(s) attempting to fulfil the high-level goal~\cite{Vezhnevets_Osindero_Schaul_Heess_Jaderberg_Silver_Kavukcuoglu_2017, ahilan2019feudal}. This could be adapted to a wargame environment with one Worker network per unit, or group of units. \end{itemize} \end{enumerate} \subsection{Information Flow and Unit Autonomy}\label{sect:InfoFlow2} There is relatively little academic work on restricted Information Flow within Game AI, outside of more abstract games with deliberately constrained information channels, such as Hanabi or Bridge. In these games Deep Learning approaches have been used to learn conventions from scratch~\cite{Foerster_Song_Hughes_Burch_Dunning_Whiteson_Botvinick_Bowling_2018, Yeh_Hsieh_Lin_2018}. More relevant to wargames is work in Dec-POMDPs (Decentralized Partially Observable Markov Decision Processes) that have multiple autonomous agents on the same team working towards a single team-level goal~\cite{oliehoek2016concise, Paquet_Bernier_Chaib-draa_2004, Melo_Spaan_Witwicki_2012}. These were mentioned in Section~\ref{sect:unitTechniques} as appropriate to reducing the complexity of managing multiple different units by factorising a plan into semi-independent plans for each unit, and then amalgamating these to give a global plan. Within this framework there are several options that can be used to additionally model unit autonomy and information flow: \begin{itemize} \item \textbf{Global Information}. The default option is to use global information for each individual decision/plan. This provides benefit in reducing the computation of the overall plan, but assumes that each individual unit has the same information as the overall commander. \item \textbf{Local Information}. Each unit makes its decision using only locally available information. This models local autonomy more directly, is realistic in the case of a unit being cut-off from communication networks, and is computationally cheaper. \item \textbf{Information Cost}. Communicating information can be treated as an action in its own right, and the commander can choose to pass on some global information to units that they can then incorporate in local decisions. This can also work in the opposite direction. There is little work in this area, and the focus is on side-ways communication between the individual agents without any central command unit~\cite{Melo_Spaan_Witwicki_2012, wu2011online}. \end{itemize} Consider a concrete example of how the framework might be adapted in a wargame environment to provide low-level control of units once given a target by the commander (either human or computer). If guided by a utility function that applies suitable weights to secondary goals such as self-preservation and remaining unobserved as well reaching the target, then instead of following a centrally-plotted path the units could make their own decisions at each point based on their local information only, adapting this as they become aware of enemy (or friendly) units. There are no restrictions on the algorithms used for individual agent policies in a Dec-POMDP setting, and RL or search-based planning methods are both common. Co-evolution is also used~\cite{chades2002heuristic}, and this can be especially relevant with an absence of formal communication and heterogeneous units, where each unit type needs to adapt to the others. Graph neural networks (GNN) are a new emerging area of research in Deep RL that may be a useful tool for modelling information flow in wargames~\cite{zhou2018graph}. The basic idea behind a GNN is to model the dependencies of graphs via learned message passing between the nodes of the graph. The same neural network is used for all nodes in the graph to learn to integrate information from incoming nodes and to iteratively come up with a solution. In the case of wargaming, nodes in the GNN could represent units, while the connections between them reflect communication channels. A GNN could be trained to integrate information in a decentralised way and learn by itself to resolve communication issues. GNNs are discussed in a little more detail in Section~\ref{sect:GNN}. \subsection{Imperfect Information}\label{sect:POMDP} More realistic algorithms that work in large-scale POMDPs usually sample from some estimate of the unknown State Space: \begin{itemize} \item Perfect Information methods can be used by sampling possible states, then solving each sample, and then taking the `average' of the best actions. These approaches have theoretical flaws, but can work well in practise in some domains. To understand the detail of the flaws (`strategy fusion' and 'non-locality'), see~\cite{Frank_Basin_1998}. \item Monte Carlo search methods sample from possible hidden states and take an expectation over these. For example Information-Set MCTS samples one possible state of the world on each iteration~\cite{Cowling_Powley_Whitehouse_2012}, and Imperfect Information Monte Carlo Search (IIMC) does the same but with recursive opponent models that factor in what the opponent can observe to allow bluffing~\cite{Furtak_Buro_2013}. \item A distribution over hidden information (or `belief states') can be maintained with a particle filter and updated as the game unfolds to complement these methods~\cite{Silver_Veness_2010}. This approximates a full Bayesian update, which is usually intractable in a non-trivial game environment. \item Counterfactual Regret Minimisation (CFR) has worked exceptionally well in dealing with hidden information and player bluffing in up to 6-player Texas Hold'em Poker~\cite{Zinkevich_Johanson_Bowling_Piccione_2008, Lanctot_Lisy_Bowling_2014, Brown_Sandholm_2019}. However this required pre-calculation of a whole-game Nash Equilibrium strategy, which took 8 days on 64 cores for 6-players. Some work has compared MCTS to Monte Carlo versions of CFR, and found that while CFR can give better results, MCTS performs better for more limited computational budgets~\cite{Ponsen_2011}. \item Deep Reinforcement Learning can be used directly on the Observation Space, relying on implicit models of the hidden state to be built. This applies in Dota2 and also in other approaches to Poker~\cite{Deepstack_2017, berner2019dota}. \item Smoothed versions of both MCTS and Deep Learning play a mixture of a best response policy with an averaged fictitious play can help convergence in imperfect information environments~\cite{Heinrich_Silver_2015, Heinrich_Silver_2016}. \end{itemize} \subsection{Adversarial Opponents}\label{sect:AdvOpponent} The presence of adaptive, adversarial agents complicates any learning approach and introduces issues around the `Red Queen' effect, in which improving play will not necessarily improve the outcome if the opponent is also learning. This is a well-documented problem in co-evolution, with non-progressive cycles. Consider a simple case of Rock-Paper-Scissors. If the opponent has a tendency to play Rock, then we will learn to play Paper, which will prompt the opponent to learn to play Scissors\ldots and we can keep cycling \textit{ad infinitum}. It is important to use a variety of training opponents to avoid over-adapting the current policy to the current opponent. This is sometimes called a `Hall of Fame' and can be constructed from policies from earlier stages of the learning process~\cite{Cliff_Miller_1995, Moriarty_Mikkulainen_1996, Rosin_Belew_1997}. This ensures that we do not forget how to deal with particular strategy once we have defeated it once. In the Rock-Paper-Scissors example this would learn a strategy that can be effective against an opponent that plays any of Rock, Paper or Scissors, and converges to the Nash Equilibrium strategy. Approaches of this sort are used in AlphaStar, with multiple agents learning in parallel and playing each other in a Tournament to bootstrap strategies against each other without over-fitting to a single opponent (see Section~\ref{sec:continual_learning}). It is notable that master level Go in AlphaZero did not require this opponent variety and only used self-play against the current policy. However, AlphaZero (unlike the pure RL of AlphaStar) used MCTS planning on top of RL to select each move, which would be able to detect longer-term problems in a highly recommended move at the top level of the tree. AlphaZero did use distributed asynchronous learning, as did OpenAI's Dota2 work. This involves running many thousands of games simultaneously, each using a local copy of the current learned policy and providing updates to a central hub. This hub learns the policy using the traces of all games and periodically sends out updates. This helps avoid overfitting of the policy by including information from many different games at different stages in each update~\cite{mnih2016asynchronous, berner2019dota}. Another tool to consider in an adversarial environment where both sides are learning is the `Win or learn fast' principle~\cite{Bowling_Veloso_2002}. Roughly speaking, this ramps up the learning rate when we are losing training games compared to when we are winning. This gives better theoretical convergence guarantees in many cases. Opponent Modelling is the general idea that we think about what our opponent will do when planning our moves~\cite{Albrecht_Stone_2018}. In the context of a 2-player primarily zero-sum wargame the best approach is to learn the opponent's strategy simultaneously (with Deep RL or co-evolution), or use the same planning technique (e.g. MCTS). More sophisticated `theory of mind' approaches are unnecessary, and are primarily of benefit in general-sum games where there is an incentive for players to co-operate in at least some parts of the game. \subsection{Relative Reward Sparsity}\label{sect:RelativeRS} It is a triumph of RL (and especially DeepRL) that it is able to cope so well with such sparse rewards, and learn policy and value networks able to play classic games to a superhuman standard (see AlphaZero~\cite{AlphaZero_2017} and MuZero~\cite{schrittwieser2019mastering}). The algorithms rely on the fact that although the rewards are sparse, there are patterns in the game state that can accurately predict the value, and these patterns can be learned. It is essential that during learning, the learner gets to experience a range of outcomes; for example, if every playout ends in a loss, there is no learning signal. In RL if the inherent reward signal is too sparse then \emph{Reward Shaping} may be used to provide additional incentives and guide a learning agent towards successful behaviours. Related concepts are curriculum learning, where the agents learns tasks of increasing complexity on the path towards the full scale of problem, and intrinsic motivation, where the agent actively seeks out novel game states it has not seen before~\cite{bengio2009curriculum, sukhbaatar2017intrinsic, Justesen_Risi_2018}. $\epsilon$-greedy or softmax approaches often do very poorly with sparse rewards because they explore independently at each action/time-step. Instead we want to use an exploration policy that is `consistent' over time, making similar deviations when exploring, for example by biasing moves that go up-hill, or that attack at worse odds than normal. There is a rich literature on how we can encourage consistent exploration in RL, including evolution of the evaluation function or policy and intrinsic motivation to seek out novel states~\cite{Bellemare_Srinivasan_Ostrovski_Schaul_Saxton_Munos_2016, Ostrovski_Bellemare_Oord_Munos_2017, Salimans_Ho_Chen_Sidor_Sutskever_2017, Osband_Aslanides_Cassirer_2018, Osband_Blundell_Pritzel_VanRoy_2016}. Expert Iteration learns an interim reward signal that can be used in short-term planning towards a long-term goal that is beyond the planing horizon. This is a technique used in AlphaZero (amongst others) to learn a game evaluation function from RL, and then use this in MCTS search~\cite{Anthony_Tian_Barber_2017, Swiechowski_Tajmajer_Janusz_2018}. Over several iterations of this meta-process the local evaluation function is bootstrapped up to learn what local, short-term features are conducive to global, long-term success. Model Predictive Control (MPC) is another option if we have a forward model. This uses a planning horizon of $H$ to plan an optimal sequence of moves, and then re-plans after taking the first of these and seeing the effect in the environment~\cite{Lowrey_Rajeswaran_Kakade_Todorov_Mordatch_2018}. It is possible to learn an evaluation function (via RL for example) that is then used to optimally plan up to $H$ steps ahead using MPC. Learning an interim evaluation function can also provide useful information on what the agent is seeking to maximise in the short-term as useful to achieve a long-term goal, as the weights it uses may be quite different to those a human expert would design in. This is not always needed. For example the world-championship beating Dota2 work from OpenAI used a hand-designed short-term reward signal based on the team's domain knowledge. Where this domain knowledge exists, this is usually a better thing to try first, as it can give the desired level of play with less complexity. \subsection{Strategy Exploration}\label{sect:Exploration} In some use-cases the purpose of a wargame is not to find the single best course of action, but to explore a range of possible outcomes. This is especially true in the case of Concept or Force Development wargames. A number of techniques can be useful here to ensure that a diverse range of policies is found: \begin{itemize} \item \textbf{Multi-objective optimisation}. This starts from the premise that there may be multiple different objectives, and a policy is needed that can adapt at run-time to the actual objective. It hence seeks a range of different policies that are `optimal' in different ways~\cite{Deb_Agrawal_Pratap_Meyarivan_2000, Perez-Liebana_Mostaghim_Lucas_2016}. Given a set of different objectives, for example to a) minimise casualties, b) minimise fuel usage, c) maximise the enemy forces degraded, a multi-objective approach returns a set of policies on the `Pareto-front' of these dimensions. A policy on the Pareto-front is one which is better than all other policies for at least one linear combination of the different objectives; for example with 80\% weighting on minimising casualties, 20\% on fuel usage and 0\% on degrading the enemy. These can also be set as secondary targets to the main goal of the wargame to give policies which achieve the core victory objective with the best result on this secondary target. When the actual objective of a game is known (usually at game start, but this could change at some mid-point in line with Objective Variability discussed in Section~\ref{sect:ObjectiveVar}), then a relevant policy to be used can be selected from the trained library. See~\cite{mossalam2016multi} for a Deep Learning multi-objective approach. \item \textbf{Niching}. In Evolutionary Algorithms that maintain a population of policies, an additional bonus can be specified to ensure that this population remains diverse and does not converge too quickly on a single solution. This helps ensure that more of the possible policy space is explored. Classic options here can include a reward based on genome-distance, if this can be specified, but this may not automatically correspond to phenotypic distance. An alternative approach is to match the population against a diverse set of opponents (most commonly from a `Hall of Fame' from past generations), and divide the reward for beating each across all those population members that are able to. This rewards a policy that can defeat one or two opponents the others cannot, even if it has a low overall score~\cite{Rosin_Belew_1997}. For a more detailed review see~\cite{preuss2015multimodal}. \item \textbf{MAP-Elites}. Similar to Multi-objective optimisation, MAP-Elites is a recent algorithm that seeks to find diverse different solutions to the same problem~\cite{Mouret_Clune_2015}. It requires the specification of one or more dimensions of `phenotype', which for example could be `movement', `fuel usage' or `casualties suffered'. These are combined in a grid, and an optimal policy is sought for each cell (e.g. high movement, low fuel usage and low casualties). \item \textbf{Nash Averaging}. This can be used in combination with any of the above approaches, as well as in its own right. The common intuition is that a set of different policies may not be very diverse in practise. Nash Averaging can use game theoretic analysis on the results of tournaments between the policies (or their performance on a range of different scenarios) to extract the small sub-set that between them encapsulate the full diversity of the population~\cite{Balduzzi_Tuyls_Perolat_Graepel_2018}. Nash Averaging has the benefit of discounting duplicate opponents when assessing the strength of each player, and hence prevents a weak player appearing strong by being especially good at beating a cluster of self-similar weak players. \end{itemize} \subsection{Map-based}\label{sect:maps} One feature of many wargames, especially land-based ones, is that they are played out on a map of varying terrain features. There are a few approaches that are natural tools to use in this case, which we highlight here: \begin{itemize} \item \textbf{ Convolutional Neural Networks (CNNs)}. While we strongly recommend against learning to play wargames from raw pixel visual inputs, CNNs are still a useful tool for processing a symbolic version of a map. This is for example what a Go or Chess board really are. CNNs are used for example in~\cite{Barriga_Stanescu_Buro_2017} to process a symbolic representation of an RTS map to pick one of four scripts to use for a given unit. \item \textbf{Multi-unit path-finding}. A* is the classic algorithm in this case, but copes less well when multiple units are involved. In this case Conflict-Based Search is the current state-of-the-art~\cite{sharon2015conflict, boyarski2015icbs}. \end{itemize} \subsection{Human-like control}\label{sect:imitation} In some wargame use-cases (see Section~\ref{sect:wargameTypes}) there is a requirement for an AI to act in a `human-like' way, which may also involve following standard military doctrine for the force in question. Deep RL that has allowed agents to beat the world champions in some games, is less relevant for these use-cases, in which policies should not perform arbitrary policies but policies that are simultaneously high-performing and human-like. To encourage more human-like play, data from humans can be incorporated at different points in the training loop. \textbf{Imitation learning:} One typical approach is to collect human playtraces and then train a policy network in a supervised way to reduce the error between the predicted action for a certain state, and the action that a human performed. This approach was part of the original AlphaGo, in which a policy was trained to predict the most likely actions human would perform using databases from master-level tournaments~\cite{AlphaGo_2016}. This policy was then used to guide the MCTS tree-search by seeding initial values for each leaf node. In this example the method was used to get a better policy, not one that was specifically `human-like', and in later work (AlphaZero), the authors discard this approach~\cite{AlphaZero_2017}. Other examples have aimed at `human-like' behaviour via this approach, for example learning a player-specific driving style in a racing game~\cite{Munoz_Gutierrez_Sanchis_2013}. Beyond very simple cases `naive' imitation learning in this fashion can be fragile and lead to very poor performance when the agent moves even a small distance from the training data. To mitigate this algorithms such as \textsc{DAgger} can be used to generate new expert-like training data in situations where this deviation is most likely~\cite{Ross_Pineau_Chaib-draa_Kreitmann_2011}. This requires a policy that can give a reasonable 'expert' move in any given situation. In a wargame context human experts could indicate what the `correct' move is after the AI has taken one in a few trial games, and this used to augment the training data. \textbf{Reward shaping:} Another approach, which was deployed in AlphaStar, is to incorporate the distance to human playtraces into the reward function used for RL. For example, in AlphaStar, bots were rewarded for winning while at the same time producing strategies reminiscent of human strategies. The benefit of this approach is that it directly allows the agent to optimize for both metrics, without needing a dedicated purely supervised pre-training phase. This approach requires a suitable metric to be defined between human play and the strategy followed, and this often requires expert domain knowledge to specify what classic human strategies look like in game terms. \textbf{Inverse Reinforcement Learning:} This approach `inverts' the classic RL problem by seeking to learn the reward function an agent is using based on their behaviour~\cite{Ng_Russell_2000}. It is useful for tasks in which a reward function might be hard to define. Human playtraces are used to estimate the implicit reward function, and then this reward function is used in classic RL to learn a policy. This avoids some of the fragility issues with naive imitation learning, but is computationally more demanding. This approach has been used, for example, to construct a human-like AI in the game of Super Mario~\cite{Lee_Luo_Zambetta_Li_2014}. \textbf{Preference Based Reinforcement Learning: } A reward function can also be learned from human preferences~\cite{wirth2017survey}. In the approach by~\cite{christiano2017deep}, humans are presented with short video clips of agents performing Atari or MuJoCo robot control tasks, starting from random policies. The user selects which of the two policies they prefer; by repeatedly asking a human for the preferences, a model of the user's preferences is learned through supervised learning. Once this model is learned, RL can be driven by this learned model. This approach was successful applied to learning policies for different simulated robots. For our wargaming purposes, we imagine units could be trained through RL via self-play and a first estimate of a reward function. Every once in a while a user is asked to compare selections of agent policies, which should allow to refine the initial reward function to produce more and more human-like and realistic strategies over time. \vfill \subsection{From RL to Deep RL} An agent in reinforcement learning tries to solve a sequential decision making problem under uncertainty through a trial-and-error learning approach with respect to a reward signal \cite{sutton1998introduction}. The approach can often be described as follows: the agent receives a state $s_t$ at timestep $t$ from the environment and based on this state, samples an action $a_t$ from its policy $\pi(a_t|s_t)$. After performing the chosen action, the environment transitions to the next state $s_{t+1}$ and the agent receives a scalar reward $r_{t+1}$. The main objective in an RL setting is to optimize the agent's policy in order to maximise the sum of rewards. A particularly popular early RL method was Q-learning, which tries to learn an optimal state-action value function $Q(s, a)$ describing the best action $a$ to take in a particular state $s$. However, a challenge with this original tabular version of Q-learning is that the size of the table quickly becomes infeasible when the number of different states in the environment grows. Additionally, learning in such a sparse table would not be very efficient. A breakthrough introduced in 2015 by DeepMind was a method called Deep Q-Network (DQN), in which $Q(s, a)$ is represented by a deep neural network that learns low-level representations of high-level states \cite{atari}. The DQN approach was the first approach to being able to master many Atari games at a human level from pixels alone. Since then, many different deep reinforcement learning approaches combining the representational power of neural networks with reinforcement learning have shown impressive results in a variety of different domains. Two of the most impressive applications of Deep RL in games are DeepMind's work on StarCraft II \cite{vinyals2019grandmaster} and OpenAI's bot for Dota2 \cite{berner2019dota}. In the following we will review these approaches in terms of their computational and also engineering efforts. Both StarCraft II and Dota2 not only have a very high action space but many aspects are continuous (see Sections~\ref{sect:StateSpace} and~\ref{sect:ActionSpace}). Additionally, we will review other recent trends in RL that are particular important for wargaming, such as being able to continually learn, to produce explainable actions, or hierarchical deep RL methods. \subsection{Dota2} One of the potentially most relevant applications of deep RL to games, in regards to the challenges faced in typical wargames, is OpenAI's OpenFive bot \cite{berner2019dota}. This was the first AI system to defeat world champions at an e-sport game. In contrast to DeepMind's work on AlphaStar that learns from pixels, OpenFive learns from pre-processed information on enemy and unit locations. This setup is likely more relevant for an AI that is tasked with playing wargames such as CMANO or Flashpoint. Dota2 is a multi-player real-time strategy game with complex rules that have evolved over several years. The game is played on a square map with two teams of five players each competing against each other. Each player controls one of the five team members, which is a hero unit with special abilities. Players can gather resources through NPC units called ``creeps" and use those to increase the power of their hero by purchasing new items and improving their abilities. Dota2 is challenging for RL systems since it includes imperfect information (not all parts of the map are visible at the same time; see Section~\ref{sect:Observability}), long time horizons, and continuous state and action spaces. Games last for approximately 45 minutes and the state of the world is only partially observable, limited to the areas near units and buildings. \subsubsection{Neural Network architecture} The OpenFive neural network architecture that controls each agent in the game observes around 16,000 inputs each time step (Figure~\ref{fig:open_five}). The majority of these input observations are per-unit observations for each of the 189 units in the game (e.g.\ 5 heroes, 21 buildings, etc). The action space is divided into primary actions that the agent can take (e.g.\ move, attack) and actions are then parameterised with additional neural network outputs. Availability of actions was checked through hand-designed scripts. In total, the action space had 1,837,080 dimensions. Each of the five agents is controlled by replicas of the same network. Observations are shared across all members of the team (the network gets as input an indicator which unit it is controlling). The employed network is a recurrent neural network with approximately 159 million parameters, mainly consisting of a single-layer 4096-unit LSTM. \begin{figure}[ht] \centering \includegraphics[width=0.9\textwidth]{open_five_network.png} \caption{Neural architecture for OpenAI Five \cite{berner2019dota}.} \label{fig:open_five} \end{figure} As mentioned above, instead of working from the screen pixels directly, information about opponent positions etc, which would also be available to a human player, is pre-processed and given to the neural network directly. This way the system is focused on high-level decision making and strategic planning instead of visual information processing. Such as system thus aligns well with the setup likely encountered in wargames. Some game mechanics were controlled by hand-designed scripts, such as the order in which heroes purchase items. Additionally, while humans need to click on certain parts of the map to view it and obtain information, this is instantaneously available to the network at each time-step. This means the AI arguably has an advantage over human-players in reducing the number of clicks needed to get information, however this `click-to-view' is an artefact of the real-time game genre, and the key point for wargames is that the AI does not have access to information unavailable to human players. \subsubsection{Training Regimen} The network was trained with a hand-designed reward function that not only rewarded the agent for winning the game (which would be a very sparse reward) but includes additional signals such as if another character died, or which resources were collected. This reward function was constructed by people familiar with Dota 2, and according to the paper, not altered much during the project. Instead of manually designing reward functions, these can also be directly learned from human preferences, which we explain in more detail in Section~\ref{sect:imitation}. The particular RL training algorithm was Proximal Policy Optimization (PPO) \cite{schulman2017proximal}, which is a state-of-the-art policy optimization method. The system is trained through \emph{self-play}, in which the agent plays 80\% of games against itself and 20\% against an older version of its policy. The system implements a complicated training architecture with both GPU and CPU pipelines that handle the game rollouts, to reach the large number of samples needed for training: ``After ten months of training using 770$\pm$50 PetaFlops/s days of compute, it defeated the Dota 2 world champions in a best-of-three match and 99.4\% of human players during a multi-day online showcase." \cite{berner2019dota}. In conclusion, the OpenFive agent uses a very computationally expensive approach that required extensive fine-tuning of its reward function. Thus, in its current form, it is likely not the best approach for wargaming. \subsection{AlphaStar} Even more so than Dota2, StarCraft II is incredibly complex. Instead of five units, players in StarCraft control hundreds of units. Additionally players need to balance short and long-term goals. Therefore, AlphaStar \cite{vinyals2019grandmaster} uses a more complicated neural architecture than the OpenFive Dota agent, combining multiple recent deep learning advancements, such as a neural network transformer \cite{vaswani2017attention}, LSTM core \cite{hochreiter1997long}, pointer network \cite{vinyals2015pointer}, and centralised value baseline \cite{foerster2018counterfactual}. While an RL approach by itself was able to learn to play the game at a high-level, it is important to note that Grandmaster level in this game was only reached when starting training with human demonstrations. Training in a purely supervised way, the system was already able to reach gold level play. Training the agent further through RL, allowed AlphaStar to be above 99.8\% of officially ranked human players, reaching Grandmaster status. In Section~\ref{sect:imitation} we will go into more detail on how human demonstration and related methods can bias RL systems towards human-like play. The previously mentioned AlphaStar tournament-like training setup (also called the AlphaStar league) points to the fact that it is incredibly difficult to make sure agents do not overfit to a particular playstyle or opponent, which would allow them to be easily exploited. Interestingly, AlphaStar did not employ any search-based planning method. Instead, the LSTM-based network learned to do some form of planning by itself. However, training this very complex system comes at a cost: ``The AlphaStar league was run for 14 days, using 16 TPUs for each agent. During training, each agent experienced up to 200 years of real-time StarCraft play." \subsection{Frameworks for scaling up training of deep RL agents} \label{sec:deep_rl_frameworks} While AlphaStar and Dota 2 relied on their own engineered training system, a few frameworks have since been released that have the potential to reduce the engineering efforts required for large-scale distributed AI computing. Therefore, these systems are likely of relevance for improving capabilities in the area of AI and wargaming. We identified one particular framework, that could significantly reduce such engineering efforts. Fiber\footnote{https://uber.github.io/fiber/introduction/} is a framework recently released by Uber to more easily scale machine learning approaches such as reinforcement learning and evolutionary optimization to many different machines in a compute cluster~\cite{wang2019poet}. Fiber tries to address common issues with scaling RL up to a large number of computers, such as (1) time it takes to adapt code that runs locally to work on a cluster of computers, (2) dynamic scaling to the amount of available resources, (3) error handling when running jobs on a cluster, and (3) high learning costs when learning a new API for distributed computation. Fiber seems easy to learn, since it uses the same API as Python multiprocessing (which many RL approaches are already based on) and applications can be run the same way they are normally run without extra deployment steps. The framework is also supposed to work well with existing machine learning frameworks and algorithms. Other existing frameworks include PyTorch-based Horizon \cite{gauci2018horizon}, which allow end-to-end RL training but seems less flexible than Fiber to quickly try out new ideas. Dopamine is another tensorflow-based system \cite{castro2018dopamine} that is flexible to use but does not directly support distributed training. \subsection{Automatically Learning Forward Models for Planning} \label{sec:learning_fm} Wargames would benefit from agents that can do long-term strategic planning. While these abilities can in principle emerge in an LSTM-based neural network that learns to play (such as AlphaStar), this approach is in generally computationally expensive and requires very long training times. An alternative approach that has gained significant attention recently is to learn a model of the world through machine learning \cite{ha2018world} and then use that model for a planning algorithm \cite{schrittwieser2019mastering,hafner2019dream,lucas2019local,ha2018world}. This approach tries to combine the benefits of high-performing planning algorithms \cite{Browne_Powley_Whitehouse_Lucas_Cowling_Rohlfshagen_Tavener_Perez_Samothrakis_Colton_2012} with breakthroughs in model-free RL. For example, the muZero approach developed by DeepMind~\cite{schrittwieser2019mastering}, first learns a model of the environment's dynamics and then uses Monte-Carlo Tree Search at each timestep in the learned forward model to find the next action to execute in the actual environment. The benefit of this approach is that planning can happen in a smaller latent space, in which it is not trained to predict the next pixels but instead the reward, the action-selection policy, and the value function. These functions are trained through backpropagation based on trajectories sampled from a replay buffer. Using a small latent space for planning is computationally faster and only incorporates the information the system learns is needed to make effective decisions; for example by ignoring wall textures or pixel-animations of sprites, both of which take up a lot of 'information' in the raw pixel input and do not need to be included in a useful forward model. Their approach showed new state-of-the-art performance in both the visually rich domain of Atari games, and the board games Go, Chess, and Shogi. However, computational requirements are rather heavy for this approach. For the three board games, they used 16 TPUs for training and 1,000 TPUs for selfplay. Agents were trained for 1 million training steps using 800 simulation steps per move. For the Atari games, 8 TPUs were used for training and 32 TPUs for selfplay. In 2019, cost of a a cloud TPU v3 device was at \$8 US per hour. The time for training the Atari agents was 12 hours (for the final model, not taking into account models trained during experimentation) and is likely much higher for Go. We estimate one training run on Atari costs around 40 TPUs * 12 * 8 = \$3,840 US and running 36 hours training for the board games would be 1,000 TPUs * 36 * 8 = \$288,000 US. One thing to note is that algorithms are also becoming more efficient to train, and increasing in efficiency more than Moore's law would predict\footnote{https://openai.com/blog/ai-and-efficiency/}. For example, it now takes 44 times less compute to train a high-performing network for state-of-the-art image recognition than it took in 2012 (Moore's law would have only predicated a 11x cost improvement). Similar trends can be observed in other domains. For example, AlphaZero required 8x less compute than AlphaGoZero. The increasing commoditisation of GPU/TPU facilities in the cloud have also contributed to decreasing the overall cost of computation over time. \subsection{Explainable AI}\label{sect:ExplainableAI} To best inform decisions on future force structures based on the results from the wargaming experiments, it would be ideal if the algorithm could explain its decision. For example, did the AI attack the ship because it believed it to have a particular weapon on board and would its decision have been different, if that wasn't the case. While methods based on deep neural networks are often considered to be black boxes that are difficult to analyse, recent advances have allowed more insights into the decision making process of neural networks. These techniques can be roughly divided into approaches that aim to (a) visualize features, and (b) elucidate the relationship between neurons. Visualizing hidden layers’ features can give insights into what network inputs would cause a certain reaction in an internal neuron or in the network output. In contrast to optimizing the network’s weights, as normally done through gradient descent to train the network, one can use the same process to optimize the input to the network that would maximally activate a certain neuron \cite{nguyen2016multifaceted}. These techniques can help to identify what features certain neurons learned to pay attention to (Figure~\ref{fig:activation_max}). Instead of looking at only single features, more advanced methods look at combinations of features to determine which are important for the network to reach its decision \cite{olah2020zoom}. For example, to identify a car, these methods determined that the network learns to identify windows, car bodies, and wheels; only if all three are present does the network predict a car. \begin{figure} \centering \includegraphics[width=1.0\textwidth]{activation_maximization.png} \caption{Activation maximization \cite{nguyen2016multifaceted}. These show the input (in this case, an image) that would maximally activate a specific neuron, to show what patterns the neural network is looking for.} \label{fig:activation_max} \end{figure} Similarly these approaches can create saliency maps (Figure~\ref{fig:saliency}) that indicate how important each input signal is for the network outputs. Similar approaches cover parts of the image or blur them out and these occupancy-based salience maps can similarly give insights into what types of input are important for the network. While these approaches are typically applied to image-based inputs, they can also work for other input representations~\cite{Gupta_Puri_Verma_Kayastha_Deshmukh_Krishnamurthy_Singh_2020}. \begin{figure}[h] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.9\textwidth]{saliency_map.png} \label{fig:sfig1} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.9\textwidth]{ChessSaliency.png} \label{fig:sfig2} \end{subfigure} \caption{Saliency maps~\cite{greydanus2017visualizing, Gupta_Puri_Verma_Kayastha_Deshmukh_Krishnamurthy_Singh_2020}. The brighter pixels in (a) show the areas of the neural network input that affect the decision (i.e. changing them, changes the decision). In (b) the highlighted pieces are the ones that affect the neural network decision to move the bishop as shown on the right. } \label{fig:saliency} \end{figure} Additionally, by giving counterfactual examples to the network (e.g.\ instead of weapon type A, the network now receives weapon type B as input), can give insights into the situations that resulted in the network performing a certain action \cite{myers2020revealing}. \subsection{Continual adaptation and fast learning} \label{sec:continual_learning} While applications of Deep RL have shown impressive results, they only perform well in situations they have been trained for in advance and are not able to learn new knowledge during execution time. If situations or circumstances change only slightly, current Deep RL-trained AI systems will likely fail to perform well. These issues clearly limit the usage of these machines, which have to be taken offline to be re-trained while relying heavily on human expertise and programming. In the context of wargaming, a new unit type might be introduced or the strength of existing units could change. One approach would be to just retrain the system from scratch, but depending on the frequency of changes to the game and the computational training demands, this approach could quickly become infeasible. Because the code and settings for Dota 2 changed over time, OpenAI developed an approach they called `surgery' that allowed them to resume training. A similar approach could be deployed for wargaming. However, ideally, an approach should be able to continually incorporate new knowledge and adapt to new circumstances during deployment without having to be taken offline for training. While current deep learning systems are good at learning a particular task, they still struggle to learn new tasks quickly; meta-learning tries to address this challenge. The idea of meta-learning or \emph{learning to learn} (i.e.\ learning the learning algorithms themselves) has been around since the late 1980s and early 1990s but has recently gathered wider interest. A family of meta-learning approaches trains a special type of recurrent network (i.e.\ an LSTM) through gradient-based optimization that learns to update another network~\cite{ravi2016optimization, zoph2016neural}. In an approach based on reinforcement learning (RL) an agent learns how to schedule learning rates of another network to accelerate its convergence \cite{fu2016deep}. Typically, such networks are trained on several different tasks and then tested on their ability to learn new tasks. A recent trend in meta-learning is to find good initial weights through gradient-based optimization methods from which adaptation can be performed in a few iterations. This approach was first introduced by \cite{finn2017model} and is called Model-Agnostic Meta-Learning (MAML). A similar approach is used in Natural Language Processing (NLP), with pre-trained networks used as a starting point (having been trained on all of wikipedia for example, to gain a solid model of English syntax), and then specialised in some domain, for example by fine-tuning on Hansard to parse political speeches, or medical journals for an application in medicine. \subsection{Overfitting in RL agents}\label{sect:overfit} A challenge with employing RL agents for wargames is that pure RL algorithms often overfit to the particular scenario they are trained in, resulting in policies that do not generalize well to related problems or even different instances of the same problem. Even small game modifications can often lead to dramatically reduced performance, demonstrating that these networks learn reactions to particular situations rather than general strategies~\cite{kansky2017schema,zhang2018study}. For example, to train OpenAI Five, several aspects of the game had to be randomized during training (e.g.\ the chosen heroes and the items they purchased), which was necessary for robust strategies to emerge that can handle different situations arising when playing against human opponents. This type of overfitting can also be exploited for adversarial attacks. For example, Gleave et al.~\cite{gleave2019adversarial} showed that an agent acting in an adversarial way (i.e.\ a way unexpected to another agent), can break the policy of humanoid robots trained through RL to perform a variety of different tasks. In one interesting case, a robot goal keeper just falling to the ground, twitching randomly, can totally break the policy of an otherwise well performing goal-shooting robot. One idea to counter overfitting is to train agents on a a set of progressively harder tasks. For example, it has been shown that while evolving neural networks to drive a simulated car around a particular race track works well, the resulting network has learned only to drive that particular track; but by gradually including more difficult levels in the fitness evaluation, a network can be evolved to drive many tracks well, even hard tracks that could not be learned from scratch~\cite{togelius2006evolving}. Essentially the same idea has later been independently invented as curriculum learning~\cite{bengio2009curriculum}. Similar ideas have been formulated within a coevolutionary framework~\cite{brant2017minimal}. Several machine learning algorithms also gradually scale the difficulty of the problem. Automated curriculum learning includes intelligent sampling of training samples to optimize the learning progress \cite{graves2017automated}. Intelligent task selection through asymmetric self-play with two agents can be used for unsupervised pre-training \cite{sukhbaatar2017intrinsic}. The \textsc{powerplay} algorithm continually searches for new tasks and new problem solvers concurrently \cite{schmidhuber2013powerplay} and in Teacher-Student Curriculum Learning \cite{matiisen2017teacher} the teacher tries to select sub-tasks for which the slope of the learning curve of the student is highest. Reverse curriculum generation automatically generates a curriculum of start states, further and further away from the goal, that adapts to the agent's performance \cite{florensa2017reverse}. A promising recent method to combat overfitting in deep RL is to train agents on a large number of different procedurally generated environments \cite{risi2019increasing, justesen2018illuminating}. In the \emph{progressive procedural content generation} approach \cite{justesen2018illuminating}, an agent is presented with a completely new generated level each episode during reinforcement learning. If the agent is able to solve the level, difficulty of the generated environments is increased. This approach allows agents to solve levels they would normally not be able to solve, and also produces agents that overfit less and generalize better to other levels. \subsection{Hierarchical RL}\label{sect:HRL} A particularly relevant form of RL for wargaming is hierarchical RL (HRL). HRL aims to scale up RL by not just training one policy but a hierarchy of policies. In this hierarchy, some actions operate on low level actions while other levels can make use of these simpler actions to perform macro-actions. This type of abstraction greatly reduces the search space of the problem but finding the right level of abstraction remains an important challenge in HRL. Some of the most popular forms of HRL are `options frameworks' \cite{sutton1999between} and `feudal RL'. In the options framework, actions can take a variable amount of time. More specifically, options consist of an option policy, an initiation set, and a termination set. A particular option is available to take in a certain state $s$, if $s$ is part of that option's initiation set. In that case the policy is executed until it terminates stochastically according to some termination condition. Early work in this area dealt with pre-defined options but more recent work focuses on learning the appropriate options. \begin{figure}[h] \centering \includegraphics[width=0.7\textwidth]{feudal_network.png} \caption{FeUdal Network Architecture \cite{ahilan2019feudal}.} \label{fig:feudal} \end{figure} In feudal RL, levels of hierarchy within an agent communicate via explicit goals but not exactly how these goals should be achieved. More recent work in RL extends the idea of feudal RL to deep neural networks \cite{ahilan2019feudal}. In this work (Figure~\ref{fig:feudal}), a feudal system is composed of two different neural networks. A manager network sets goals at a lower temporal resolution for a worker operating at a higher temporal resolution. The worker performs primitive actions conditioned on the goal given by the manager network. This approach has shown promise in hard exploration problems such as the Atari game Montezuma’s revenge. While typical RL algorithms only reach very low scores in this game, the FeUdal approach allowed the manager to learn meaningful sub-goals for the worker, such as picking up the key in the environment or reaching the ladder. For wargaming, the feudal approach is likely more relevant than the options framework, since it already reflects the typical hierarchical troop structure in combat scenarios. \subsection{Deep Multi-agent Learning} OpenFive and AlphaStar present two different forms of deep multi-agent learning. OpenFive can be described as a distributed homogeneous multi-agent system, in which each agent is controlled by clones of the same network but there is no overall manager network. AlphaStar is using a different approach, in which one centralised manager network controls all the available units. Other approaches such as distributed heterogeneous multi-agent systems train a different neural network for each agent, based on approaches such as independent Q-learning (cite). However, it is difficult to scale these approaches to a large number of agents. Multi-agent learning and HRL methods have also been combined \cite{kumar2017federated}. An important factor to consider for wargaming is scalability. Ideally we do not want to retrain the whole system from scratch when a new unit type if introduced, which limits the use of centralised controllers. Heterogeneous multi-agent RL approaches are also divided into approaches in which the environment becomes partially observable from the point of each agent that might not have access to the whole state space. In the context of wargaming agents, we can assume that all agents have access to all information all the time. \vfill \subsection{Types of wargames}\label{sect:wargameTypes} Wargames are used by defence and military organizations for several distinct purposes. \begin{enumerate} \item Planned Force Testing. These are large-scale wargames involving tens to hundreds of participants in multiple different and collaborative commands. They are concerned with end-to-end testing of holistic military capabilities across logistics, diplomacy, theatre access and scenario aftermath as well as combat. Computer tools may be used for some of the detailed moderation, but these are primarily run as analogue exercises. \item Plan Variation Testing. This takes a single scenario plan, for example part of an outcome from Planned Force Testing, to consider in more detail. These are often run multiple times to analyse interesting branch-points that need human decision-making focus. \item Concept/Force Development. These wargames take a proposed concept or change to capability, such as a new rifle or autonomous land vehicle, and explore the associated strategy/tactics space to find viable concept combinations and potential doctrine suitable for the proposal. They will be at the minimum scale needed to test the proposal. \item Procurement. These wargames are the most constrained type. They are used in the context of a decision to purchase one type of equipment from a small set of options. The scenarios are tightly controlled and repeated multiple times to quantify as far as possible the differences between the options. Ideally these outcome differences would be analysed with changes to equipment but not military doctrine; with doctrine changed by old equipment; and with both doctrine and equipment changes. \end{enumerate} This study focuses on the potential use of AI techniques in computer-moderated wargames. These tend to be complex games with large state spaces and large action spaces, to name just two dimensions of complexity. Section~\ref{sect:GameFeatures} provides a comprehensive study of all the main aspects of a game that can make it difficult for an AI or human player to play it well. This focus on complex games is in contrast to abstract game-theory type games where the actions and rewards for each player form a payoff matrix, and the games have no intrinsic state. \vfill \subsection{Evolutionary Algorithms} Evolutionary Algorithms (EA) of various types are derivative-free \textbf{search} algorithms that start with a population of possible (often random) solutions, and make changes (mutations, cross-over) to the best of these solutions to come up with a new population of solutions; repeating this process until a sufficiently good solution is found. A major challenge is often finding a suitable representation (genome) of the solution that is amenable to the mutation and cross-over operators. EAs have some clear theoretical disadvantages over RL approaches; they are less sample efficient and cannot use the information from a gradient. In derivative-based RL (e.g back-propagation on Neural Networks), the policy or function being learned is updated with each individual action by gradient descent in the direction of (current) greatest benefit. In an EA the policy or function is only updated, at best, once after each full game in a random direction~\cite{Lucas_2008}. However, EAs can be much better at exploring large search spaces precisely because of their ability to take large random jumps, and if the fitness landscape is highly irregular then gradient-descent methods can get stuck in local optima (although there are various techniques such as momentum to reduce the risk of this happening). More advanced methods such as CMA-ES or NES also incorporate a form of pseudo-derivate to make bigger jumps in more promising direction~\cite{Hansen_Ostermeier_2001, Wierstra_Schaul_Glasmachers_Sun_Peters_Schmidhuber_2014}. CMA-ES in particular has a range of software libraries across different platforms to make it accessible. For example, using CMA-ES to evolve Deep Neural Networks has been found to be quite competitive with RL in Atari games \cite{Salimans_Ho_Chen_Sidor_Sutskever_2017}. Having a population of different solutions also enables niching techniques that reward a diverse set of solutions, and not just the best possible game score~\cite{preuss2015multimodal, Agapitos_Togelius_Lucas_Schmidhuber_Konstantinidis_2008, Rosin_Belew_1997}. This is a useful technique to explore the space of viable strategies, and not just generate a single `best' one. \subsection{Random Forests} Random Forests are a tool used in supervised learning, especially with structured data~\cite{breiman2001random}. In Kaggle competitions they have been the most common tool used by winning competition entries, along with the related XGBoost~\cite{chen2016xgboost}, with Deep Neural Networks a close second and preferred when image data is involved~\cite{Usmani_2018}. They consist of multiple Decision Trees, with each tree classifying the data by branching at each node on one or more of the data attributes (each node forms a binary \textit{if}\ldots \textit{then}\ldots \textit{else} condition). Aggregating the decisions of all the trees in the forest (as an ensemble method) gives much better performance than a single individual tree. Due to the innate discontinuity at each branch in a tree, decision trees can be effective at modelling policies or functions that have similarly sharp discontinuities in them. Trees/Forests are not used as much in recent Game AI research, but they can be a useful tool at times. For example decision trees have been used to provide an easily interpretable policy to teach players~\cite{Silva_Togelius_Lantz_Nealen_2018}, and also as a means of learning a forward model~\cite{Dockhorn_Lucas_Volz_Bravi_Gaina_Perez-Liebana_2019}. \subsection{Statistical Forward Planning}\label{sect:SFP} Statistical Forward Planning (SFP) algorithms are descendants in some respects of the classical min-max search used in Chess and Checkers research in the 1980s. The combinatorial explosion of large action spaces and branching factors prevents exhaustive search to a certain depth in the game-tree, and SFP methods do not attempt this. Instead they search stochastically, and use statistics from previous iterations to make the decision about where to search next. At each iteration a forward model simulates the effect of possible actions on the current game state in a `what if' scenario to obtain a value for the proposed plan. The crucial requirement is a forward model for these simulated rollouts. This is a notable difference to model-free RL methods , although model-based RL can use (or learn) a forward model to generate training data. Even so, in \textit{vanilla} RL the learned policy that makes decisions after training is complete does not use a forward model. \textit{Vanilla} SFP methods do not do any pre-training, but use the forward model to make a decision when an action is required. They need a computational budget to use for this, and everything else being equal are slower in actual play. (See Section~\ref{sect:Hybrids} for notes on exceptions to the \textit{vanilla} case.) Common SFP methods used in Game AI of possible relevance to wargames include: \begin{itemize} \item \textbf{MCTS}. Monte Carlo Tree Search expands the game tree by one node per iteration, and stores statistics at each node on the number of times each action has been taken from that node, and the average value that resulted. These are then used to balance exploitation of the best action with exploration of actions that have been tried relatively few times. See~\cite{Browne_Powley_Whitehouse_Lucas_Cowling_Rohlfshagen_Tavener_Perez_Samothrakis_Colton_2012} for a survey. \item \textbf{RHEA/OEP}. Rolling Horizon Evolutionary and Online Evolutionary Planning Algorithms use EAs to generate forward plans at each iteration, based on previously successful ones~\cite{Perez_Samothrakis_Lucas_Rohlfshagen_2013, Justesen_Mahlmann_Togelius_2016}. These methods divide their budget more equally at all depths in the game-tree, which can be an advantage over the more short-term focus of MCTS in some domains. \item \textbf{CMAB}. Combinatorial Multi-Armed Bandits are very similar to MCTS, and have been successful in RTS games, including MicroRTS and Starcraft~\cite{Ontanon_2017}. The crucial difference is that a global action is factored into contributions from each unit under the player's control, and statistics are maintained for each unit as well as at the global level. As with any SFP, the forward model is called over a number of iterations. On each of these an action is selected for each individual unit based on past statistics to balance exploration of new actions with exploitation of previously tried good actions, exactly as in MCTS. These are then combined to give a single `global' action. At each future iteration during planning a CMAB algorithm either selects the previous best `global' action, or samples a new individual action for each unit to create a new `global' action. This is a good approach with a large number of units, each of which can take its own action (as in wargames). \end{itemize} \subsection{Others} There are a number of older techniques used in commercial Game AI, such as hand-written Finite State Machines, Parameterised Scripts and Behaviour Trees~\cite{yannakakis2018artificial}. These are not learned (although RL and EA methods amongst other can be used to learn the best values in parameterised scripts for example), but have advantages in ease of debugging and interpretability. The example of the OpenAI work on Dota2, which used hand-crafted static heuristics (or scripts) in several decision areas, shows that in an application domain these can be a useful part of a full system, even if they are not stressed in the academic literature produced. \subsection{Hybrids}\label{sect:Hybrids} None of these AI approaches are the answer to all games, and some will work better on some problems than others. It is better to think of them as a tools that provide options to be combined with one another as needed, with no single silver bullet that will solve each and every problem. Applying an AI technique to a game (or any application) first involves understanding the features and structure of the game, and tuning the appropriate tools to this structure. Some illustrative examples of this hybridisation are listed below, and many more are covered in Section~\ref{sect:algoSummary}. \begin{figure} \includegraphics[width=1.0\textwidth]{EIDiag.png} \caption{Expert Iteration. Iterations of a Statistical Forward Planning algorithm generate data that is used to learn a policy, $\Pi(s)$, or an evaluation function $Q(s, a)$. This is then used in the next iteration of SFP to ratchet up performance.} \label{fig:ExpertIteration} \end{figure} \begin{itemize} \item \textbf{Expert Iteration}. One particularly powerful recent hybridisation, used by AlphaGo amongst others, is between Deep RL and SFP to give `Expert Iteration'~\cite{Anthony_Tian_Barber_2017, AlphaZero_2017, Tong_Liu_Li_2019}. This iterates i) playing games using SFP to generate training data that, ii) is used by Supervised RL to learn policies or evaluation functions used in the next round of SFP games (see Figure~\ref{fig:ExpertIteration}). In this way the quality of play ratchets up, and the overall cycle can be cast a Reinforcement Learning, with the SFP algorithm used as both policy improvement and valuation operator. This is discussed further in the context of wargames in Section~\ref{sect:RelativeRS}. \item \cite{Marino_Moraes_Toledo_Lelis_2019} use Evolutionary Algorithms to learn an Action Abstraction that provides the Actions used in SFP (specifically, CMAB is used). This provides slightly better results than previous work by the same authors that used an expert-specified Action Abstraction directly in CMAB. This is a good example that solutions can often be built up over time, learning one aspect of a game and using rough heuristics in others. Trying to learn everything from scratch at once can make the learning task much, much more difficult by not using scaffolding that is helpful to reach a good solution before it is discarded. \item \cite{Stanescu_Barriga_Hess_Buro_2016} use a Convolutional Neural Network to learn the value of a state from the map in an RTS, and then use the CNN as an evaluation function in MCTS to decide which of a small number of heuristic scripts to use at that point in the game. The CNN is pre-trained on a variety of different maps so that it will generalise reasonably well to unseen scenario maps. \item \cite{Horn_Volz_Perez-Liebana_Preuss_2016} investigate several hybrids between MCTS and RHEA in GVGAI play. The best overall algorithm uses RHEA of the first $X$ moves and then MCTS from that point. The precise hybrid that works best varies by game, for example they find that MCTS is better at dealing with adversarial opponents in a game, but can have problem where path-finding is most important. \item \cite{Lucas_Reynolds_2005} use Evolutionary Algorithms to learn Finite State Machines, and find that this is better at dealing with noisy data. \item A good example of constructing a system from disparate building blocks is~\cite{ha2018world}. They combine a Variational Autoencoder neural network to process a visual image, a Recurrent Neural Network as a memory component, and an evolutionary algorithm (CMA-ES) to evolve a neural network controller (policy). The first two components are trained first on game-play, and then the controller is evolved using the resultant learned model. \end{itemize} Algorithm are often constructed of commonly recurring components, and it can be helpful to consider how these interact in hybrids. \begin{itemize} \item Policy. The most obvious component is a policy that decides what action to take in any given situation. Usually abbreviated to $\pi(s, a)$ that defines a probability of playing each action, $a$, given the current state, $s$. Classically this is learned directly in policy-based reinforcement learning. In SFP and search-based approaches distinct policies can be used to decide which action to take in simulation using the forward model; these rollout policies tend to balance the taking the best action with exploring new actions to find a better one. \item State Evaluation Function. This provides a value for a state, or for a specific action in a state. In a game this is usually the percentage change of winning, or the total score estimated if that action is taken. Usually abbreviated to $V(s)$ for a state-evaluation function, or $Q(s, a)$ for an action-state evaluation function. Classically these are learned by reinforcement learning methods, such as Deep Q-learning. (Note that a learned $Q(s, a)$ can implicitly define a policy, for example by taking the action with the highest $Q$-value; with a forward model, a $V(s)$ function can be used in the same way.) \item Embedding. A common technique with high-dimensional inputs is to `embed' these into a lower-dimensional latent space. This latent space is then used to make actual decisions. This is effectively what many deep neural networks, for example to convert a $10^8$-dimension visual image into a 256-dimensional embedding. This can then be used with a simple one-layer neural network, or even just a linear function, to generate a $V$, $Q$ or $\pi$ function. \end{itemize} \vfill \subsection{Open AI Gym} \url{https://gym.openai.com/} This is a widely used framework within reinforcement learning and includes a wide variety of environments, such as the Atari Learning Environment (ALE) and MuJoCo tasks. However, there are significant limitations: support for planning algorithms is limited (e.g. the copy() method, essential to statistical forward planning algorithms) works on the ALE tasks, but not on others. The main limitation which renders it unsuitable for wargaming is the lack of support for multi-player games. \subsection{OpenSpiel} \url{https://github.com/deepmind/open_spiel} \begin{itemize} \item Core implementation language: C++, with wrappers for Python (and possibly other languages) \end{itemize} OpenSpiel is led by Marc Lanctot from DeepMind. The main focus of OpenSpiel is on classic board and card games, though it can potentially be used by any game that meets the standard interface and has an SFP-ready game state (a forward model that can be easily copied and run fast). The standard interface assumes that actions in a game can be enumerated. At each agent decision point, the set of available actions is passed to the agent and the agent then selects one of them. This is a standard interface that works well for classic games with small numbers (e.g. up to hundreds) of possible moves in each game state, but not for all games. For example, in Flashpoint Campaigns, move actions can contain up to three waypoints en route to the destination, each of which can be on any hex in the map. Hence, if the map has 100 hexes, then there would be $10^8$ possible movement paths for each unit, which would be infeasible to enumerate. OpenSpiel has an elegant way of representing chance events, which are a central feature of games such as Backgammon and Poker. Chance is represented as another player in the game, end each chance event is modelled as a move made by the chance player. Each state in the game has a one to one mapping from the state to the move history, which is made possible by the inclusion of the chance moves in the move history. One of the main attractions of OpenSpiel is the significant number of implementations of recent Game AI algorithms, such as Monte Carlo Tree Search and a range of DRL agents such as DQN and A3C. OpenSpiel also comes with a wide range of classic games, which are parameterised to enable different versions to be run. \subsection{Polygames} \url{https://github.com/facebookincubator/Polygames} \begin{itemize} \item Core implementation language: C++, with wrappers for Python (and possibly other languages) \end{itemize} Polygames is similar in scope to OpenSpiel, with the main focus on 2-player classic board games such as Go and Othello. Compared to OpenSpiel, it has fewer games and fewer AI agents. However, Polygames does provide a standard way to interface convolutional neural nets to board game environments. As with OpenSpiel, games in Polygames can be run with different parameters (such as board size). Although the challenge of learning from pixels (and more generally from visual input such as board-tiles) is less relevant to wargame AI, it may still be helpful to allow agents to learn from a spatial arrangement of map-tiles. \subsection{ELF: Extensive, Lightweight and Flexible platform for game research} \url{https://github.com/facebookresearch/ELF} \begin{itemize} \item Core implementation language: C++, with wrappers for Python (and possibly other languages) \end{itemize} ELF comes with three sample enviromments: an ALE wrapper, Go, and most relevant to wargames, a mini RTS. The mini-RTS game is similar in nature to microRTS. ELF offers a reasonably fast and well designed implementation in C++, but does not offer any particular advantages for wargames. \subsection{General Video Game AI (GVGAI)} \url{http://gvgai.net} GVGAI \cite{GVGAI-Multi} is a multi-faceted game AI framework that enables experimentation with many aspects of video games, each defined by its own competition track: \begin{itemize} \item The Single-player planning track. Agents use the forward model to play a wide range of games and puzzles. Leading agents include a range of tree search methods as well as rolling-horizon evolution. This track has had the most interest. \item Single-player learning track. This is most similar to the ALE framework, and agents are given a short learning period on some training levels before attempting to play unseen test levels. The short learning time and limited advance information made this (in retrospect) too challenging and led to a limited number of entries. Agents can learn from pixels or an object-based game state observation. \item Two-player planning track: agents have access to the forward model, but have to cope with an unknown agent on an unknown game. \item Level-generation track: the aim is to generate interesting (or at least playable) novel levels for unseen games: very challenging. \item Rule-generation track: generating new game rules for novel games; again very challenging. \end{itemize} \begin{itemize} \item Original implementation in Python (Schaul), more recent implementation in Java (much faster and more competition/evaluation tracks (2-player, learning track, level generation track). Java version also has wrappers for Open AI Gym \end{itemize} The learning track of GVGAI is similar in nature to ALE. ALE has the advantage of using commercial games (albeit from a bygone era) that are easy to relate to, though due to the finite set, limited number of levels for each game and deterministic nature has been susceptible to significant over-fitting \cite{OpenAIOverfitting}. Although less widely used than ALE, GVGAI does have some distinct advantages that are relevant to Wargame AI: \begin{itemize} \item An extensible set of games, game levels and game variations which are relatively easy to author in VGDL \item Support for 2-player games \item Stochastic games \end{itemize} A particular feature of the GVGAI framework is the \textit{Video Game Description Language} (VGDL). VGDL is a Domain Specific Language (DSL) designed to make it easy to express the rules of typical arcade-oriented 2D video games. Although VGDL was designed with this in mind, the overall approach of having a high-level DSL is very relevant for war game AI, and one of our recommendations is to consider developing a language to describe war game scenarios, including maps, assets, objectives and observers (where an observer specifies how and when to convert game states in observations that can be fed to the agents). \footnote{With languages such as Kotlin implementing DSLs is straightforward, and enables edit-time type-checking which greatly assists in the content authoring process: \url{https://kotlinlang.org/docs/reference/type-safe-builders.html }} \subsection{Codingame} \url{https://www.codingame.com/start} Codingame is a bit of an outlier here in this section as it does not meet the criterion of having a standard interface between the agents and the games. Instead, each game / challenge can adopt the interfaces that best suit it. Games for the platform can be coded in any programming language, and communication between the game engine and the agents is done by exchanging text messages via console IO. However, to make a game SFP-ready may mean porting the game to the language of choice and ensuring it has a suitable copy() method. Codingame is a very popular platform for software developers wishing to practice and achieve recognition for their coding skills while solving game AI challenges. Codingame also offers a platform for recruiters wishing to hire software developers. Game AI competitions run on the platform often have thousands of entrants. On discussion with one of the competition organisers, it is clear that many of the entries are typically just porting or applying standard algorithms, but the leading entries often show significant ingenuity and achieve high standards of game play. The platform is mentioned here as a possible forum to run wargame AI challenges, and likely generate more entries than for a typical academic competition. \subsection{Flexibility} For future research on wargame AI there is a strong need for flexibility. This includes the ability to change rules, edit scenarios, back-track to a point in a game to consider a new branch. There are also aspects needed to support war games that are not often needed for commercial games. These include the ability to: moderate manually, set doctrinal restrictions, analyse resulting data for narrative construction and identify and replay critical branch-points. \subsection{Summary of Platforms} Of the platforms mentioned above, the ones that are of particular interest for wargame AI are OpenSpiel and GVGAI. OpenSpiel is well designed and extensible and built for SFP algorithms. It comes with an extensive set of classic games and a range of recent good performing game AI agents. However, it does not support structured actions, since each action is coded as an integer from a (usually small) finite set. This might sound like a minor software engineering point, but is actually a manifestation of a deeper issue as it affects the operation of most of (perhaps all) the agents developed for a platform. For example, many algorithms work by sampling actions from a relatively small set of possible actions; if this set is effectively infinite they will fail unless adapted to cope with this. GVGAI is of interest due to its use of VGDL, showing a relevant practical example of how a DSL can enable relatively rapid authoring of new games. Like OpenSpiel though it codes actions as integers, so for this and other reasons does not support wargames. There is much to be gained by developing a new platform built from the ground up for wargames and wargame AI. This should offer support for scenario design and analysis, and to enable easy interaction with a range of AI agents. This will be discussed in more detail in section~\ref{sect:Recommendations}. \vfill \subsection{Recommendation 1: Develop a new Wargame AI Framework}\label{rec1} The review of existing platforms in section \ref{sect:Platforms} indicates that the existing game AI platforms do not provide adequate support for wargame AI for a number of reasons. This is not surprising, as none of them were designed with that purpose. However, the existing platforms do clearly show the potential for a well positioned system to supercharge research in a particular domain. A prime example of this is how the ALE framework (often used via OpenAI Gym) has captured the imagination of DeepRL researchers especially, leading to the publication of hundreds of papers. As a result the domain of Atari 2600 games is now well understood. \begin{figure}[h] \includegraphics[width=1.0\textwidth]{Interface.png} \caption{Generic proposed architecture with standard interface to cleanly separate AI Algorithm implementations from wargames. Wargames could be based on a new platform, or wrapped legacy/commercial environments. Each wargame would need to implement a minimum Core part of the interface, with support for Optional elements allowing use of increasing number of algorithms and analysis.} \label{fig:interface} \end{figure} Previous attempts have shown that using the latest AI techniques on existing wargame environments can be problematic due to their relatively slow execution time, lack of a clean interface for AI interaction, and lack of a forward model that can be copied or branched easily. The central recommendation of this report is that a framework is developed to support both the development of AI for wargames, and of wargames that are amenable to AI. Figure~\ref{fig:interface} shows this high-level architecture, consisting of three conceptual components: \begin{enumerate} \item \textbf{Interface}. This is the core component, and is primarily a design specification rather than software. Like the OpenAI Gym or OpenSpiel interfaces this defines the API methods that a wargame needs to support for AI to be used. This specification can have core methods that must be implemented, and others that are optional. We give some examples of this shortly. \item \textbf{Wargames}. Wargame implementations can be new ones, or potentially existing ones that are updated to support the standardised interface. \item \textbf{AI Algorithms}. AI development is cleanly separated from the underlying wargames, permitting algorithms to be ported across different environments and new techniques tried. This does not mean that AI development is agnostic to the target wargame, for as this report has catalogued, successful AI techniques are tailored and optimised to the structure of the domain, each of which will have distinctive patterns to its action and observation spaces. \end{enumerate} It is possible that existing wargames, either commercial or legacy in-house systems, can be updated to provide an API that supports this new interface, or a software wrapper developed that achieves the same end, although this may require prohibitive work to support all parts of the interface specification, in particular a forward model for SFP algorithms. One particular recommendation is to develop a software platform for new wargames. This platform can design in from the start key elements useful for the AI interface, such as a fast forward model and hierarchically decomposable observation and action spaces. A single platform is also more cost-effective than developing separate wargames in each domain, with some elements, such as units, command structures or enemy visibility common across all types of wargames. Using third-party suppliers to wrap/adapt an existing commercial game has some major advantages in terms of leveraging existing functionality and a pool of relevant software engineering expertise. The disadvantages are a potential loss of control over the process and content upgrades. The balance between these will obviously depend on the extent to which an existing wargame meets current requirements, and an assessment of the relative depth of skill-sets and experience. \begin{comment} \begin{table}[] \begin{tabular}[t]{|p{2cm}|p{3.2cm}|p{3.2cm}|p{3.2cm}|} \hline \textbf{Component} & \textbf{Dstl in-house} & \textbf{Third-party or Commercial Partner} & \textbf{Existing Legacy} \\ \hline Interface & Essential for Dstl to own the definition of this interface & N/A & N/A \\ \hline AI Algorithms & + Control & + Leverage expertise & N/A\\ & - Lack of Expertise & - Control & \\ \hline Individual & + Control & + Leverage expertise & + Re-use code\\ Wargames& - Lack of Expertise & - Control & - Cost, Constraints \\ \hline Wargame & + Control & + Leverage expertise & N/A\\ Platform & - Lack of Expertise & - Control & \\ \hline \end{tabular} \caption{Components of a future wargame framework from Figure~\ref{fig:interface}, with high-level pros and cons of development options. Yes/No indicates } \label{table:components} \end{table} \end{comment} Future defence wargaming environments should be developed to this platform/framework to enable AI techniques to be used uniformly across games. While the design framework and interface should be generic, it is advisable to start with an initial domain-specific implementation that meets a current requirement as a proof of concept. We consider this further in Recommendation 2. \subsubsection{Interface/Wargame sub-components} Figure~\ref{fig:interface} suggests that a suitable interface will have core and optional parts, with not all wargames needing to support all of the latter. The list below provides a first sketch of interface sub-components, and how these will benefit/impact supporting wargames. This is not an exhaustive list, and the work to detail the requirements beyond this high-level is beyond the scope of this report. \begin{itemize} \item \textbf{Core}. A clean design split between the core engine, graphical display, and AI. Support for either Deep RL and SFP algorithms requires many game executions, either from start-to-finish or for game-tree planning. Running in `headless' mode with no graphical display or expensive database access is essential to achieve the required speed of execution when there are no humans-in-the-loop. The OpenAI and OpenSpiel frameworks provide good model examples, and there is significant overlap but adjustments are needed for wargame-specific features such as multiple units. Some core concepts to consider are: \begin{itemize} \item \texttt{State.step()} to move the time forward one step. In a wargame environment a continuous time argument may make more sense. \item \texttt{State.apply(actions)} to specify actions to take. Unlike the OpenAI/OpenSpiel interfaces this should be extended to cover a list of actions for different units. \item \texttt{State.registerPolicy(unit, policy)} is an option to provide a policy to be used for one or more agents. An injected policy is then used when the model is rolled forward with \texttt{step()}. \item Each \texttt{State} should have, to use the OpenAI terms, an \texttt{action\_space} and \texttt{observation\_space} defined. The \texttt{observation\_space} should be a structured semantic representation and not pixel-based. For a wargame support for unit-specific spaces will be needed with a hierarchical structure. It is worth stressing that each wargame will otherwise have different domain-relevant conventions for these spaces, as do the OpenAI Gym environments, or OpenSpiel games. \end{itemize} \item \textbf{Copyable Forward Model}. A \texttt{State.copy()} method to copy the current state to implement a forward model. This is required for support of SFP and other planning algorithms, such as used in AlphaGo. This is put as `optional' here as pure-RL methods do not require it as long as the core game engine is fast (as outlined in Sections~\ref{sect:DeepRL} and~\ref{sect:OtherAlgos}). For existing systems in particular this can be a software engineering challenge to implement with a need for robust deep copies of the game state. \item \textbf{Observation Filters}. \texttt{State.observationFilter(unit)}-like methods that report only the state visible to a unit, or group of units. This can be enhanced to support different levels of filter to emulate different levels of imperfect information for unit decision-making. \item \textbf{Belief Injection}. \texttt{State.observe(unit, data)} or \texttt{State.assume(data)} methods to provide API access to the forward model to allow AI algorithms to use the model / engine to evaluate hypothetical plans incorporating estimates about what cannot be currently observed. \item \textbf{OpenSpiel support}. OpenSpiel provides a number of robust and state of the art Game AI algorithms. An additional interface sub-component could provide conversion support to the OpenSpiel interface to allow these to be used in unit-based wargames. \item \textbf{Visuals.} \texttt{State.render(unit)} to allow the current state to be visually displayed, perhaps from the perspective of a specific unit or element of the command structure. \end{itemize} If the route to a full wargame software platform is taken, then some key aspects this should include on top of the list above are: \begin{itemize} \item Easy generation of features. A feature is a game-specific piece of information likely to be helpful to a decision-making agent. Instead of (or as well as) making the full raw game state available agents, a mechanism to specify these easily for a particular wargame or scenario will speed development and learning. \item An easy way for users to author new scenarios. This, like the next two points, would be well supported by a Domain-Specific Language (DSL) tailored to wargame requirements. A model is VGDL used by GVGAI discussed in Section~\ref{sect:Platforms}. \item Extensible: easy to add new unit types \item Configurable objectives (including multi-objectives) \item Fully instrumented with configurable logging (this also applies to AI Algorithms so that the data behind each decision is recorded for later analysis and insight mining \item Record/Replay facility so that a previously played game can be watched later \item Offer planning at multiple levels of abstraction \end{itemize} \subsubsection{Next Steps} Specifically recommended next steps are: \begin{enumerate} \item Detailed work to define the interface component for wargame AI sketched above. This can, and probably should, be done in parallel with one or both of the following points in an iterative approach. \item Identify useful existing wargames that can be adapted without excessive development effort, either in-house or from third-parties. \item Scope possible work on building a more generic wargame platform. \end{enumerate} \subsection{Recommendation 2: Tractable Challenges}\label{sect:Challenges} This section reviews some of the challenges of incorporating the current state of the art AI techniques into wargames, using the framework typology of Section~\ref{sect:wargameTypes}. In all cases there is an assumption that the relevant sections of the wargame have been engineered in line with the recommendation in Section~\ref{rec1}. Underlying conclusions are that using AI to decide on communication with other agents or humans is at the very challenging end. A general rule in all cases is that the smaller the scenario, and less of a strategic master-plan is required, the more suitable AI will be. For example a sub-hunt scenario that involves 2-3 destroyers is tractable, as is a company-level scenario to secure and hold an objective. A scenario that models an amphibious assault on an extensive archipelago with sea and air support is less suitable. This is particularly true for an initial proof of concept. From the review below, some potential scenario-agnostic goals for a proof of concept are: \begin{enumerate} \item Unit `micro-control' as assistance for human players in a computer-moderated wargame. This avoids the need for strategic level decision-making, which is the responsibility of the human player. An analogy is the in-game AI in Flashpoint Campaigns that controls the detailed moves of the player's units. The complexity can be reduced if each unit is autonomous, making decisions based primarily on local information as in DecPOMDP models. \item AI full control of all units in a small wargame, with a single clearly defined objective. Either for use as an opponent for human players, or for analyst insight with scenario results with both sides under AI control. Adding realism to the AI through full imitation of human-like behaviours would add considerable complexity. More realistically different reward functions could be tailored to obtain behavioural variations. \item AI control of one or both sides in a Concept Development wargame. In this context the open-ended goal of seeking a diverse range of strategies can be supported by use of multi-objective approaches. The ability with AI to run hundreds or thousands of games with the same, or slightly different setup is useful for statistical analysis of the results, as well as permitting a full exploration of the strategy space. \item As the previous point, but in a Procurement setting. This also benefits from the ability to run many games to feed into statistical analysis, but the requirement to have control experiments with doctrinal realism of behaviour adds challenge if this cannot be easily codified. \end{enumerate} \subsubsection{Planned Force Testing} Significant incorporation of AI into large-scale Planned Force tests involving large numbers of communicating groups and sub-teams is not a realistic goal in the immediate future. This requires breakthroughs in areas of modelling restricted information flow and co-ordination between multiple agents not addressed seriously be recent research (see Sections~\ref{sect:InfoFlow} and~\ref{sect:AdvOpponent}). The scope of including diplomatic and/or external logistic aspects is also not well studied. However, there may be some opportunities to incorporate AI in aspects of the moderation of parts of a large-scale wargame, which are covered in the following sections. \subsubsection{Plan Variation Testing}\label{sect:PlanVarTest} Given a specific scenario to be repeated a number of times there are a few ways that AI techniques could be utilised, of varying challenge levels. Two aspects are specifically relevant here: the level of control the AI has, and the constraints under which it must operate. \begin{enumerate} \item{\textbf{AI control} \begin{itemize} \item Interactive control. The AI is expected to emulate the dynamic behaviour of a human player by responding to changing objectives and orders as the scenario unfolds. Two-way communication, responding to orders or providing an interpretative summary of the current situation is not feasible. One-way communication with precise changes to strategic targets is more feasible, as long as these can be encoded clearly in a utility or state evaluation function, but still very challenging. Any adaptive requirement here would be much easier to support with SFP or other planning methods, or else known changes would need to be included in pre-training for purer RL approaches. \item Full control. The AI has full control of one side in the game, but with a fixed objective at the start of the scenario that does not change (although clearly the AI must still respond to the actions of the opposing side). This is less challenging than interactive control, and is less restrictive about applied methods with pure RL now competitive. It is also most similar to the Dota2 and Starcraft II game set-ups, which set a rough upper bound on the challenge and cost level. \item Unit micro-management. A human player is responsible for strategic decisions, while the AI is responsible for moving units on a hex-by-hex basis to implement these. This would be most similar, for example, to the role of the AI in Flashpoint Campaigns, which decides for each unit exactly where to move, and when to attack visible enemies. The benefit sought here is to make best use of the human player's time, and avoid it being spent on low-value activities. The challenge in this case is reduced significantly by the lack of need to consider strategic moves. \end{itemize} } \item{\textbf{AI constraint} \begin{itemize} \item Unit independence. Each unit (or group of units) is controlled independently, so only acts based on its local knowledge along with some initially specified goal. This contrasts with a default approach in which a single AI controls all units, taking into account what each of them can see. The local, independent approach is less computationally challenging, as it avoids some of the problems of large action and state spaces. It would require some additional features in the API discussed in Section~\ref{rec1} to support it. The default approach of all units being controlled by one AI is simpler architecturally, and theoretically more optimal, but is not computationally tractable for large numbers of units. \item Fog of War. Fully intelligent understanding of imperfect information is challenging, although the support of it is not, provided this is factored up-front into the API design. By `intelligent' we mean taking into account the value of information-gathering moves, and bluffing/second-guessing the opponent (Section~\ref{sect:Observability}). However, a good simulation of an intelligent understanding can be obtained by crafting the reward function to include a bonus for visible terrain, and scouting activities. \item Military doctrine. Where an AI needs to act in line with specific tactical doctrine to provide useful results, the challenge is clearly defining what the military doctrine is. If this can be defined in game mechanic terms, then this can be implemented by filtering non-compliant actions from the action space. More strategic elements can be factored in by engineering the reward function or victory points awarded. Learning a doctrine implicitly from observations of human actions is much more difficult. \item Specific Plan. More challenging is where the AI needs to broadly follow a plan generated as an outcome from a previous physical wargame, minimising variations from this. This can potentially be supported by incorporating the target plan into the reward function, although with less weight than the actual victory conditions. This will incentivise the AI to keep as closely as possible to the plan, but not at the expense of winning. Deviations from the target plan can then be analysed for common breakpoints. \end{itemize} } \end{enumerate} \subsubsection{Concept/Force Development}\label{sect:ConceptDev} These wargames are particularly suitable for using AI due to their explicitly exploratory goals. These means less work is required to impose constraints based on tactical doctrine or \textit{a priori} assumptions on the best/correct way to act in a situation, and algorithms such as MAP-Elites and multi-objective training are especially useful here to encourage a diverse array of solutions (see Section~\ref{sect:Exploration}). The issues instead revolve around interpretability of the results and insight extraction. \begin{itemize} \item \textbf{Human Observation}. Analyst observation of games using the final learned policies can be a prime source of insight. \item \textbf{Statistical Analysis}. This requires flexible and in-depth instrumentation as discussed in Section~\ref{rec1}. This focuses on patterns in the course of game, and does not provide direct information on why those patterns occur. This would still require analyst insight. \item \textbf{Plan interrogation}. Instrumentation can include all the actions an agent considers at each step, and the relative weights applied to each; for example the visit counts in MCTS or the Q-value of the action in Reinforcement Learning. In the case of SFP methods this query can be extended deeper into future simulated at that decision point to understand what the agent believed would happen to some time horizon. This can highlight critical decision points where different actions had very similar values, but led to very different future results. \item \textbf{Feature Perturbation}. Plan interrogation does not provide direct evidence as to why an agent took a particular decision. Feature Perturbation is especially helpful in Deep RL methods in which the neural network that makes a decision is very difficult to interpret directly. This modifies different inputs to the decision and highlights those that were instrumental in making the decision~\cite{Gupta_Puri_Verma_Kayastha_Deshmukh_Krishnamurthy_Singh_2020}. See Section~\ref{sect:ExplainableAI} for further methods. \end{itemize} \subsubsection{Procurement Testing} The smaller scale of these wargames makes these amenable to AI techniques, and many of the points made in Sections~\ref{sect:ConceptDev} and~\ref{sect:PlanVarTest} apply here. Statistical analysis from multiple iterations (assuming AI versus AI games) comparing the outcomes when equipment/doctrine is varied between a small number of specific options would provide further benefits beyond what is currently achievable due to resource constraints with human-in-the-loop games that limit the number of iterations. The main challenge in this domain is applying doctrinal and other constraints to AI behaviour. \subsection{Recommendation 3a: A Scalable Deep Learning Approach for Wargaming through Learned Unit Embeddings} This section presents one particular deep learning approach that we believe is promising for wargaming. Wargames come with their own particular requirements and challenges compared to other games that deep learning approaches have been applied to so far. Here we propose one particular deep learning approach that combines the most relevant aspects of the AlphaStar and OpenFive architecture, while paying particular attention to the computational and scaling demands of the approach. An overview of the proposed approach is shown in Figure~\ref{fig:approach1}. Similarly to AlphaStar or AlphaGo, we first train a value and policy network based on existing human playtraces in a supervised way. First training on existing playtraces, instead of starting from a \emph{tabula rasa}, will significantly decrease the computational costs needed for learning a high-performing policy. In the second step, and given that a fast forward model of the game is available, the policy can be further improved through an expert iteration algorithm (see Figure~\ref{fig:ExpertIteration}). \begin{figure}[h] \includegraphics[width=1.0\textwidth]{approach_idea1.pdf} \caption{Training (A). A policy network that predicts a distribution of valid moves and a value network that predicts the expected game outcome are first trained based on human examples. Policies are further fine-tuned through expert iteration. The policy network (B) is a feudal network in which a manager controls lower level units. The manager and unit network takes as input processed unit information such as distances, enemy types, etc. instead of working from raw pixels. (C) In order to support new unit types without having to retrain the whole system, unit types embeddings are based on unit abilities. This way the feudal network should be able to generalise to new units, based on similar units it already learned to control. } \label{fig:approach1} \end{figure} In terms of employed policy network, we believe the most scalable version with the least computational demands would be a Feudal network \cite{ahilan2019feudal} approach (Figure~\ref{fig:approach1}b). Similarly to a system such as AlphaGo, one manager network controls each of the different units. One main disadvantage of the AlphaStar system for wargaming is that it would require retrained from scratch every time a new unit or weapon type is introduced. Therefore we propose a new Feudal policy manager approach that does not directly work with specific unit types, but with \emph{unit embeddings} instead. Embeddings are most often used in a subfield of the deep learning dealing with natural language processing \cite{levy2014dependency}. The idea is that words that have a similar meaning should be represented by a learned representation of vectors that are similar to each other. We imagine a similar embedding can be learned for different unit and weapon types. This way, the Feudal policy network would not have to be retrained once a new unit is introduced and the network should be able to interpolate its policy to a new unit, whose embedding should be close to already existing unit types. Other approaches such as (1) automatically learning a forward model for faster planning in latent space (Section~\ref{sec:learning_fm}), or (2) adding functionality for continual learning (Section~\ref{sec:continual_learning}) could be added to this system in the future. To train such as system, we believe the Fiber framework (Section~\ref{sec:deep_rl_frameworks}) introduced by Uber could be a good fit and would require minimal engineering efforts. Given a fast enough simulator and the fact that we should be able to kickstart training with human replays, we speculate that even a modest setup of $\sim$100 CPUs and $\sim$5 GPUs might allow the system to be trained in around 12 hours. \subsection{Recommendation 3b: Graph Neural Networks for Unit Information Integration}\label{sect:GNN} In addition to using mostly off-the-shelf components as in described in the previous section, a less explored but potentially very relevant approach for wargaming are graph neural networks. Graph neural networks (GNN) are becoming more and more popular in deep learning \cite{zhou2018graph}, and have shown promising results in domains such as physics system, learning molecular fingerprints, modelling disease, or predicting protein interactions. The basic idea behind graph neural network (Figure~\ref{fig:gnn}), is to model the dependencies of graphs via learned message passing between the nodes of the graph. For example, a Sudoko puzzle can be modelled as a graph \cite{palm2018recurrent}, in which each of the 81 cells in the 9$\times$9 Sudoko grid is a node in the graph. The same neural network is used for all nodes in the graph to learn to integrate information from incoming nodes and to iteratively come up with the Sudoko solution. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{graph_neural_network.png} \caption{Example of a Graph Neural Network modelling a social network \cite{zhou2018graph}. A similar structure could model the chain of command and communication in wargames.} \label{fig:gnn} \end{figure} In the case of wargaming, nodes in the GNN could represent units, while the connections between them reflect communication channels. A GNN could be trained to integrate information in a decentralised way and learn by itself to resolve communication issues and misalignment (e.g.\ seeing the same unit twice, noisy communication channels) into a coherent whole. Additionally, a particularly relevant and recently proposed GNN architecture is called recurrent independent mechanism (RIM) \cite{goyal2019recurrent}. In this system, units only sporadically communicate and keep a level of autonomy. These RIMs might be particularly promising to model situations in which a lower level wargaming unit lost contact to a higher level orders. The unit would have to learn to work both when higher levels orders are available, but also compensate and follow their own autonomy when they are not. \subsection{Recommendation 3c: High Performance Statistical Forward Planning Agents} \label{HighPerfSFP} As an alternative/parallel approach to the Deep RL-focus of the previous two recommendations, an SFP approach could productively be built on recent results in RTS and multi-unit game environments. This approach would leverage domain knowledge in the form of low-level action scripts to provide Action Abstraction. Domain knowledge can also be incorporated in a state evaluation function used to determine the value of an action choice after rolling out the forward model. Specific variants here are: \begin{enumerate} \item A Combinatorial Multi-Armed Bandit approach, such as NaiveMCTS~\cite{Ontanon_2017} or direct MCTS~\cite{Churchill_Buro_2015}. The expert-scripts provide the set of actions for each unit. This is suitable for a relatively small number of units. \item A two-stage approach that uses a neural network trained by RL to make the initial decision for each unit, followed by low-level modification of this plan using MCTS or CMAB as in~\cite{Barriga_Stanescu_Buro_2017} to take account of unit (and enemy) interactions. This makes more effective use of the computational budget to scale up to larger scenarios. \item Online Evolutionary Planning (OEP/RHEA) as an evolutionary option for multiple units~\cite{Justesen_Mahlmann_Risi_Togelius_2018}. \item Stratified Strategy Selection~\cite{Lelis_2017}. All units are partitioned into a set of types, for example based on position, unit type, damage and so on. Each type is then given a single consistent order (i.e. script), and the algorithm searches in the space of type partitions and script combinations. The scales well to large numbers of units. \end{enumerate} In all cases the Action Abstraction scripts and/or the state evaluation functions can be learned through either Evolutionary methods (see~\cite{Marino_Moraes_Toledo_Lelis_2019, Neufeld_Mostaghim_Perez-Liebana_2019}), or Expert Iteration based on RL from expert games as described in Section~\ref{sect:OtherAlgos}. \subsection{Recommendation 4: Open areas of research} As this report has shown, much of the intensive research effort over the past few years into Deep RL and Game AI has generated techniques that are selectively very relevant to wargames. Below we summarise a number of areas relevant to wargames that have not benefited from this surge of recent work, and which are relatively under-developed. \begin{itemize} \item Restricted Information Flow between agents, and between low-level units and high-level commanders. \item Diplomacy and Negotiation in games with more than two players. \item Exploring Graph Neural Networks for modelling unit information integration \item Combining deep RL with learned unit embeddings as a scalable approach for wargaming AI \item Integration of human-factor research on realistic behavioural patterns of military commanders into AI constraints \end{itemize} \vfill \section{Conclusions} Great strides have been made in Game AI over the last 5 years in particular, though the headline achievements using DeepRL methods have often been achieved at the cost of great effort, expertise and expense. Wargames are in many cases not fundamentally harder than playing StarCraft to a high standard, but they are different to commercial games and come in a wide variety. In most cases it will not be possible to put vast amounts of effort into developing strong AI for any particular wargame, but there remain many interesting and open questions regarding the level of competence that could be achieved using existing recent methods, and the amount of investment needed to achieve satisfactory performance. We make a number of recommendations that offer viable ways forward and we firmly believe that these should be explored in detail and taken forward as appropriate. There has never been a better time to invest in this area, and the potential benefits are significant. They include better staff training, better decision making, and an improved understanding of the nuances of problem domains that comes as an inevitable and desirable spinoff from building better models and gaming with them. \vfill \subsection{Action Space}\label{sect:ActionSpace} The Action Space of a game is the set of actions available to a player when they make a move. In the case of Go this is a discrete set of 361 board locations (on a 19 by 19 board), and in Atari games this is the set of possible joystick positions, plus the pressing of the button (a maximum of 18 for all combinations, but most game use far fewer). These number represent an upper bound as not all of these actions will be valid in any given situation, for example in Go some of the board positions will already be occupied and hence unavailable. A key distinction is whether the action space of a game is \textbf{discrete}, as in the Go and Atari examples, or \textbf{continuous}. In MuJoCo for example an `action' is the setting of angles and torques for all limb rotations and movements, and each angle can be any value between 0 and 360 degrees. In this the number of dimensions that need to be specified is important. In games such as Starcraft II or CMANO, any specific unit can be ordered to move to a map position, which is a continuous two or three dimensional vector; although other actions, such as the target of an attack, are discrete. Any continuous action space can be turned into a discrete one by selecting specific points as chooseable (`discretisation'). This is part of the design of MicroRTS with the game working on a fixed grid, hence discretizing a continuous 2-dimensional space into fixed squares; Flashpoint, like other wargames, does the same with hexes. Table~\ref{table:ActionSpace} summarises the features of the different environments. Starcraft II and MicroRTS are similar in style, with multiple units being controlled simultaneously and hence a full action space that is combinatorially very large. Chess, Go, Atari and GVGAI are a different type of environment with a smaller set of actions available at any one time. A player in Dota 2 is halfway between these, and controls a single unit which can take one action at a time (but up to 80,000 actions may be possible). The Starcraft II action space can be considered in two ways: \begin{enumerate} \item {Clicks on screen. This is the approach used by DeepMind with Deep Learning, and the gives the rough $10^8$ set of actions each turn, as these are defined by the human point-and-click mouse interface~\cite{vinyals2017starcraft}.} \item{Unit orders. This uses an API, which provides a list of available units and the orders that can be given to each.} \end{enumerate} The second of these is most appropriate for wargames, for which there is no requirement to additionally learn the vagaries of a human interface. Classic AI approaches, including MinMax and Monte Carlo Tree Search as well as Q-Learning based approaches used in Go and Atari require a discretised action space. Policy Gradient RL techniques have been developed to operate with a continuous action space (or policy)~\cite{policyGradient}. Another approach is to discretise the space, and this is also used to reduce the sizes of discrete spaces to a smaller number. This `Action Abstraction' reduces a large number of possible actions to a small set tractable for forward planning or other techniques~\cite{Churchill_Buro_2013, Moraes_Marino_Lelis_Nascimento_2018}. For example in some MicroRTS and Starcraft II work, a set of scripts can be used to define a particular tactic (`worker rush', `build economy', 'defend against incoming attack'), and the AI focuses on learning which tactic to apply in a given situation without needing to learn the detailed instructions that make it up~\cite{Churchill_Buro_2013, Neufeld_Mostaghim_Perez-Liebana_2019}. Sub-goal MCTS does something similar with pre-specified sub-goals that are used to automatically prune the action space~\cite{Gabor_Peter_Phan_Meyer_Linnhoff-Popien_2019}. This is a key mechanism to introduce domain knowledge in wargames. It can leverage expert knowledge embedded in the scripts that define useful action sequences (such as `take cover', `seek high ground', `patrol with active sonar'), without being fully constrained as the AI can learn which script to use in which situation, which may not always accord with expert intuition. The net result is to significantly speed up the learning or planning process (by orders of magnitude) at a cost in loss of flexibility. Extensions of this idea relevant to wargames are to simultaneously learn the parameters of scripts (for example, an aggression parameter that specifies the odds required to attack); to evolve a sub-set of scripts to use from a larger population~\cite{Marino_Moraes_Toledo_Lelis_2019}; or to use the results of scripted recommendations for more detailed low-level planning~\cite{Barriga_Stanescu_Buro_2017}. This last work generates actions for units based on scripts, and then devotes some of the computational budget to refining proposed moves for units that are close to enemy units, for which a small modifications of a high-level default move may have an especially large impact. (There is overlap here with the unit-based techniques discussed in Section~\ref{sect:unitTechniques}.) \begin{table}[] \begin{tabular}[t]{|l|l|c|c|c|} \hline \textbf{Game} & \textbf{Discrete/Cont.} & \textbf{Order Mode} & \textbf{Max Action Space} & \textbf{Decisions} \\ \hline \textbf{CMANO} & Continuous & $10^{0\mhyphen 3}$ units & $10^{10+}$ & $10^5$ \\ \textbf{Flashpoint} & Discrete & $10^{1\mhyphen 2}$ units & $10^{10+}$ &$10^0$ \\ \textbf{Chess/Go} & Discrete & 1 move & $10^2$ to $10^3$ &$10^0$ to $10^1$ \\ \textbf{Atari/GVGAI} & Discrete & 1 move & $10^1$ & $10^2$ to $10^4$ \\ \textbf{Starcraft II} & Continuous & $10^{0\mhyphen 3}$ units & $10^8$ or $10^{10+}$ & $10^{5+}$ \\ \textbf{Dota2} & Discrete & 1 move & $10^5$ & $10^{5+}$ \\ \textbf{MicroRTS} & Discrete & $10^{1\mhyphen 2}$ units & $10^6$ to $10^8$ & $10^2$ to $10^3$ \\ \textbf{MuJoCo} & Continuous & 3-17 dimensions & - & $10^{3+}$ \\ \hline \end{tabular} \caption{Action Space Categorisation. `Order Mode' can be 1 move per turn, orders per unit or a single multi-dimensional vector per time-step. `Decisions' is an approximation of the number of decisions a player makes during one game.} \label{table:ActionSpace} \end{table} \subsection{Branching Factor}\label{sect:Branching} The Branching Factor of a game is the number of new positions that can be reached after each move/action. In general the higher this is, the more challenging the game is to any AI technique. This is closely related to the Action Space. In a deterministic game, each distinct action will lead to a different game position and hence the branching factor is equal to the average action space size. In a stochastic game then the branching factor can be much higher, for example in a wargame a decision to attack a unit can lead to many different states depending on the random damage dealt to both sides, and the results of any morale checks. The impact of branching factor is hence covered in Sections~\ref{sect:ActionSpace} and ~\ref{sect:Stochasticity} on Action Space and Stochasticity respectively. \subsection{Number of Decisions}\label{sect:NumberDecisions} This refers to the average number of decisions or actions made by a player during the game. Games with more decisions are potentially more complex, but this is also dependent on the size of the action space. For this reason the number of decisions a player makes is included alongside Action Space in the third line of Table~\ref{table:ActionSpace}, as these two can roughly be multiplied together as a rough gauge of complexity. The length of a game can be characterised by either the number of decisions made by each player or the number of game simulation `ticks'. Classic games such as chess have one `game tick' per decision. Realtime wargames may play out for tens of thousands of game simulation ticks, but on most of those the players may be taking no actions (even if they could) due to limits on human perception, thinking and reaction times. In Starcraft, the AI agent may interact via a constrained interface in order to reduce the click rate and level the playing field when playing against human players. The very different numbers of decisions available for CMANO ($10^5$) and Flashpoint ($10^0$ to $10^1$) in Table~\ref{table:ActionSpace} draw attention to two quite different ways of looking at wargames. The figure for CMANO is estimated from a maximum of one action per second over a 2-3 hour realtime game; which is of the same order of magnitude as in Starcraft and Dota 2. In Flashpoint Campaigns the player has a `command cycle' that only allows them to enter orders (for all units) at a few specific points. Once orders have been given, 15-30 minutes of simulated time then unfold during which the player can only watch events. This difference is between a low-level versus high-level control perspective, which can apply to \emph{either} an AI or human player. Flashpoint seeks to model the constraints around human decision making in the field, in line with much of the purpose of wargaming outlined in Section~\ref{sect:wargameTypes}. The second by second view is more in line with low-level control of units to fulfil these goals, and in Flashpoint these are in effect executed by the in-game AI that makes decisions for each unit about moving, attacking and retreating based on the high-level goals provided by the player. This perspective is relevant for AI that supports a strategic human player by micromanaging units for them in pursuit of a specified high-level goal. Neither perspective is similar to the strict turn based approach of classic games, or the Atari/GVGAI environment with a very constrained set of actions at each decision point. This distinction between low-level (or `tactical') and high-level (or `strategic') decisions is more important than the raw numerical differences in Table~\ref{table:ActionSpace}. It is addressed by a number of techniques covered in more detail elsewhere in this report, specifically: \begin{itemize} \item Hierarchical methods in Sections~\ref{sect:unitTechniques} and~\ref{sect:HRL}; \item Action Abstraction (for example each high-level strategy being a script that specifies the low-level tactics to follow) in Section~\ref{sect:ActionSpace}. \end{itemize} \subsection{State Space}\label{sect:StateSpace} \begin{table}[] \begin{tabular}[t]{|l|l|l|l|l|l|l|} \hline \textbf{CMANO} & \textbf{Flashpoint} & \textbf{Chess/Go} & \textbf{Atari/} & \textbf{Starcraft II} & \textbf{MicroRTS} & \textbf{MuJoCo}\\ & & & \textbf{GVGAI} & \textbf{(+ Dota2)} & & \\ \hline LC & LC & $10^{47, 170}$ & $10^{6000}$ / LC & $10^{1685}$ / LC & LC & LC \\ Unit & Unit & Global & Global & Unit & Unit & Global\\ \hline \end{tabular} \caption{State Space categorization. `LC' indicates a game is `locally continuous'. The state-space for Atari is based on the possible values for all pixels over four frames after downsampling~\cite{atari}. State-space estimates for other games from~\cite{Ontanon_2017}. The second line indicates if state is purely global, or if it can largely be factored to individual units.} \label{table:StateSpace} \end{table} We can categorise the State Space of a game in terms of the number of different states it can be in. These are calculable in cases like Chess or Go ($10^{47}$ and $10^{170}$ respectively). In games with continuous state spaces, these are technically infinite. This categorisation is especially relevant to search-based techniques, as used classically for Chess. In Chess or Go, each board position is unique (ignoring symmetries), and it can make a huge difference to the outcome of a game if a pawn is one square to the left, or if a Go stone is moved by one space. A difference of one square for a pawn can for example can open up an attack on a player's Queen or King. This is much less true in Starcraft II, many Atari games, and RTS games in general. These games are more `locally continuous', in the sense that small changes in unit position, health or strength usually lead to similarly small changes in the outcome. We should also distinguish between the state space and the observation space (section~\ref{sect:ObservationSpace}). The observation space is the lens through which the agent views the underlying state. The difference between state and observation of state is emphasized for partially observable games, where the agent is forced to make assumptions about the unobservable parts of the state. However, it may also be that the observation is an expanded version of the underlying state. For example the full observation space for Atari 2600 games is $10^{70,000}$ based on the number of pixels, the possible colours of each pixel. This is reduced (downsampled) to $10^{6000}$ for processing by the deep network in the original (and later) DeepMind work~\cite{atari}. This downsampling by thousands of orders of magnitude `loses' all but an infinitesimal fraction of the original information without noticeably reducing performance, and is a clear indication that the game is locally continuous in this sense. In this regard they are wargame-like, and classic state-space complexity is less relevant. However, the Atari 2600 console only has 128k bytes of RAM (1024 bits) so the underlying state space is limited by this, and hence much smaller than even the compressed observation space described above (though some cartridges came with up to 4k of extra RAM). The main point is that after graphical rendering the observation space can be much larger than the underlying state space. Local continuity still allows for discontinuities; for example an infantry company may move only a few metres, but if this is from inside a dense wood onto an open plain in sight range of the enemy then it will have a major, discontinuous impact on the game. The key point is that the formal state space size is not a good measure of game complexity. It is better to think about this as a low-dimensional, non-linear manifold within the high-dimensional pixel (or other) space. This lower-dimensional manifold represents the true complexity of the state space, but is not directly observable. It is this low-dimensional manifold that machine learning techniques seek to identify, building a model that understands the boundary between wood and plain is the important implicit variable. Deep RL does this using multiple convolutional neuron layers, random forests by constructing multiple decision trees and so on. Hence in Table~\ref{table:StateSpace}, we categorize games by this idea of `local continuity'. In addition to a distinction between locally-continuous and discrete games, some games can be largely factored into the state of individual units. In these cases, we can consider the state space to be composed of a number of distinct components: \begin{enumerate} \item {The state of each unit; position, damage, equipment etc.} \item {The interactions between units; their relative positions are likely to be relevant in a wargame.} \item {Purely global state; developed technologies in Starcraft II, or the number of available air-strikes in Flashpoint.} \end{enumerate} Wargames are unit-based and locally continuous, and most similar to the RTS-style games in Table~\ref{table:StateSpace}. The number of units that a player controls is an important aspect of the complexity of RTS games and wargames. A large number of units are in play limits the ability of a player to track them all, and to properly consider the best actions that each should take in relation to what the others are doing. In wargames such as CMANO, a player can even write Lua scripts to control how a set of units behave. As the number of units increase, so the need for some type of structured system of control becomes apparent, such as standard military hierarchies. Various approaches have been used in the academic literature looking at unit-oriented state spaces, and these are surveyed in detail in Section~\ref{sect:algoSummary} given how important this aspect is to wargames. \subsection{Observability}\label{sect:Observability} \begin{table}[] \begin{tabular}[t]{|l|l|l|l|l|l|l|l|} \hline \textbf{CMANO} & \textbf{Flashpoint} & \textbf{Chess} & \textbf{Atari/} & \textbf{Starcraft II} & \textbf{Dota2} & \textbf{$\mu$RTS} & \textbf{MuJoCo}\\ & & \textbf{/Go} & \textbf{GVGAI} & & & & \\ \hline Imperfect & Imperfect & Perfect & Perfect & Imperfect & Imperfect & Perfect & Perfect \\ Fog of War & Fog of War & & & Fog of War& Fog of War & & \\ Unit & Unit & & & Camera/Unit & Unit & & \\ \hline \end{tabular} \caption{Observability categorization. The first line shows if a game has Perfect or Imperfect information, the second line the type of Imperfect information, and the third line how Observability is restricted.} \label{table:Observability} \end{table} The Observability of game defines what elements of the full game state are visible. At one extreme, a game with Perfect Information has the whole state space visible to all players. A game with Imperfect Information has some parts of this hidden, for example in most card games a player can see their own hand, but not that of the other players. In a wargame the most common form of Imperfect Information is `Fog of War' (FoW), in which a player can only see their own units and those of the enemy within line of sight and range. Other forms of imperfect information are possible, for example a player may not have full knowledge of the capabilities of enemy units at the start of a scenario, even when the units are visible. For the games under consideration the primary aspect of Observability that is relevant is FoW, as summarised in Table~\ref{table:Observability}. In this regard they split straightforwardly into Perfect Information games, and Imperfect Information ones with Fog of War. Hidden information through FoW fundamentally changes some of the challenges faced compared to perfect information games such as Go. We can now only observe part of the full State Space, and formally therefore have to track all possible states that the unobservable parts of the State Space \emph{could} be in. This expands the complexity of the problem, and the most theoretically rigorous analysis of this expansion (in Partially Observable Markov Decision Processes, or POMDPs) is only tractable in small, toy scenarios~\cite{Gmytrasiewicz_Doshi_2005, Ross_Pineau_Chaib-draa_Kreitmann_2011}. More realistic algorithms that work in large-scale POMDPs usually sample from some estimate of the unknown State Space and are reviewed in more detail in Section~\ref{sect:POMDP}. \subsection{Observation Space}\label{sect:ObservationSpace} In a Perfect Information game the Observation Space is by definition the same as the State Space, as this is fully observable. In an Imperfect Information game the Observation Space is a strict subset of the State Space. For example, where we have Fog of War we can only see some hexes and the full state of our own units. This should not be interpreted to mean that a smaller Observation Space makes a game easier, and the smaller the Observation Space compared to the State Space, the harder the game in general. Refusing to look at a Chess board when playing would simplify the Observation Space to a single state, and be unlikely to improve one's play. The essential categorization of games is covered in Table~\ref{table:Observability}. The third line in this table emphasizes that the mode of Observation can vary: \begin{itemize} \item {Unit-based visibility. This is most standard, with a player able to see anything that any of their units can see.} \item {Camera-based visibility. In Starcraft II this is an additional constraint important in a real-time game. A player must physically navigate the camera view to the area they wish to look at, and then they still only see what is visible to their units.} \end{itemize} The relevance of the additional camera-based limitation largely depends on the pace of the game. It is akin to a wargame that models the reality of a commander's restricted attention bandwidth when rapid decisions are needed. In a more relaxed turn-based game, or where the passing of time is slow, then it is not relevant. In wargames the camera-based limitation is not relevant as this approach to modelling attention bandwidth is primarily an artifact of the commercial RTS game genre. In DOTA 2 each player controls a single unit (hero), and can sees the world from this unit's perspective. However the player also has access to a mini-map that shows the world with all units visible to any other player on the same team. This subtlety does not affect the data in Table~\ref{table:Observability}. \subsection{Information flow}\label{sect:InfoFlow} A feature of wargames that is missing from all of the example games here, including Flashpoint and CMANO, is the role of a restricted information flow. In the games of Table~\ref{SummaryTable}, information is presented to the player by visibility of units on a map. In the case of FoW the player (commander) can see anything that their units can see. In physical wargames, as in real combat situations, this is frequently not the case. Instead the commander is reliant on reports back from units on the ground, which have a restricted informational bandwidth in what they can transmit. A unit that comes under unexpected enemy fire would report this as a priority with perhaps an estimate of the opposing force composition, and not the complete specification of all visible units. This feature is important in physically-moderated wargames, but is not currently common in computer-moderated ones. Computer-moderated games are required to incorporate restrictions in Information Flow from commander to units, modelling command and control constraints. Information Flow restrictions from units back to commander is anticipated to be a requirement for future wargames. \subsection{Stochasticity}\label{sect:Stochasticity} \begin{table}[] \begin{tabular}[t]{|l|l|l|l|l|l|l|} \hline \textbf{CMANO} & \textbf{Flashpoint} & \textbf{Chess/Go} & \textbf{Atari/} & \textbf{Starcraft II} & \textbf{MicroRTS} & \textbf{MuJoCo}\\ & & & \textbf{GVGAI*} & \textbf{+ Dota2} & & \\ \hline Stochastic & Stochastic & Determin. & Determin. & Stochastic & Determin. & Stochastic \\ \hline \end{tabular} \caption{Stochasticity categorization. Environments are either Stochastic (have random event outcomes), or Deterministic. GVGAI has a mixture of deterministic games and stochastic games.} \label{table:Stochasticity} \end{table} This refers to whether game is deterministic or has random (stochastic) elements. In a deterministic game the same action in a given state always leads to the same next state. In a stochastic game this will lead to a distribution of possible next states. This is closely linked to Branching Factor (Section ~\ref{sect:Branching}), which dramatically increases for stochastic games due to the increase in possible outcomes from a single action, and is a key reason that the minimax search techniques that achieved world championship level play in Chess are less suitable for wargames. These can be converted to an `Expectiminimax' algorithm, but at the cost of more computation due to the branching factor, and a reduced ability to prune the search tree~\cite{russell2016artificial}. A more common approach is to use Monte Carlo techniques to randomise the outcomes in `rollout' simulations used in both Monte Carlo Tree Search and in the generation of data for Deep RL techniques. Deterministic single player games are susceptible to over-fitting: agents may learn a successful sequence of actions, rather than learning how to play the game in a general way. An example of this is learning the precise route for a Pac-Man level given deterministic search patterns by the ghosts; this does not help the agent in the next level. Environments such as Atari/GVGAI\footnote{The deterministic single-player subset of GVGAI games} and MuJoCo are susceptible to this kind of over-fitting in RL techniques, though that has been mitigated by adding randomness in the interface between the game engine and the agent~\cite{Haarnoja_Zhou_Abbeel_Levine_2018, Fujimoto_vanHoof_Meger_2018}. Classic forms of stochasticity in wargames are the uncertainty of combat outcome, or spotting probability of enemy units, minefields etc, which in both physical and computerised versions are decided by dice-rolling~\cite{peterson2012playing}. This stochasticity introduces the possibility of low-probability but high-impact events in any single run of a game. For example, spotting a well-camouflaged tank column at distance may enable them to be neutralised at low cost, giving a very different outcome in, say, 5\% of games. This is a problem for physical wargames, or ones with humans-in-the-loop, as this constrains the number of games that can be run to (usually) low single-figures. For this reason identification of these events is key to determine whether to branch the game (see Section~\ref{sect:wargameTypes}) so that it is representative of the median expected outcome. This is less of an issue in fully computerised wargames with an AI on both sides, as if thousands of games are run, then these low-probability events are representatively sampled and averaged out. For wargames, there are other sources of uncertainty. Since they are inherently multiplayer, the actions of the opponent (whether human or AI) are normally unpredictable, and partial observability also has similar effects. This uncertainty of opponent action (especially with an adversarial opponent) is covered in Section ~\ref{sect:Opponent}, and is not formally `random', but simply not known. If the policy of the opponent were known perfectly, then this might still be random if playing a mixed strategy deliberately, for example in Rock-Paper-Scissors in which a known opponent might play each option with equal random probability. In practise many game engines may model an AI opponent using an element of randomness, representing the real-world unknown actions they would take. The explicit use of randomness in simulations can provide an efficient way to model a number of types of uncertainty. For the benchmark game environments, MicroRTS uses deterministic combat, with each unit doing a fixed amount of damage, while CMANO, Flashpoint, DOTA2 and Starcraft II have random damage. CMANO and Flashpoint additionally have random chances for spotting enemy units, affecting the Observation Space. An interesting way to model stochastic games is taken in the OpenSpiel framework (see Section~\ref{sect:Platforms}). For most OpenSpiel games any randomness is modelled as the actions of a special random player. The actions of the random player are recorded, just as they are for any other player. From the root state of a game, the sequence of actions taken then uniquely defines the resulting game state. \subsection{Win Conditions}\label{sect:WinConditions} \begin{table}[] \begin{tabular}[t]{|l|l|l|l|l|l|l|} \hline \textbf{CMANO} & \textbf{Flashpoint} & \textbf{Chess/Go} & \textbf{Atari/} & \textbf{Starcraft II} & \textbf{MicroRTS} & \textbf{MuJoCo}\\ & & & \textbf{GVGAI} & \textbf{+ DOTA2} & & \\ \hline VP Scale & VP Scale & Win-Lose & VP Scale & Win-Lose & Win-Lose & VP Scale \\ \hline \end{tabular} \caption{Win Condition categorization. Environments are either Win-Lose, or have a scale of victory points (VP).} \label{table:WinConditions} \end{table} Games range from simple, clearly defined and unchanging win conditions (e.g. Chess, Go) to more complex conditions, which in wargames may be asymmetric, and could potentially change during the course of a campaign. In a wargame the same scenario could be played with different win conditions for each player in order to provide different challenges. In most games to date, the win conditions are single-objective with binary (or ternary if a game can end in a draw / stalemate) outcomes (e.g. in chess, the aim is to get the opponent in Checkmate), even though they can be achieved in a multitude of ways. In this case a player either wins or loses (or draws). This can be supplemented by a numeric score (or Victory Points) of some sort. Many Atari/GVGAI games have both a win-lose condition combined with a score, for example a treasure hunt game may be `won' when the player reaches the exit before being eaten by a spider, but their score is determined by the number of gold coins they pick up en route. In a similar way wargames can be multi-objective, where the aim is to achieve a particular outcome while minimising casualties and economic cost. These are often reformulated, as in Flashpoint, to a numeric scale by assigning victory points to every feature of the outcome, although this mapping may be unsatisfactory and can lead to unexpected (and implausible) AI behaviour if the balance of the reward is mis-specified. Biasing the AI in this way can also discourage exploration away from pre-conceived strategies embedded implicitly in the victory points scale. An alternate, multi-objective, approach is not to weight the different parts of the `score', but seek a range of different policies that are `optimal' in different ways~\cite{Deb_Agrawal_Pratap_Meyarivan_2000, Perez-Liebana_Mostaghim_Lucas_2016}. For example one policy might minimise casualties and fuel usage, while another optimises the number of enemy forces degraded with less concern for the associated cost. This can be a useful way of exploring the space of viable strategies. The multi-objective approach is covered in more detail in Section~\ref{sect:Exploration}. Of the benchmark games the RTS and Dota2 games are Win-Lose, and differ in this respect to wargames, while some Atari games are closer given the presence of a running score as well as a win-lose condition. MuJoCo is rated as a victory point scale as success is measured by how far and fast an agent learns to move. \subsection{Reward Sparsity}\label{sect:RewardSparsity} This refers to the inherent rewards given \emph{during} a game. For classic games such as chess, the only inherent reward is at the end of a game when a player wins, loses or draws. This is closely linked to the Win Conditions of a game in Table~\ref{table:WinConditions}. A game with a binary Win-Lose condition almost by definition also has a sparse reward, while one with a VP Scale of some type provides inherent rewards (VPs) as the game progresses. Most RTS and wargames have natural features to provide anytime score updates, for example by penalising friendly casualties and loss of assets and incentivising territory gain. However, these natural heuristics can be misleading in the short-term with immediate losses required (such as sending units into combat to take casualties) as an investment for a longer-term payoff (taking a strategic location). In this sense they have elements of `deceptive' games, in which following the immediate reward signal is counter-productive to final victory~\cite{Anderson_Stephenson_Togelius_Salge_Levine_Renz_2018}. Hence, methods to promote exploration such as intrinsic motivation and curriculum learning can be very relevant when a key desired outcome is exploration of possible tactics and doctrines, as in Concept Development wargames. Hence, while wargames, like RTS, do have a short-term point score many of the AI techniques developed to cope with sparse rewards are important. These are looked at in more detail in Section~\ref{sect:RelativeRS}. \subsection{Active/Adversarial Opponents}\label{sect:Opponent} \begin{table}[] \begin{tabular}[t]{|l|l|l|l|l|l|l|} \hline \textbf{CMANO} & \textbf{Flashpoint} & \textbf{Chess/Go} & \textbf{Atari/} & \textbf{Starcraft II} & \textbf{MicroRTS} & \textbf{MuJoCo}\\ & & & \textbf{GVGAI} & \textbf{+ Dota2} & & \\ \hline Adaptive & Adaptive & Adaptive & Non-Adapt. & Adaptive & Adaptive & Non-Adapt. \\ Adversarial & Adversarial & Adversarial & & Adversarial & Adversarial & \\ \hline \end{tabular} \caption{Opponent categorization. Opponents may be Adaptive to a players actions and may or may not also be Adversarial to them.} \label{table:Opponent} \end{table} An essential component of a wargame is one or more opponents. In this they contrast with many Atari games in which a single-player fights against the environment, as in Space Invaders, Pac-Man or Asteroids. In these, the enemies are scripted units that do not change behaviour or adapt to player actions. Other Atari games have enemies that do adapt, for example the ghosts in Ms Pac-Man will change direction to move towards a visible player, however these remain simple reactive scripts and are not `Adversarial' in terms of planning a strategy to win the game. This contrasts with Chess, Go, RTS games or wargames, in which there is a clearly defined opposing force that makes proactive decisions to achieve objectives and adapt to the player's actions. All the benchmark games considered are one or two player games. Some wargames can have more than two sides, for example a neutral Brown or White supranational force, or a Pink side that may, depending on what happens, become actively allied to Blue or Red. A large Planned Force Test will have multiple autonomous players on each side, with restricted communication between them even if they are collaborating on a joint goal. However, the computerised wargames directly relevant to AI control are Red vs Blue 2-player situations, and here the essential requirement to deal with large numbers of units controlled by a single player is covered in detail in Section~\ref{sect:StateSpace}. There is also at this stage relatively little academic work that addresses the unique aspects of wargames with more than two interacting players, especially where communication can occur. This can introduce `king-making' in which a third player can decide which of the others achieves a victory objective, and negotiation between players can become vital to win\cite{elias2012characteristics}. \subsection{Scenario Variability}\label{sect:ScenarioVar} \begin{table}[] \begin{tabular}[t]{|l|l|l|l|l|l|l|l|} \hline \textbf{CMANO} & \textbf{Flashpoint} & \textbf{Chess} & \textbf{Atari/} & \textbf{Starcraft II} & \textbf{Dota2} & \textbf{$\mu$RTS} & \textbf{MuJoCo}\\ & & \textbf{/Go} & \textbf{GVGAI} & & & & \\ \hline Scenario & Scenario & Fixed & Scenario & Scenario & Scenario & Scenario & Fixed \\ \hline \end{tabular} \caption{Scenario categorization.} \label{table:Scenario} \end{table} In most classic board games the start state is always the same, whereas in wargames the same underlying rules may be played out over a wide range of initial scenarios. In Table~\ref{table:Scenario} games can relatively cleanly be split into those that have some concept of `scenario' (for Atari games these are different `levels', which use the same underlying rules but with different maps), and those which have a single fixed set up. In the case of DOTA2 there is little difference between maps compared to RTS and wargames, however a similar level of variability comes in due to the combinations of different heroes that form both teams; and with a slight stretch we can consider these different opposing teams as different `scenarios'. The biggest risk of using techniques with a single fixed set up is of over-fitting to the map. This is not an issue in Chess or Go, in which we want to overfit; learning a policy able to generalise well to a 7x7 board, or with half the number of starting pawns would be wasteful. In wargames, as in RTS games generally, we are only interested in AI techniques that can generalise to scenario variations. As a note of caution, some papers in the literature use games that support scenarios/levels, but only report results that are trained and tested on one specific set up. Planning techniques in general are more robust in the case of scenario variability than methods without a planning component, such as \emph{vanilla} RL. In particular, both MicroRTS and GVGAI competitions put the trained agent through multiple maps, at least some of which are unseen prior to the competition. It is noticeable that the winning entries in both competitions (see~\cite{Perez-Liebana_Samothrakis_Togelius_Schaul_Lucas_Couetoux_Lee_Lim_Thompson_2016, Ontanon_Barriga_Silva_Moraes_Lelis_2018} for a summary of these) use planning and search-based methods with little direct RL, even though the decision time for each move is only in the range 40-100 milliseconds on a single processor. The MicroRTS winners tend to use a two-level hierarchical approach to select amongst scripts to use for different units (these are discussed in more detail in Section~\ref{sect:unitTechniques}). The headline work from DeepMind and OpenAI on Starcraft II and Dota2 using Deep RL does support multiple `scenarios' in the sense of having different heroes, maps and opposing races. However these are all available at the start and included in the training process. There is little work showing good performance with Deep RL on unseen environments, although this is an area of active research interest in terms of transfer-learning. This does not mean Deep RL is not useful in the context of wargames, but is not suitable for completely unseen scenarios. Any substantive change to a scenario will require some training of a Deep RL model for good performance. The issues around this overfitting in Deep RL are discussed in more detail, along with mitigation approaches, in Sections~\ref{sec:continual_learning} and~\ref{sect:overfit}. \subsection{Objective Variability}\label{sect:ObjectiveVar} In a wargame the objective that a player is striving for may change as the game progresses. For example due to changes or setbacks on other fronts, a player attempting to take a strategic location may be ordered to fall back and reinforce elsewhere. This can cause the `reward' function or win condition to change drastically. Wargames such as CMANO come with a large number of scenarios, and these can potentially be played out with a number of different objectives for each player. This presents a significant generalisation problem for Deep RL algorithms, which are normally trained with a specific objective in mind, and transferring what they learn during training on one objective to then act in the pursuit of a different objective is likely to remain a research challenge for some time. If this variability is incorporated during training, then this is less of an problem. This could be via a multi-objective approach, or incorporating the possible objectives in a VP-scale (see section~\ref{sect:WinConditions}). Planning/search methods with a forward model will be better at adjusting to changing objectives if this is needed. None of the considered benchmarks really incorporate any variation of game objectives in this way. \subsection{Player Asymmetry}\label{sect:PlayerAsymmetry} \begin{table}[] \begin{tabular}[t]{|l|l|l|l|l|l|l|} \hline \textbf{CMANO} & \textbf{Flashpoint} & \textbf{Chess/Go} & \textbf{Atari/} & \textbf{Starcraft II} & \textbf{MicroRTS} & \textbf{MuJoCo}\\ & & & \textbf{GVGAI} & \textbf{+ DOTA 2} & & \\ \hline Asymmetric & Asymmetric & Symmetric & - & Asymmetric & Symmetric & - \\ \hline \end{tabular} \caption{Player asymmetry categorisation. Atari and MuJoCo are 1-player environments.} \label{table:Asymmetry} \end{table} This refers to the asymmetry in player capabilities and roles. For example, although chess may have a slight first-player advantage, the action space is the same for each player, and the game is well balanced and largely symmetric. On the other hand, in the Ms Pac-Man versus ghosts competition, AI agents could play as Pac-Man, or play as the entire team of ghosts, hence the objectives and the actions spaces are both asymmetric. Wargames are in general highly asymmetric, with differences in capabilities, unit compositions, starting positions and ultimate objectives between the two sides. Even the RTS games in Table~\ref{table:Asymmetry} are relatively symmetric compared to wargames; in Starcraft II there are four possible factions with specific units, but each game starts with a similar set up and both sides have the same objective to destroy the other. In MicroRTS the same units and technology are shared by both sides. DOTA 2 might have very different teams of 5 heroes on each side, but the map is essentially symmetric, as is the goal of each side to destroy the other's base. High levels of asymmetry prevent easy use of some AI techniques, especially those that rely on self-play in RL. In this approach the AI can bootstrap its playing ability by using itself, or a slightly older version of itself, to play the opponent. However, the policy that the Blue side is learning is not \textit{a priori} going to work very well if used to model the actions of an asymmetric Red side. \subsection{Features specific to wargames}\label{sect:wargameSpecific} This section discusses some requirements of practical wargames not in directly linked to the game-play itself, but to the underlying purpose of running the wargame, and the efficient generation of desired outcomes. \subsubsection{Instrumentation} A frequent desired outcome of wargames is to understand key decision points in a game rather than just the win-lose result. The end-user is the wargame analyst. For example, a rare event such as the early sinking of Blue's only aircraft carrier due to a lucky missile hit may mean that playing out the rest of the scenario is of limited value. What is important to know is that there is a risk of this happening, perhaps even quantified that this occurs in 2-5\% of games. Finding this important insight can require excessive data mining and be easy to miss. Wargames hence require rich instrumentation of the trajectory that an individual game takes to facilitate anomaly detection of this sort of situation and reduce the work required to understand the location of common branch points. \subsubsection{Moderation} Computer-moderated wargames always have options for human intervention to adjust the state of play at any point and/or back-track to a previous point. This is required when one side is being played by humans to make efficient use of their time. If a low-probability high-impact event occurs, such as the aircraft carrier loss of the previous example, then the decision may be made to branch at that point, log the result, and then continue play in a counterfactual universe. This need for human moderation is less of an issue if all sides are AI-controlled. \subsubsection{Player Constraints} One issue with human players in wargames is a tendency to `play the game' rather then `play the problem'. Examples are the `last turn effect' in which players may gamble everything on a chance of victory even if in the real world this would leave them heavily exposed to future enemy action~\cite{rubel2006epistemology}. This is an issue to which AI agents are particularly prone without careful specification of the reward signal they use as outlined in Section~\ref{sect:WinConditions}. A related requirement is often for players to be `credible' in terms of following operational constraints, such as orders from further up the command hierarchy or standard operating procedures for the side in question. This only applies in some types of wargames; in Concept Development the objective is to deliberately explore diverse and unexpected strategies with new equipment or capabilities. We discuss useful techniques for this later in Section~\ref{sect:Exploration}. One issue with practical wargames is that valuable time of participating human experts can be taken up with micro-management of units. This detracts from the central aim of the wargame to analyse/train human decision-making. A helpful tool in some wargames would be to have an AI control units once given a high-level order. It is essential that this is realistic as naive use of A* pathfinding and simple scripted AI has shown problems with units moving directly from A to B without paying attention to available cover or the unexpected appearance of enemy forces. \vfill
{'timestamp': '2020-09-28T02:09:07', 'yymm': '2009', 'arxiv_id': '2009.08922', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08922'}
arxiv
\section{Appendix} \subsection{Notation Summary} \begin{table}[htp] \centering \caption{Notation}\label{tab:notation} \begin{tabular}{c|l} \hline Notation & Definition \\ \hline\hline $\mathcal{D}_s=\{(x_i^s, t_i^s)\}_{i=1}^{n_s}$ & Training set with $n_s$ examples in the central server \\ $\mathcal{D}_{test}$ & Test data set in the central server \\ $\mathcal{D}_k= \{(x_i^k, t_i^k)\}_{i=1}^{n_k}$ & Local training set with $n_k$ examples in the $k^{\mathrm{th}}$ client\\ $C$ & Number of label classes in the training set, i.e., $t\in \mathbb{R}^C$ \\ $K$ & Number of clients \\ $f(\cdot)$ & Learning algorithm \\ $L(\cdot,\cdot)$ & Loss function over prediction and target \\ $y_*, y_m$ & Optimal prediction and main prediction \\ $B(\cdot), V(\cdot), N(\cdot)$ & Expected bias, variance and irreducible noise \\ $\mathbb{E}[\cdot]$ & Expected value \\ $\mathcal{D}_p$ & Candidate training set for poisoning attack \\ $w_k$ & Local model parameters over $\mathcal{D}_k$ \\ $w_G$ & Server's global model parameters \\ $f_{\mathcal{D}_k}(x; w_k)$ ($f_{\mathcal{D}_k}$ for short) & Local model prediction on $x$ with parameters $w_k$ \\ $\mathrm{Aggregate}(w_1,w_2,\cdots,w_K)$ & Synchronous aggregation function over local parameters \\ $B(\cdot; w_1,\cdots,w_K)$ & Empirical estimated bias over training sets $\{\mathcal{D}_1, \cdots,\mathcal{D}_K\}$ \\ $V(\cdot; w_1,\cdots,w_K)$ & Empirical estimated variance over training sets $\{\mathcal{D}_1, \cdots,\mathcal{D}_K\}$ \\ $E$ & Number of local epochs \\ $F$ & Fraction of clients selected on each round \\ $B$ & Batch size of local client \\ $\eta$ & Learning rate \\ $\Omega(\cdot)$ & Perturbation constraint \\ $\epsilon$ & Perturbation magnitude \\ $\hat{x}$ & Adversarial counterpart of an example $x$, i.e., $\hat{x}\in \Omega(x)$ \\ $H(\cdot)$ & Entropy \\\hline \end{tabular} \end{table} \subsection{Proof of Theorems} {\bf Proof of Theorem~\ref{thm:empirical_estimation}}. Theorem~\ref{thm:empirical_estimation} states that assume $L(\cdot,\cdot)$ is the cross-entropy loss function, then the empirical estimated main prediction $y_m$ for an input example $(x,t)$ has the following closed-form expression: \begin{equation*} y_m(x; w_1,\cdots,w_K) = \frac{1}{K}\sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) \end{equation*} Furthermore, the empirical bias and variance as well as their gradients over input $x$ are estimated as: \begin{equation*} \begin{aligned} B(x; w_1,\cdots,w_K) = \frac{1}{K} \sum_{k=1}^K L(f_{\mathcal{D}_k}(x;w_k), t) &~~\mathrm{and}~~ V(x; w_1,\cdots,w_K) = L(y_m, y_m) = H(y_m) \\ \nabla_x B(x; w_1,\cdots,w_K) &= \frac{1}{K} \sum_{k=1}^K \nabla_x L(f_{\mathcal{D}_k}(x;w_k), t) \\ \nabla_x V(x; w_1,\cdots,w_K) &= - \frac{1}{K}\sum_{k=1}^K \sum_{j=1}^C (\log{y_m^{(j)}} + 1)\cdot \nabla_{x} f_{\mathcal{D}_k}^{(j)}(x;w_k) \end{aligned} \end{equation*} where $H(y_m) = -\sum_{j=1}^C y_m^{(j)}\log{y_m^{(j)}}$ is the entropy of the optimal prediction $y_m$ and $C$ is the number of classes. \begin{proof} We first calculate the main prediction. Let \begin{equation*} \begin{aligned} \mathcal{M} &= \frac{1}{K}\sum_{k=1}^K L(f_{\mathcal{D}_k}(x;w_k), y') \\ &= -\frac{1}{K}\sum_{k=1}^K \big( f_{\mathcal{D}_k}(x;w_k) \cdot \log{y'} + (1- f_{\mathcal{D}_k}(x;w_k)) \cdot \log{(1-y')} \big) \end{aligned} \end{equation*} Take the derivative of $\mathcal{M}$ with respect to $y'$, we have \begin{equation*} \begin{aligned} \frac{\partial \mathcal{M}}{\partial y'} &= -\frac{1}{K}\sum_{k=1}^K \Big( \frac{f_{\mathcal{D}_k}(x; w_k)}{y'} - \frac{1- f_{\mathcal{D}_k}(x;w_k)}{1-y'} \Big) = -\frac{1}{K}\sum_{k=1}^K \frac{f_{\mathcal{D}_k}(x;w_k) - y'}{y'(1-y')} \end{aligned} \end{equation*} By letting $\partial \mathcal{M} / \partial y' = 0$, we have \begin{equation*} y_m(x; w_1,\cdots,w_K) = \frac{1}{K}\sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) \end{equation*} Then for bias and variance, we have, \begin{equation*} \begin{aligned} B(x; w_1,\cdots,w_K) &= L \Big(\frac{1}{K}\sum_{k=1}^K f_{\mathcal{D}_k}(x;w_k), t \Big) \\ &= -\frac{1}{K}\sum_{k=1}^K f_{\mathcal{D}_k}(x;w_k) \cdot \log{t} + \Big( 1-\frac{1}{K}\sum_{k=1}^K f_{\mathcal{D}_k}(x;w_k) \Big) \cdot \log(1-\log{t}) \\ &= -\frac{1}{K}\sum_{k=1}^K \Big( f_{\mathcal{D}_k}(x;w_k) \cdot \log{t} + (1- f_{\mathcal{D}_k}(x;w_k)) \cdot \log(1-\log{t}) \Big) \\ &= \frac{1}{K} \sum_{k=1}^K L(f_{\mathcal{D}_k}(x;w_k), t) \end{aligned} \end{equation*} and \begin{equation*} \begin{aligned} V(x) &= \frac{1}{K} \sum_{k=1}^K L(f_{\mathcal{D}_k}(x;w_k), y_m) \\ &= -\frac{1}{K} \sum_{k=1}^K \Big( f_{\mathcal{D}_k}(x;w_k) \log{y_m} + (1- f_{\mathcal{D}_k}(x;w_k)) \log(1-\log{y_m}) \Big) \\ &= -y_m \log{y_m} - (1- y_m) \log(1-\log{y_m}) \\ &= L(y_m, y_m) \\ &= H(y_m) \end{aligned} \end{equation*} which completes the proof. \end{proof} \subsection{Additional Experiments} \subsubsection{MSE v.s. Cross-entropy}\label{sec:mse_ce} Both cross-entropy and mean squared error (MSE) loss functions could be used for training a neural network model. In our paper, the loss function of neural networks determines the derivation of bias and variance terms used for producing the adversarial examples. More specifically, we show that when using cross-entropy loss function, the empirical estimate of bias and variance as well as their gradients over input $x$ are as follows: \begin{equation*} \begin{aligned} B_{CE}(x; w_1,\cdots,w_K) = \frac{1}{K} \sum_{k=1}^K L(f_{\mathcal{D}_k}(x;w_k), t) &~~\mathrm{and}~~ V_{CE}(x; w_1,\cdots,w_K) = H(y_m) \\ \nabla_x B_{CE}(x; w_1,\cdots,w_K) &= \frac{1}{K} \sum_{k=1}^K \nabla_x L(f_{\mathcal{D}_k}(x;w_k), t) \\ \nabla_x V_{CE}(x; w_1,\cdots,w_K) &= - \frac{1}{K}\sum_{k=1}^K \sum_{j=1}^C (\log{y_m^{(j)}} + 1)\cdot \nabla_{x} f_{\mathcal{D}_k}^{(j)}(x;w_k) \end{aligned} \end{equation*} In the similar way, we show that when using MSE loss function, the empirical estimate of bias and variance as well as their gradients over input $x$ are as follows: \begin{equation*} \begin{aligned} B_{MSE}(x; w_1,\cdots,w_K) &= ||\frac{1}{K} \sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) - t||_2^2 \\ V_{MSE}(x; w_1,\cdots,w_K) &= \frac{1}{K-1} \sum_{k=1}^K ||f_{\mathcal{D}_k}(x;w_k) - \frac{1}{K} \sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k)||_2^2 \end{aligned} \end{equation*} and \begin{equation*} \begin{aligned} &\nabla_x B_{MSE}(x; w_1,\cdots,w_K) = \left(\frac{1}{K} \sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) - t \right) \left( \frac{1}{K} \sum_{k=1}^K \nabla_x f_{\mathcal{D}_k}(x; w_k) \right) \\ &\nabla_x V_{MSE}(x; w_1,\cdots,w_K)\\ &= \frac{1}{K-1} \sum_{k=1}^K \left(\left( f_{\mathcal{D}_k}(x;w_k) - \frac{1}{K} \sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) \right) \left(\nabla_x f_{\mathcal{D}_k}(x;w_k) - \frac{1}{K} \sum_{k=1}^K \nabla_x f_{\mathcal{D}_k}(x; w_k)\right)\right) \end{aligned} \end{equation*} It can be seen that the empirical estimate of $\nabla_x B_{MSE}(x; w_1,\cdots,w_K)$ has much higher computational complexity than $\nabla_x B_{CE}(x; w_1,\cdots,w_K)$ because it involves the gradient calculation of prediction vector $f_{\mathcal{D}_k}(x; w_k)$ over the input tensor $x$. Besides, it is easy to show that the empirical estimate of $\nabla_x V_{MSE}(x; w_1,\cdots,w_K)$ is also computationally expensive. We empirically compare the cross-entropy and MSE loss function in our framework. Table~\ref{mse_ce} reports the adversarial robustness of our decentralized framework w.r.t. FGSM attack ($\epsilon=0.3$) on MNIST with IID setting. It can be observed that (1) our framework with MSE loss function has significantly larger running time; (2) the robustness of our framework with MSE loss function becomes slightly weaker when using the MSE loss function, which might be induced by the weakness of MSE loss function in the classification problem setting. \begin{table}[htp] \centering \begin{tabular}{ccccc} \hline \multirow{2}{*}{} & \multirow{2}{*}{Clean} & \multicolumn{3}{c}{{{Decent\_BVA}}{}} \\ \cline{3-5} & & BiasOnly & VarianceOnly & BVA \\ \hline Cross-entropy & 0.5875 (38.13s) & 0.7627 (47.58s) & 0.7594 (63.46s) & 0.7756 (63.67s) \\ MSE & 0.6011 (39.67s) & 0.7112 (65.03s) & 0.7108 (162.40s) & 0.7119 (179.60s) \\ \hline \end{tabular} \caption{Adversarial robustness with different loss functions and running time (second/epoch)}\label{mse_ce} \end{table} \subsubsection{BV-PGD v.s. BV-FGSM} Our bias-variance attack could be naturally generalized to any gradient-based adversarial attack algorithms when the gradients of bias $B(\cdot)$ and variance $V(\cdot)$ w.r.t. $x$ are tractable to be estimated from finite training sets. Here we empirically compare the adversarial robustness of our framework with BV-PGD or BV-FGSM. Table \ref{fgsm_pgd} provides our results on w.r.t. FGSM and PGD attacks ($\epsilon=0.3$) on MNIST with IID and non-IID settings. Compared to FedAvg, our framework {{Decent\_BVA}}{} with either BV-FGSM or BV-PGD could largely improve the model robustness against adversarial noise. \begin{table}[htp] \centering \setlength\tabcolsep{1pt} \begin{tabular}{ccccccccccc} \hline \multicolumn{2}{c}{\multirow{2}{*}{}} & \multicolumn{4}{c}{IID} & & \multicolumn{4}{c}{non-IID} \\ \cline{3-6} \cline{8-11} \multicolumn{2}{c}{} & Clean & FGSM & PGD-10 & PGD-20 & & Clean & FGSM & PGD-10 & PGD-20 \\ \hline FedAvg & - &0.9863 & 0.5875 & 0.6203 & 0.2048 & & 0.9462 & 0.1472 & 0.5254 & 0.0894 \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}{{Decent\_BVA}}{} \\ (BV-FGSM training)\end{tabular}} & BiasOnly & 0.9840 & 0.7627 & 0.7671 & 0.5154 & & 0.9597 & 0.6510 & 0.6226 & 0.3614 \\ & VarianceOnly & 0.9834 & 0.7594 & 0.7616 & 0.5253 & & 0.9577 & 0.5979 & 0.5990 & 0.3504 \\ & BVA & 0.9837 & 0.7756 & 0.7927 & 0.5699 & & 0.9671 & 0.6696 & 0.6953 & 0.4717 \\ \hline \multirow{3}{*}{\begin{tabular}[c]{@{}c@{}}{{Decent\_BVA}}{}\\ (BV-PGD training)\end{tabular}} & BiasOnly & 0.9817 & 0.7578 & 0.8455 & 0.6422 & & 0.9690 & 0.6585 & 0.7868 & 0.5749 \\ & VarianceOnly & 0.9850 & 0.7419 & 0.8226 & 0.6076 & & 0.9688 & 0.6293 & 0.7587 & 0.5299 \\ & BVA & 0.9849 & 0.7565& 0.8399 & 0.6317 & & 0.9670 & 0.6592 & 0.7836 & 0.5752 \\ \hline \end{tabular} \caption{Adversarial robustness with BV-PGD and BV-FGSM}\label{fgsm_pgd} \end{table} \subsubsection{Parameter Analysis} In this part, we perform parameter analysis regarding a few key hyper-parameters that have high influence on the model performance. Since our target is to train a decentralized model where the robustness of the model is high but the accuracy still remains. For that purpose, we have the following three sets of experimental plots to guide us choosing the optimal hyper-parameters used in the experiments. \begin{figure}[!h] \hspace{-3mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/numShare_plot1.png} \vspace{-6mm} \caption{\small Accuracy of clean training with varying $n_s$} \label{fig_num_share1} \end{minipage}% \hfill \hspace{1mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/numShare_plot2.png} \vspace{-6mm} \caption{\small Robustness under FGSM attack with varying $n_s$} \label{fig_num_share2} \end{minipage} \hfill \hspace{0mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/numShare_plot3.png} \vspace{-6mm} \caption{\small Robustness under PGD-20 attack with varying $n_s$} \label{fig_num_share3} \end{minipage} \vspace{-62mm} \end{figure} {\bfseries Number of shared perturbed samples $n_s$}. From Fig.~\ref{fig_num_share1}, we see that the accuracy of \textit{FedAvg} (i.e., $n_s=0$) has the best accuracy as we expected. For \textit{{{Decent\_BVA}}} with varying size of asymmetrical transmitted perturbed samples (i.e., $n_s=8, 16, 32, 64$), its performance drops slightly with increasing $n_s$ (on average drop of $0.05\%$ per plot). As a comparison, the robustness on test set $\mathcal{D}_{test}$ increases dramatically with increasing $n_s$ (increasing ranges from $18\%$ to $22\%$ under FGSM attack and ranges from $15\%$ to $60\%$ under PGD-20 attack). However, choosing large $n_s$ would have high model robustness but also suffer from the high communication cost. In experiment, we choose $n_s=64$ for the ideal trade-off point. \begin{figure}[!h] \hspace{-3mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/momentum_plot1.png} \vspace{-6mm} \caption{\small Accuracy of clean training with varying momentum} \label{fig_momentum1} \end{minipage}% \hfill \hspace{1mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/momentum_plot2.png} \vspace{-6mm} \caption{\small Robustness under FGSM attack with varying momentum} \label{fig_momentum2} \end{minipage} \hfill \hspace{0mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/momentum_plot3.png} \vspace{-6mm} \caption{\small Robustness under PGD-20 attack with varying momentum} \label{fig_momentum3} \end{minipage} \vspace{-55mm} \end{figure} {\bfseries Momentum}. We also care about the choice of options in the SGD optimizer's settings. As seen in Fig.~\ref{fig_momentum1}, the accuracy of clean training is monotonically increase with momentum. Interestingly, we also observe that the decentralized model is less vulnerable when momentum is large no matter the adversarial attack is FGSM or PGD-20 on test set $\mathcal{D}_{test}$, see Fig.~\ref{fig_momentum2} and Fig.~\ref{fig_momentum3}. This phenomenon is also monotonically observed when we changing momentum from $0.1$ to $0.9$ and this suggests us to choose momentum as $0.9$ through all experiments. \begin{figure}[!h] \hspace{-3mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/local_epoch_plot1.png} \vspace{-6mm} \caption{\small Accuracy of clean training with varying local epoch} \label{fig_localEpoch1} \end{minipage}% \hfill \hspace{1mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/local_epoch_plot2.png} \vspace{-6mm} \caption{\small Robustness under FGSM attack with varying local epoch} \label{fig_localEpoch2} \end{minipage} \hfill \hspace{0mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4.5cm,height=4cm]{figures/local_epoch_plot3.png} \vspace{-6mm} \caption{\small Robustness under PGD-20 attack with varying local epoch} \label{fig_localEpoch3} \end{minipage} \vspace{-60mm} \end{figure} {\bfseries Local epochs $E$}. The third important factor of decentralized training is the number of epoch $E$ we should use. In Fig.~\ref{fig_localEpoch1}, we clearly see that more local epochs in each client leads to more accurate aggregated server model in prediction. Similarly, its robustness against both FGSM and PGD-20 attack on test set $\mathcal{D}_{test}$ also have the best performance when local epochs are large on device. Hence, in our experiments, if the on-device computational cost is not very high (large data example size, model with many layers), we choose $E=50$. Otherwise, we will reduce $E$ to a smaller number accordingly. \subsection{Network Architectures} For the MNIST and Fashion-MNIST data sets, the CNN network structure is shared since the input image examples have the same dimensions. The detail is shown in Table.~\ref{arch_cnn_mnist}. Conv1 and Conv2 denote the convolution block that may have one or more convolution layers. E.g., $[5 \times 5, 10] \times 1$ denotes 1 cascaded convolution layers with 10 filters of size $5 \times 5$. \begin{table}[h!] \centering \begin{tabular}{|l|c|} \hline \textbf{Layers} & \textbf{CNN-MNIST} \\ \hline \hline Conv1 & {[}5 $\times$ 5, 10{]} $\times$ 1 \\ \hline Pool1 & 2 $\times$ 2 Max Pooling, Stride 2 \\ \hline Conv2 & {[}5 $\times$ 5, 20{]} $\times$ 1 \\ \hline Dropout & 0.5 \\ \hline Pool2 & 2 $\times$ 2 Max Pooling, Stride 2 \\ \hline FC1 & 50 \\ \hline FC2 & 10 \\ \hline \end{tabular} \vspace{2mm} \caption{CNN architecture for MNIST and Fashion-MNIST} \label{arch_cnn_mnist} \end{table} For the CIFAR data set, the CNN network structure is shown in Table.~\ref{arch_cnn_cifar}. It should be noticed that state-of-the-art approaches have achieved a better test accuracy for CIFAR, nevertheless, this model is sufficient for our experimental needs since our goal is to evaluate the robust decentralized model instead of achieving the best possible accuracy on testing stage. \begin{table}[!t] \centering \begin{tabular}{|l|c|} \hline \textbf{Layers} & \textbf{CNN-CIFAR} \\ \hline \hline Conv1 & {[}3 $\times$ 3, 32{]} $\times$ 1 \\ \hline Conv2 & {[}3 $\times$ 3, 64{]} $\times$ 1 \\ \hline Pool1 & 2 $\times$ 2 Max Pooling, Stride 2 \\ \hline Conv3 & {[}3 $\times$ 3, 128{]} $\times$ 2 \\ \hline Pool2 & 2 $\times$ 2 Max Pooling, Stride 2 \\ \hline Dropout & 0.05 \\ \hline Conv4 & {[}3 $\times$ 3, 256{]} $\times$ 2 \\ \hline Pool3 & 2 $\times$ 2 Max Pooling, Stride 2 \\ \hline Dropout & 0.1 \\ \hline FC1 & 1024 \\ \hline FC2 & 512 \\ \hline Dropout & 0.1 \\ \hline FC3 & 10 \\ \hline \end{tabular} \vspace{2mm} \caption{CNN architecture for CIFAR-10} \label{arch_cnn_cifar} \end{table} \section{Introduction} \vspace{-2mm} The explosive amount of decentralized user data collected from the ever-growing usage of smart devices, e.g., smartphones, wearable devices, home sensors, etc., has led to a surge of interest in the field of decentralized learning. To protect the privacy-sensitive data of the clients, privacy-preserving decentralized learning~\cite{mcmahan2017communication, fl_yangqiang} has been proposed. It decentralizes the model learning by allowing a large number of clients to train local models using their own data, and then collectively merges the clients' models on a central server by secure aggregation~\cite{homomorphic_encryption}. Privacy-preserving decentralized learning has attracted much attention in recent years with the prevalence of efficient light-weight deep models~\cite{mobilenet} and low-cost network communications~\cite{TernGrad}. In decentralized learning, the central server can only inspect the secure aggregation of the local models as a whole. Consequently, it is susceptible to corrupted updates from the clients (system failures, adversarial manipulations, etc.). Recently, multiple robust decentralized learning models~\cite{robust_fed_localPoisoning, robust_agg_fed, robust_fed_weightTruncate, robust_fed_hyperParameter} have been proposed. However, these works only focus on performing client-level model poisoning attacks or designing server-level aggregation variants with hyper-parameter tuning, and largely ignore the underlying true cause of decentralized learning's vulnerability that comes from the server's generalization error. Our work bridges this gap by investigating the loss incurred during secure aggregation of decentralized learning from the perspective of bias-variance decomposition~\cite{pedro2000unified, valentini2004bias}. Specifically, we show that the untargeted adversarial attacks over the central server can be decomposed as bias attack and variance attack over multiple local clients, where the bias measures the loss triggered by the main prediction of these clients, and the variance measures the variations among clients' model predictions. In this way, we can perform adversarial training on local models by receiving a small amount of bias-variance perturbed data from the server via asymmetrical communication. The experiments are conducted on neural networks with cross-entropy loss, however, other loss functions are also allowed as long as their gradients in terms of bias and variance are tractable to be estimated from local clients' models. In this way, any gradient-based adversarial training strategies could be used by taking the bias-variance oriented adversarial examples into consideration, e.g., bias-variance based FGSM and PGD proposed in this paper. Compared with previous work, our major contributions include: \begin{itemize}[leftmargin=*,noitemsep,nolistsep] \item We give the exact solution of bias-variance analysis in terms of the generalization error for neural network based decentralized learning. \item Without violating the clients' privacy, we show that providing a tiny amount of bias-variance perturbed data to the clients through asymmetrical communication could significantly improve the robustness of the server model. In contrast, the conventional decentralized learning framework is vulnerable to the strong attacking methods with increasing communication rounds. \item We conduct extensive experiments to demonstrate the robustness of our proposed framework against adversarial attacks. \end{itemize} \vspace{-2mm} \section{Preliminaries} \vspace{-2mm} \subsection{Notation} \vspace{-2mm} In decentralized learning, there are a central server and $K$ different clients, each with access to a private training set $\mathcal{D}_k= \{(x_i^k, t_i^k)\}_{i=1}^{n_k}$, where $x_i^k$, $t_i^k$, and $n_k$ are the features, label, and number of training examples in the $k^{\mathrm{th}}$ client $(k=1,2\cdots,K)$. The raw data $\mathcal{D}_k$ must not be shared with the server and other clients. In addition, there is a small public training set $\mathcal{D}_s=\{(x_j^s, t_j^s)\}_{j=1}^{n_s}$ with $n_s$ training examples in the server which could be shared with clients. The goal of decentralized learning is to train a global classifier $f(\cdot)$ using knowledge from all the clients such that it generalizes well over test data $\mathcal{D}_{test}$. The notation used in this paper is summarized in the Appendix (see Table \ref{tab:notation}). \vspace{-2mm} \subsection{Problem Definition}\label{sec:problem_definition} \vspace{-2mm} Privacy-preserving decentralized learning trains the machine learning models without directly accessing to the clients' raw data. A large number of clients could collaborate in achieving the learning objective under the coordination of a central server which aggregates the asynchronous local clients' parameters~\cite{kairouz2019advances}. In this paper, we study the adversarial robustness of neural networks\footnote{Our theoretical contribution mainly focuses on classification using neural networks with cross-entropy loss and mean squared loss. However, the proposed framework is generic to allow the use of other classification loss functions as well.} in the decentralized learning setting, and we formulate robust decentralized learning as follows. \begin{definition} \textbf{(Robust Decentralized Learning)} \\ \indent\textbf{\em Input:} (1). A set of private training data $\{\mathcal{D}_k\}_{k=1}^K$ on $K$ different clients; (2). Limited training data $\mathcal{D}_s$ on the central server; (3). Learning algorithm $f(\cdot)$ and loss function $L(\cdot, \cdot)$. \indent\textbf{\em Output:} A trained model on the central server that is robust against adversarial perturbation. \end{definition} We would like to point out that our problem definition has the following properties: \begin{itemize}[leftmargin=*,noitemsep,nolistsep] \item {\bf Asymmetrical communication:} In our design, the asymmetrical communication between each client and server cloud is allowed: the server provides both global model parameters and limited training data to the clients; while each client uploads its local parameters back to the server. \item {\bf Data distribution:} In this paper, we assume that all training examples of the clients and the server follow the same data distribution. However, the experiments show that our proposed algorithm also achieves satisfactory performance in the non-IID setting, which is typical among personalized clients (e.g., users' mobile devices~\cite{hard2018federated}) producing the non-IID local data sets in real scenarios. \item {\bf Shared learning algorithm:} We assume that all the clients would use the identical model $f(\cdot)$, including model architectures as well as hyper-parameters (e.g., learning rate, local epochs, local batch size), which could be assigned by the central server. \end{itemize} \vspace{-2mm} \subsection{Bias-Variance Trade-off} \vspace{-2mm} Following~\cite{pedro2000unified,valentini2004bias}, we define the optimal prediction, main prediction as well as the bias, variance and noise for any real-valued loss function $L(\cdot,\cdot)$ as follows: \begin{definition}({\bf Optimal Prediction and Main Prediction}) Given a loss function $L(\cdot, \cdot)$ and learning algorithm $f(\cdot)$, the optimal prediction $y_*$ and main prediction $y_m$ for an example are defined as follows: \begin{equation} y_*(x) = \arg\min_{y} \mathbb{E}_t[L(y,t)] \quad\mathrm{and}\quad y_m(x) = \arg\min_{y'} \mathbb{E}_{\mathcal{D}}[L(f_{\mathcal{D}}(x), y')] \end{equation} where $\mathcal{D}$ is the training set and $f_{\mathcal{D}}$ denotes the model trained using $\mathcal{D}$. In short, the main prediction is the prediction whose average loss relative to all the predictions over data distributions is minimum, e.g., the main prediction for zero-one loss is the mode of predictions. In this work, we show that the main prediction is the average prediction of client models for mean squared loss and cross-entropy loss in Section~\ref{BVD_gradients}. \end{definition} \begin{definition}({\bf Bias, Variance and Noise}) Given a loss function $L(\cdot, \cdot)$ and learning algorithm $f(\cdot)$, the expected loss $\mathbb{E}_{\mathcal{D},t}[L(f_{\mathcal{D}}(x), t)]$ for an example $x$ can be decomposed\footnote{This decomposition is based on the weighted sum of bias, variance, and noise.} into bias, variance and noise as follows: \begin{equation}\label{eq:bias_variance_noise} B(x) = L(y_m, y_*) \quad\mathrm{and}\quad V(x) = \mathbb{E}_{\mathcal{D}}[L(f_{\mathcal{D}}(x), y_m)] \quad\mathrm{and}\quad N(x) = \mathbb{E}_{t}[L(y_*, t)] \end{equation} \end{definition} In short, bias is the loss incurred by the main prediction w.r.t. the optimal prediction, and variance is the average loss incurred by predictions w.r.t. the main prediction. Noise is conventionally assumed to be irreducible and independent to $f(\cdot)$. \begin{remark} Our definitions on optimal prediction, main prediction, bias, variance and noise slightly differ from previous ones~\cite{pedro2000unified,valentini2004bias}. For example, conventional optimal prediction was defined as $y_*(x) = \arg\min_{y} \mathbb{E}_t[L(t, y)]$, and it is equivalent to our definition when loss function is symmetric over its arguments, i.e., $L(y_1, y_2) = L(y_2, y_1)$. But it does not hold for non-symmetric loss functions. \end{remark} \vspace{-2mm} \section{The Proposed Framework} \vspace{-2mm} A typical framework~\cite{kairouz2019advances} of privacy-preserving decentralized learning can be summarized as follows: (1) {\em Client Update:} Each client updates local model parameters $w_k$ by minimizing the empirical loss over its own training set; (2) {\em Forward Communication:} Each client uploads its model updates to the central server; (3) {\em Server Update:} It synchronously aggregates the received parameters; (4) {\em Backward Communication:} The global parameters are sent back to the clients. Our framework follows the same paradigm but with substantial modifications: {\bfseries Server Update}. Server has two components: The first component uses FedAvg~\cite{mcmahan2017communication} algorithm to aggregate the local models' parameters, i.e., $w_G = \mathrm{Aggregate}(w_1,w_2,\cdots,w_K) = \sum_{k=1}^K \frac{n_k}{n}w_k$ where $n = \sum_{k=1}^K n_k$ and $w_k$ is the model parameters in the $k^{\mathrm{th}}$ client. Meanwhile, another component is designed to produce adversarially perturbed examples which could be induced by a poisoning attack algorithm for the usage of robust adversarial training. It has been well studied~\cite{belkin2019reconciling,pedro2000unified,valentini2004bias} that in the classification setting, the generalization error of a learning algorithm on an example is determined by the irreducible noise, bias and variance terms as defined in Eq. (\ref{eq:bias_variance_noise}). Similar to the previous work, we also assume a noise free learning scenario where the class label $t$ is a deterministic function of $x$ (i.e., if $x$ is sampled repeatedly, the same values of its class $t$ will be observed). This motivates us to generate the adversarial examples by attacking the bias and variance terms induced by clients' models as: \begin{equation} \label{eq:maximization} \max_{\hat{x}\in\Omega(x)} B(\hat{x}; w_1,\cdots,w_K) + \lambda V(\hat{x}; w_1,\cdots,w_K) \quad \forall (x,t)\in \mathcal{D}_s \end{equation} where $B(\hat{x}; w_1,\cdots,w_K)$ and $V(\hat{x}; w_1,\cdots,w_K)$ could be empirically estimated from a finite number of local training sets $\{\mathcal{D}_1, \mathcal{D}_2, \cdots, \mathcal{D}_K\}$. Here $\lambda$ is a hyper-parameter to measure the trade-off of bias and variance, and $\Omega(x)$ is the perturbation constraint. Note that $\mathcal{D}_s$, which is on the server, is the candidate subset of all available training examples that would lead to their perturbed counterparts. This is a more feasible setting as compared to generating adversarial examples on clients' devices because the server usually has much powerful computational capacity in real scenarios that allows the usage of flexible poisoning attack algorithms. In this case, both poisoned examples and server model parameters would be sent back to each client ({\em Backward Communication}), while only clients' local parameters would be uploaded to the server ({\em Forward Communication}), i.e., the {\em asymmetrical communication} between the clients and the server as discussed in Section \ref{sec:problem_definition}. {\bfseries Client Update}. The robust training of one client's prediction model (i.e., $w_k$) can be formulated as the following minimization problem. \begin{equation} \label{eq:minimization} \min_{w_k} \left( \sum_{i=1}^{n_k} L(f_{\mathcal{D}_k}(x_i^k; w_k), t_i^k) + \sum_{j=1}^{n_s} L(f_{\mathcal{D}_k}(\hat{x}_j^s; w_k), t_j^s) \right) \end{equation} where $\hat{x}_j^s\in\Omega(x_j^s)$ is the perturbed counterpart of clean example $x_j^s$ asymmetrically transmitted from the server. \begin{remark} Intuitively, in the noise-free scenarios, bias measures the systematic loss of a learning algorithm, and variance measures the prediction consistency of the learner over different training sets. Therefore, our robust decentralized learning framework has the following advantages: (i) it encourages the clients to consistently produce the optimal prediction for perturbed examples, thereby leading to better generalization performance; (ii) local adversarial training on perturbed examples allows to learn a robust local model, and thus a robust global model could be aggregated from clients. \end{remark} Theoretically, we could still have another possible robust decentralized training strategy: \begin{equation}\label{eq:local_robsut} \min_{w_k} \sum_{i=1}^{n_k} \max_{\hat{x}_i^k\in\Omega(x_i^k)} L(f(\hat{x}_i^k; w_k), t_i^k) \quad \forall k \in \{1,2, \cdots, K\} \end{equation} where the local candidate set of available training examples for each client $k$ that can have their perturbation counterparts is $\mathcal{D}_k$. Following~\cite{madry2018towards,tramer2018ensemble}, one intuitive interpretation of this framework is considered as a composition of inner maximization and outer minimization problems. Specifically, the inner maximization problem aims to synthesize the adversarial counterparts of clean examples, while the outer minimization problem finds the optimal model parameters over perturbed training examples. In this way, each local robust model is trained individually and the global server model is aggregated from them. One major limitation of this method is that poisoning attacks on clients could largely increase the computational cost and memory usage. This might not be feasible due to the client's limited storage and computational capacity (e.g., a mobile device~\cite{hard2018federated}) in real scenarios. \vspace{-2mm} \section{Algorithm} \vspace{-2mm} \subsection{Bias-Variance Attack} \label{BVD_gradients} \vspace{-2mm} We first consider the maximization problem in Eq.~(\ref{eq:maximization}) using bias-variance based adversarial attacks. It aims to find the adversarial example $\hat{x}$ (from the original example $x$) that would produce large bias and variance values w.r.t. clients' local models. Specifically, perturbation constraint $\hat{x}\in \Omega(x)$ forces the adversarial example $\hat{x}$ to be visually indistinguishable w.r.t. $x$. Here we consider the well-studied $l_{\infty}$-bounded adversaries~\cite{goodfellow2014explaining,madry2018towards,tramer2018ensemble} such that $\Omega(x) := \{\hat{x} \big| ||\hat{x} - x||_{\infty} \leq \epsilon \}$ for a perturbation magnitude $\epsilon$. Furthermore, we propose to consider the following two gradient-based algorithms to generate adversarial examples with bounded $l_{\infty}$ norm. {\bf Bias-variance based Fast Gradient Sign Method (BV-FGSM):} Following FGSM~\cite{goodfellow2014explaining}, it linearizes the maximization problem in Eq. (\ref{eq:maximization}) with one-step attack as follows. \begin{equation}\label{BVD-FGSM} \hat{x}_{\mathrm{BV-FGSM}} := x + \epsilon \cdot \mathrm{sign}\left( \nabla_x \left(B(x; w_1,\cdots,w_K) + \lambda V(x; w_1,\cdots,w_K) \right) \right) \end{equation} {\bf Bias-variance based Projected Gradient Descent (BV-PGD):} PGD can be considered as a multi-step variant of FGSM~\cite{kurakin2016adversarial} and might generate powerful adversarial examples. This motivated us to derive a BV-based PGD attack: \begin{equation}\label{BVD-PGD} \hat{x}_{\mathrm{BV-PGD}}^{l+1} := \mathrm{Proj}_{\Omega(x)} \left( \hat{x}^l + \epsilon \cdot \mathrm{sign}\left( \nabla_{\hat{x}^l} \left(B(\hat{x}^l; w_1,\cdots,w_K) + \lambda V(\hat{x}^l; w_1,\cdots,w_K) \right) \right) \right) \end{equation} where $\hat{x}^l$ is the adversarial example at the $l^{\mathrm{th}}$ step with the initialization $\hat{x}^0 = x$ and $\mathrm{Proj}_{\Omega(x)}(\cdot)$ projects each step onto $\Omega(x)$. \begin{remark} The proposed framework could be naturally generalized to any gradient-based adversarial attack algorithms where the gradients of bias $B(\cdot)$ and variance $V(\cdot)$ w.r.t. $x$ are tractable when estimated from finite training sets. Compared with the existing attack methods~\cite{carlini2017towards,goodfellow2014explaining,kurakin2016adversarial,moosavi2016deepfool}, our loss function the adversary aims to optimize is a linear combination of bias and variance, whereas existing work largely focused on attacking the overall classification error that considers bias only. \end{remark} The following theorem states that bias $B(\cdot)$ and variance $V(\cdot)$ as well as their gradients over input $x$ could be estimated using the clients' models. \begin{theorem}\label{thm:empirical_estimation} Assume that $L(\cdot,\cdot)$ is the cross-entropy loss function, then the empirical estimated main prediction $y_m$ for an input example $(x,t)$ has the following closed-form expression: \begin{equation*} y_m(x; w_1,\cdots,w_K) = \frac{1}{K}\sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) \end{equation*} Furthermore, the empirical bias and variance as well as their gradients over input $x$ are estimated as: \begin{equation*} \begin{aligned} B(x; w_1,\cdots,w_K) = \frac{1}{K} \sum_{k=1}^K L(f_{\mathcal{D}_k}(x;w_k), t) &~~\mathrm{and}~~ V(x; w_1,\cdots,w_K) = L(y_m, y_m) = H(y_m) \\ \nabla_x B(x; w_1,\cdots,w_K) &= \frac{1}{K} \sum_{k=1}^K \nabla_x L(f_{\mathcal{D}_k}(x;w_k), t) \\ \nabla_x V(x; w_1,\cdots,w_K) &= - \frac{1}{K}\sum_{k=1}^K \sum_{j=1}^C (\log{y_m^{(j)}} + 1)\cdot \nabla_{x} f_{\mathcal{D}_k}^{(j)}(x;w_k) \end{aligned} \end{equation*} where $H(y_m) = -\sum_{j=1}^C y_m^{(j)}\log{y_m^{(j)}}$ is the entropy of the main prediction $y_m$ and $C$ is the number of classes. \end{theorem} In addition to the commonly used cross-entropy loss in neural networks, we also consider the case where $L(\cdot, \cdot)$ is the mean squared error (MSE) loss function. Then, the empirical estimated main prediction $y_m$ for an input example $(x,t)$ has the following closed-form expression: \begin{equation*} y_m(x; w_1,\cdots,w_K) = \frac{1}{K}\sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) \end{equation*} Furthermore, the empirical bias and unbiased variance are estimated as: \begin{equation*} \begin{aligned} B(x; w_1,\cdots,w_K) &= ||\frac{1}{K} \sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k) - t||_2^2 \\ V(x; w_1,\cdots,w_K) &= \frac{1}{K-1} \sum_{k=1}^K ||f_{\mathcal{D}_k}(x;w_k) - \frac{1}{K} \sum_{k=1}^K f_{\mathcal{D}_k}(x; w_k)||_2^2 \end{aligned} \end{equation*} \begin{remark} In this paper, we focus on studying the robust decentralized learning problem using neural network model with cross-entropy loss function. Notice that in our framework, the decentralized training of neural networks with MSE loss function might have weaker robustness and higher computational complexity compared to cross-entropy loss function (see Appendix~\ref{sec:mse_ce}). \end{remark} \vspace{-2mm} \subsection{{{Decent\_BVA}}} \vspace{-2mm} We present a novel robust \underline{decent}ralized learning algorithm with our proposed \underline{b}ias-\underline{v}ariance \underline{a}ttacks, named \textit{{{Decent\_BVA}}}. Following the framework in Eq.~(\ref{eq:maximization}) and Eq.~(\ref{eq:minimization}), key components to our \begin{minipage}{0.46\textwidth} \begin{algorithm}[H] \centering \caption{{{Decent\_BVA}}}\label{algorithm:RobustFed} \begin{algorithmic}[1] \STATE {\bfseries Input:} $K$ (number of clients, with local data sets $\{\mathcal{D}_k\}_{k=1}^K$ indexed by $k$); $f$ (learning model), $E$ (number of local epochs); $F$ (fraction of clients selected on each round); $B$ (batch size of local client); $\eta$ (learning rate); $\mathcal{D}_{s}$ (data set on server); $\epsilon$ (perturbation magnitude). \STATE {\bfseries Initialization:} Initialize $w_G^0$ and $\hat{\mathcal{D}}_s = \emptyset$ \FOR{each round $r=1,2,\cdots$} \STATE $m=\max(F\cdot K, 1)$ \STATE $S_r \leftarrow$ randomly sampled $m$ clients \FOR{each client $k\in S_r$ in parallel} \STATE $w^{r}_k \leftarrow$ {\bfseries ClientUpdate}($w_G^{r-1}, \hat{\mathcal{D}}_s, k$) \ENDFOR \STATE $\hat{\mathcal{D}}_s \leftarrow$ {\bfseries BVAttack}($\mathcal{D}_s, \{w_{k}^{r}\} | k\in S_r$) \STATE $w_G^r \leftarrow$ {\bfseries Aggregate}($w_{k}^{r} | k\in S_r$) \ENDFOR \RETURN $w_G$ \end{algorithmic} \end{algorithm} \end{minipage} \hfill \begin{minipage}{0.52\textwidth} \begin{algorithm}[H] \centering \caption{ClientUpdate({$w, \hat{\mathcal{D}}_s, k$})}\label{ClientUpdate} \begin{algorithmic}[1] \STATE Initialize $k^{\mathrm{th}}$ client's model with $w$ \STATE $\mathcal{B} \leftarrow$ split $\mathcal{D}_k \cup \hat{\mathcal{D}}_s$ into batches of size $B$ \FOR{each local epoch $i=1,2,\cdots,E$} \FOR{local batch $(x, t) \in \mathcal{B}$} \STATE $w \leftarrow w - \eta \nabla L(f_{\mathcal{D}_k}(x; w), t)$ \ENDFOR \ENDFOR \RETURN $w$ \end{algorithmic} \end{algorithm} \vspace{-6mm} \begin{algorithm}[H] \centering \caption{BVAttack({$\mathcal{D}_s, \{w_{k}^{r}\} | k\in S_r$})}\label{BVDAttack} \begin{algorithmic}[1] \STATE Initialize $\hat{\mathcal{D}}_s = \emptyset$ \FOR{$(x, t) \in \mathcal{D}_s$} \STATE Estimate the gradients $\nabla_x B(x)$ and $\nabla_x V(x)$ using Theorem \ref{thm:empirical_estimation} \STATE Calculate $\hat{x}$ using Eq. (\ref{BVD-FGSM}) or (\ref{BVD-PGD}) and add to $\hat{\mathcal{D}}_s$ \ENDFOR \RETURN $\hat{\mathcal{D}}_s$ \end{algorithmic} \end{algorithm} \end{minipage} algorithm are: bias-variance attacks for generating adversarial examples on the server, and adversarial training with poisoned server examples and clean local examples on each client. Therefore, a robust decentralized learning model could be optimized by iteratively updating the adversarial examples and local model parameters. The proposed algorithm is summarized in Alg.~\ref{algorithm:RobustFed}. It is given the server's $\mathcal{D}_{s}$ and clients' training data $\{\mathcal{D}_k\}_{k=1}^K$ as input, and outputs a robust global model on the server. To begin with, it initializes the server's model parameter $w_G$ and perturbed data $\hat{\mathcal{D}}_s$, and then assigns to the randomly selected clients (Steps 4-5). Each client optimizes its own local model with the received parameters $w$ and $\hat{\mathcal{D}}_s$ (Steps 6-8), and then uploads the updated parameters back to the server. Then, the server updates the perturbed data $\hat{\mathcal{D}}_s$ (Step 9) using our proposed bias-variance attack algorithm (see Alg.~\ref{BVDAttack}) and global model parameters (Step 10) using an aggregation method, e.g., FedAvg~\cite{mcmahan2017communication}. Specifically, for client update (see Alg.~\ref{ClientUpdate}), each client initializes its local model $f_{\mathcal{D}}(\cdot)$ with the received global parameters $w_G$, and then optimizes the local model with its own clean data $\mathcal{D}_k$ and the received data $\hat{\mathcal{D}}_s$. Following~\cite{mcmahan2017communication,xie2019dba}, considering the neural network model $f(\cdot)$, we use Stochastic Gradient Descent (SGD) to train $E$ epochs with local learning rate $\eta$ and batch size $B$ in each client. \vspace{-2mm} \section{Experiments} \vspace{-2mm} In this section, we evaluate the adversarial robustness of our proposed algorithm on three benchmark data sets: MNIST\footnote{\scriptsize \url{http://yann.lecun.com/exdb/mnist}}, Fashion-MNIST\footnote{\scriptsize \url{https://github.com/zalandoresearch/fashion-mnist}}, CIFAR-10\footnote{\scriptsize \url{https://www.cs.toronto.edu/~kriz/cifar.html}}. \begin{figure}[!t] \begin{minipage}[c][11cm][t]{.49\textwidth} \centering \includegraphics[width=6cm,height=4cm]{figures/BVD_gradients_2.png} \vspace{-2mm} \caption{\small Visualizations of bias, variance, bias+variance, and perturbed images for MNIST.} \label{fig_visual_bvd} \end{minipage}% \hfill \begin{minipage}[c][11cm][t]{.49\textwidth} \centering \includegraphics[width=5.5cm,height=4cm]{figures/bias_variance_CNN_MNIST.png} \vspace{-2mm} \caption{\small Bias-variance curve w.r.t. the CNN model complexity on MNIST.} \label{curve_bvd_cnn} \end{minipage} \vspace{-66mm} \end{figure} \vspace{-2mm} \subsection{Baselines} \vspace{-2mm} The baseline models we use include: (1). \textit{FedAvg}: the classical federated averaging model~\cite{mcmahan2017communication}. (2). \textit{Decent\_Baseline}: The simplified version of our proposed method where the local clients are robustly trained using~\cite{madry2018towards} but the asymmetrical transmitted perturbed data are generated using the gradients from FedAvg's aggregation on the server. (3)-(5). \textit{Decent\_Bias, Decent\_Variance, Decent\_BVA}: Our proposed methods, similar to \textit{Decent\_Baseline} but the asymmetrical transmitted perturbed data is generated using the gradients from bias-only attack, variance-only attack, and bias-variance attack respectively. (6). \textit{FedAvg\_Robust\_Local}: Each client performs its own adversarial training using Eq.~(\ref{eq:local_robsut}); then, their model updates are aggregated on the server using \textit{FedAvg}. (7). \textit{Decent\_BVA\_Local}: A combination of baselines (5) and (6). Note that the latter two baselines have high computational requirements on client devices and may not be applicable in real scenarios. \begin{figure}[!t] \hspace{-2mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=5cm,height=4cm]{figures/fashionMNIST_plot1.png} \vspace{-6mm} \caption{Convergence on Fashion-MNIST} \label{fig_convergence_fashion} \end{minipage}% \hfill \hspace{3mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=5cm,height=4cm]{figures/fashionMNIST_plot2.png} \vspace{-6mm} \caption{Performance on Fashion-MNIST} \label{fig_performance_fashion} \end{minipage} \hfill \hspace{2mm} \begin{minipage}[c][11cm][t]{.3\textwidth} \centering \includegraphics[width=4cm,height=4cm]{figures/fashionMNIST_plot3.png} \vspace{-2.5mm} \caption{Efficiency on Fashion-MNIST} \label{fig_efficiency_fashion} \end{minipage} \vspace{-67mm} \end{figure} \vspace{-2mm} \subsection{Setting} \vspace{-2mm} Regarding the defense model architecture, we use 4-layer CNNs (2 convolutional layers and 2 fully connected layers) for MNIST and Fashion-MNIST. For CIFAR-10, a 9-layer CNN (6 convolutional layers and 3 fully connected layers) model is used. The detailed designs are illustrated in the Appendix. The training is performed using SGD optimizer with fixed learning rate of $0.01$ and momentum of value $0.9$. Total number of clients is 100 and the fraction of clients that are sampled to perform training is set as $F=0.1$; the asymmetrically transmitted data is randomly sampled and has the size of $n_s=64$; the local batch size $B$ of each client is $64$, and the local training epochs $E$ of each client are $50, 50, 10$ for the three data sets respectively. We empirically demonstrate that these hyper-parameter settings are preferable in terms of both training accuracy and robustness. Please see the details in Fig.~\ref{fig_num_share1} - Fig.~\ref{fig_localEpoch3} in the Appendix. For the adversarial training of the clients, the perturbed examples are generated by poisoning the training set using our proposed BV-FGSM attack algorithm. To evaluate the robustness of our decentralized learning algorithm against existing adversarial attacks, except for the clean model training, we perform FGSM~\cite{goodfellow2014explaining}, 10-step PGD~\cite{kurakin2016adversarial}, and 20-step PGD~\cite{kurakin2016adversarial} towards the aggregated server model on the test set $\mathcal{D}_{test}$. Following~\cite{goodfellow2014explaining, defense_quanquangu}, the maximum perturbations allowed are $\epsilon=0.3$ for MNIST and Fashion-MNIST, and $\epsilon=\frac{8}{255}$ for CIFAR-10. For IID sampling, the data is first shuffled and partitioned into 100 parts for 100 clients respectively; For non-IID setting, data is divided into 200 shards based on sorted example labels, then assigns each client with 2 shards. In such case, each client will have data with at most two classes. \vspace{-2mm} \subsection{Result Analysis} \vspace{-2mm} To analyze the properties of our proposed \textit{{{Decent\_BVA}}} framework, in Fig.~\ref{fig_visual_bvd}, we first visualize the extracted gradients using bias attack, variance attack, and bias-variance attack. Notice that the gradients of bias and variance are similar but with subtle differences in local pixel areas. However, according to Theorem~\ref{thm:empirical_estimation}, the gradient calculation of these two are quite different: bias requires the target label as input, but variance only needs the model output and main prediction. From another perspective, we also investigate the bias-variance magnitude relationship with varying model complexity. As shown in Fig.~\ref{curve_bvd_cnn}, with increasing model complexity (more convolutional filters in CNN), both bias and variance decrease. This result is different from the double-descent curve or bell-shape variance curve claimed in ~\cite{belkin2019reconciling, yang2020rethinking}. The reasons are twofold: First, their bias-variance definitions are from the MSE regression decomposition perspective, whereas our decomposition utilizes the concept of main prediction and the generalization error is decomposed from the classification perspective; Second, their implementations only evaluate the bias and variance using training batches on one central model and thus is different from the definition which requires the variance to be estimated from multiple sub-models (in our scenario, client models). The convergence plot of all baseline methods is presented in Fig.~\ref{fig_convergence_fashion}. We observe that \textit{FedAvg} has the best convergence, and all robust training will have a slightly higher loss upon convergence. This matches the observations in~\cite{madry2018towards} which states that training performance may be sacrificed in order to provide robustness for small capacity networks. As for the robustness performance shown in Fig.~\ref{fig_performance_fashion}, we observe that the aggregation of decentralized learning is vulnerable to adversarial attacks since both \textit{FedAvg} and \textit{FedAvg\_Robust\_Local} have decreased performance with an increasing number of server-client communications. Other baselines that utilized the asymmetrical communications have increasing robustness with more communication rounds although only a small number of perturbed examples ($n_s=64$) are transmitted. We also observe that when communication rounds reach 70, \textit{{{Decent\_BVA}}} starts to have similar performance as \textit{FedAvg\_Robust\_Local} while the latter is more resource-demanding as shown in Fig.~\ref{fig_efficiency_fashion}, where the pie plot size represents the running time. Overall, asymmetrical communications with perturbations increase model robustness and bias-variance based adversarial training is more effective for decentralized learning. For the comprehensive experiments shown in Table~\ref{tableResults:MNIST-IID-NONIID}, it is easy to verify that our proposed model outperforms all other baselines regardless of the source of the perturbed examples (i.e., locally generated like \textit{FedAvg\_Robust\_Local} or asymmetrically transmitted from the server like \textit{{{Decent\_BVA}}}). Comparing with standard robust decentralized training \textit{Decent\_Baseline}, the performance of \textit{{{Decent\_BVA}}} against adversarial attacks still increases $4\% - 15\%$ and $10\% - 16\%$ on IID and non-IID settings respectively, although \textit{{{Decent\_BVA}}} is theoretically suitable for the cases that clients have IID samples. In Table~\ref{tableResults:Fashion-CIFAR}, we observe a similar trend where \textit{{{Decent\_BVA}}} outperforms \textit{Decent\_Baseline} on FashionMNIST (with $0.3\% - 5\%$ increases) and on CIFAR-10 (with $0.2\% - 0.4\%$ increases) when defending different types of adversarial examples. For results that use local adversarial training, we only see comparable results. Our conjecture is that local adversarial training is already able to generate high-quality perturbed examples and adding more similar ones from asymmetrical communication would not have much space for improving the model robustness. \begin{table}[!t] \centering \setlength\tabcolsep{2.9pt} \scalebox{0.9}{ \begin{tabular}{lccccccccc} \hline \multirow{2}{*}{} & \multicolumn{4}{c}{IID} & & \multicolumn{4}{c}{non-IID} \\ \cline{2-5} \cline{7-10} & Clean & FGSM & PGD-10 & PGD-20 & & Clean & FGSM & PGD-10 & PGD-20 \\ \hline FedAvg & \bf \underline{0.9863} & 0.5875 & 0.6203 & 0.2048 & & 0.9462 & 0.1472 & 0.5254 & 0.0894 \\ Decent\_Baseline & 0.9849 & 0.7374 & 0.7145 & 0.4158 & & 0.9596 & 0.5630 & 0.5948 & 0.3149 \\ Decent\_Bias & 0.9840 & 0.7627 & 0.7671 & 0.5154 & & 0.9597 & 0.6510 & 0.6226 & 0.3614 \\ Decent\_Variance & 0.9834 & 0.7594 & 0.7616 & 0.5253 & & 0.9577 & 0.5979 & 0.5990 & 0.3504 \\ Decent\_BVA & 0.9837 & \underline{0.7756} & \underline{0.7927} & \underline{0.5699} & & \bf \underline{0.9671} & \underline{0.6696} & \underline{0.6953} & \underline{0.4717} \\ \hline FedAvg\_Robust\_Local & 0.9747 & 0.9028 & 0.9268 & 0.8595 & & 0.9265 & 0.7695 & 0.8435 & 0.7422 \\ Decent\_BVA\_Local & 0.9739 & \bf 0.9185 & \bf 0.9329 & \bf 0.8874 & & 0.9543 & \bf 0.8059 & \bf0.8582 & \bf0.7447 \\ \hline \end{tabular}} \caption{Adversarial robustness on MNIST with IID and non-IID settings} \label{tableResults:MNIST-IID-NONIID} \vspace{-5mm} \end{table} \begin{table}[!t] \centering \setlength\tabcolsep{2.9pt} \scalebox{0.9}{ \begin{tabular}{lccccccccc} \hline \multirow{2}{*}{} & \multicolumn{4}{c}{Fashion-MNIST} & & \multicolumn{4}{c}{CIFAR-10} \\ \cline{2-5} \cline{7-10} & Clean & FGSM & PGD-10 & PGD-20 & & Clean & FGSM & PGD-10 & PGD-20 \\ \hline FedAvg & \bf \underline{0.8785} & 0.2971 & 0.0406 & 0.0188 & &\bf \underline{0.7887} & 0.1477 & 0.0337 & 0.0254 \\ Decent\_Baseline & 0.8628 & 0.5029 & 0.1977 & 0.1628 & & 0.7793 & 0.2079 & 0.0866 & 0.0753 \\ Decent\_Bias & 0.8655 & 0.5407 & 0.1934 & 0.1689 & & 0.7760 & 0.2043 & \underline{0.0894} & 0.0769 \\ Decent\_Variance & 0.8617 & 0.5334 & 0.1935 & 0.1628 & & 0.7810 & 0.1969 & 0.0799 & 0.0693 \\ Decent\_BVA & 0.8597 & \underline{0.5506} & \underline{0.2002} & \underline{0.1799} & & 0.7812 & \underline{0.2119} & 0.0890 & \underline{0.0771} \\ \hline FedAvg\_Robust\_Local & 0.8542 & \bf 0.7424 & 0.2880 & 0.1692 & & 0.7672 &0.2796 & 0.1929 & \bf 0.1892 \\ Decent\_BVA\_Local & 0.8358 & 0.7163 & \bf0.3973 & \bf0.2626 & & 0.7676 &\bf 0.2803 &\bf 0.1935 &\bf 0.1892 \\ \hline \end{tabular} } \caption{Adversarial robustness on Fashion-MNIST and CIFAR-10} \label{tableResults:Fashion-CIFAR} \vspace{-8mm} \end{table} \vspace{-2mm} \section{Related Work} \vspace{-2mm} {\bf Adversarial Machine Learning:} While machine learning models have achieved remarkable performance over clean inputs, recent work~\cite{goodfellow2014explaining,szegedy2014intriguing} showed that those trained models are vulnerable to adversarially chosen examples by adding the imperceptive noise to the clean inputs. In general, the adversarial robustness of centralized machine learning models have been explored from the following aspects: adversarial attacks~\cite{biggio2012poisoning,mei2015using,carlini2017towards,shafahi2018poison,guo2019simple,athalye2018synthesizing,zhu2019transferable}, defense (or robust model training)~\cite{madry2018towards,tramer2018ensemble,wong2018provable,cohen2019certified,shafahi2019adversarial,tramer2019adversarial} and interpretable adversarial robustness~\cite{schmidt2018adversarially,cullina2018pac,gilmer2019adversarial,yin2019rademacher,tsipras2018robustness}. {\bf Decentralized Learning:} Decentralized learning with preserved privacy~\cite{konevcny2016federated,mcmahan2017communication,hard2018federated} has become prevalent in recent years. Meanwhile, the vulnerability of decentralized learning to backdoor attacks has also been explored by~\cite{bagdasaryan2018backdoor,bhagoji2019analyzing,xie2019dba}. Following their work, multiple robust decentralized learning models~\cite{robust_fed_localPoisoning, robust_agg_fed, robust_fed_weightTruncate, robust_fed_hyperParameter} are also proposed and studied. In this paper, we studied the underlying true cause of decentralized learning's vulnerability from the perspective of bias-variance analysis. This is in sharp contrast to the existing work that focused on performing client-level model poisoning attacks or designing server-level aggregation variants with hyper-parameter tuning. {\bf Bias-Variance Decomposition:} Bias-Variance Decomposition (BVD)~\cite{geman1992neural} was originally introduced to analyze the generalization error of a learning algorithm. Then a generalized BVD \cite{pedro2000unified,valentini2004bias} was studied in the classification setting which enabled flexible loss functions (e.g., squared loss, zero-one loss). More recently, bias-variance trade-off was experimentally evaluated on modern neural network models~\cite{neal2018modern,belkin2019reconciling,yang2020rethinking}. \vspace{-2mm} \section{Conclusion} \vspace{-2mm} In this paper, we proposed a novel framework for robust decentralized learning, where the loss incurred during the server's aggregation stage is dissected into a bias part and a variance part. Our approach improves the model robustness through adversarial training by letting the server share a few perturbed samples to the clients via asymmetrical communications. Extensive experiments have been conducted where we evaluated its performance from various aspects on a few benchmark data sets. We believe the further exploration of this direction will lead to more findings on the robustness of decentralized learning. \newpage \section*{Broader Impact} In this paper, researchers introduce \textit{{{Decent\_BVA}}}, a decentralized learning approach that learns a shared prediction model that is robust against corrupted data collected from the client devices. \textit{{{Decent\_BVA}}} could be applied to multiple types of real-life applications, including but not limited to internet of things, telecommunications, medical diagnosis, etc. In these domains, the new trend of research is collaboratively speeding up the model development with improved personalized features while preserving user privacy via decentralized learning. Our research could be used to enhance the robustness of these applications, avoiding the systematic collapse of the central model due to a few local compromised client devices. We envision future research to continue along the direction of understanding the bias and variance incurred in the decentralized aggregation stage of model learning, especially their influences on user experience and privacy protection. \bibliographystyle{plain}
{'timestamp': '2020-09-22T02:01:39', 'yymm': '2009', 'arxiv_id': '2009.09026', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09026'}
arxiv
\section{Introduction} \label{sec:intro} \input{sections/intro} \section{The SpiNNaker 2 Prototype Chip} \label{sec:hardware} \input{sections/hardware} \section{Benchmark Models} \label{sec:benchmarks} \input{sections/benchmark_models} \section{Implementation of the Benchmarks on the SpiNNaker 2 Prototype} \label{sec:software} \input{sections/software_implementation} \section{Results} \label{sec:results} \input{sections/results} \section{Discussion} \label{sec:discussion} \input{sections/discussion} \section{Conclusion} \input{sections/conclusion} \bibliographystyle{IEEEtran} \section*{Supplement}% \setcounter{table}{0} \renewcommand{\thetable}{S\arabic{table}}% \setcounter{figure}{0} \renewcommand{\thefigure}{S\arabic{figure}}% } \newcommand{\frac{\partial}{\partial t}}{\frac{\partial}{\partial t}} \newcommand{\frac{\partial}{\partial \theta_i}}{\frac{\partial}{\partial \theta_i}} \newcommand{\frac{\partial}{\partial \theta_{ki}}}{\frac{\partial}{\partial \theta_{ki}}} \newcommand{\frac{\partial}{\partial w_i}}{\frac{\partial}{\partial w_i}} \newcommand{\frac{\partial^2}{\partial \theta_{i}^2}}{\frac{\partial^2}{\partial \theta_{i}^2}} \newcommand{\frac{\partial^2}{\partial \theta_{ki}^2}}{\frac{\partial^2}{\partial \theta_{ki}^2}} \newcommand{\dd}[1]{\frac{\partial}{\partial #1}} \newcommand{\syn}[1]{\text{\textsc{syn}}_{#1}} \newcommand{\text{\tiny{\textsc{pre}}}_{i}}{\text{\tiny{\textsc{pre}}}_{i}} \newcommand{\text{\tiny{\textsc{post}}}_{i}}{\text{\tiny{\textsc{post}}}_{i}} \newcommand{\text{\textsc{pre}}_{i}}{\text{\textsc{pre}}_{i}} \newcommand{\text{\textsc{post}}_{i}}{\text{\textsc{post}}_{i}} \newcommand{\pl}[1]{{(\bf\MakeLowercase{#1})}} \newcommand{\pr}[1]{{\bf\MakeLowercase{#1}}} \newcommand{\figref}[2][]{{Fig.~\ref{#2}\MakeLowercase{#1}}} \newcommand{z_{\posti}}{z_{\text{\tiny{\textsc{post}}}_{i}}} \newcommand{\zk(t)}{z_{\posti}(t)} \newcommand{\zk(s)}{z_{\posti}(s)} \newcommand{\zk(\tau)}{z_{\posti}(\tau)} \newcommand{f_{\posti}}{f_{\text{\tiny{\textsc{post}}}_{i}}} \newcommand{\fk(t)}{f_{\posti}(t)} \newcommand{\fk(s)}{f_{\posti}(s)} \newcommand{\fk(\tau)}{f_{\posti}(\tau)} \newcommand{r(t)}{r(t)} \newcommand{r(\tau)}{r(\tau)} \newcommand{\hat{r}(t)}{\hat{r}(t)} \newcommand{\ve r}{\ve r} \newcommand{\rbin}{v_{b}} \newcommand{y}{y} \newcommand{\hat{x}}{\hat{x}} \newcommand{\boldsymbol{z}}{\boldsymbol{z}} \newcommand{\mathbf{z}}{\mathbf{z}} \newcommand{\mathbf{z}(t)}{\mathbf{z}(t)} \newcommand{\mathbf{z}_{s:t}}{\mathbf{z}_{s:t}} \newcommand{\mathbf{z}(\tau)}{\mathbf{z}(\tau)} \newcommand{\mathbf{S}}{\mathbf{S}} \newcommand{\mathbf{r}}{\mathbf{r}} \newcommand{\boldsymbol{x}}{\boldsymbol{x}} \newcommand{\mathbf{X}}{\mathbf{X}} \newcommand{\ve \theta}{\ve \theta} \newcommand{\ve \theta(t)}{\ve \theta(t)} \newcommand{\theta_i(t)}{\theta_i(t)} \newcommand{\mathcal{Z}}{\mathcal{Z}} \newcommand{\bbr, \bbs,\bbx, \bbz}{\mathbf{r}, \mathbf{S},\mathbf{X}, \mathbf{z}} \newcommand{R,\bbz}{R,\mathbf{z}} \newcommand{\sum_{r^t, \bbs^t,\bbx^t, \bbz^t}}{\sum_{r^t, \mathbf{S}^t,\mathbf{X}^t, \mathbf{z}^t}} \newcommand{\pn}[2]{p_{\mathcal{N}}\left({#1}\,\middle\vert\,{#2}\right)} \newcommand{\pe}[2]{p_{\mathcal{E}}\left({#1}\,\middle\vert\,{#2}\right)} \newcommand{\ps}[1]{p_{\mathcal{S}}\left({#1}\right)} \subsection{Comparison with SpiNNaker 1} We assume that the same benchmarks in this work could also be implemented on SpiNNaker 1. However, since in SpiNNaker 1 there is no MAC array, the vector-matrix multiplication would be much slower and therefore consume much more energy than the SpiNNaker 2 prototype. Fig. \ref{fig:encoding2} indicates the speedup in terms of number of clock cycles for the vector-matrix multiplication in the SpiNNaker 2 prototype compared to what it would be in SpiNNaker 1. The differences in fabrication technology and supply voltage etc. further increases the difference between the SpiNNaker 2 prototype and SpiNNaker 1. \subsection{Comparison with other neuromorphic platforms} To ease the discussion, we group neuromorphic platforms into 3 categories: 1. Neuromorphic platforms with static synapses, such as TrueNorth \cite{Merolla668}, NeuroGrid \cite{neurogrid}, Braindrop \cite{braindrop}, HiAER-IFAT \cite{park2017hierarchical}, DYNAPs \cite{dynaps18}, Tianjic \cite{tianjic}, NeuroSoC \cite{bionect20} and DeepSouth \cite{deepsouth18}, 2. Neuromorphic platforms with configurable (but not programmable) plasticity, such as ROLLS \cite{rolls15}, ODIN \cite{odin19} and TITAN \cite{titan16}, 3. Neuromorphic platforms with programmable plasticity, such as (except SpiNNaker 1/2 and Loihi) the BrainScales~1/2 system\cite{PPU,hartmann2010highly}. We assume all 3 groups of neuromorphic platforms should be able to implement the keyword spotting benchmark in this work. However, DNNs can not be directly implemented on these platforms since they only support SNNs (except Tianjic, which also supports DNNs). Solutions similar to the SNN version implemented on Loihi would be an option. For adaptive control, since learning is involved, we assume the neuromorphic platforms in group 1 can not support this benchmark. It would be still possible to have an external host PC to reprogram the synaptic weights, but that would not be suitable for embedded applications. Although the learning rule in adaptive control is relatively simple, it involves multiplying an external error signal with the activity of the presynaptic neuron in every time step, which is quite different from the learning rules normally supported in the neuromorphic community, like Spike-Timing Dependent Plasticity (STDP) \cite{Markram213} or Spike-Driven Synaptic Plasticity (SDSP) \cite{brader07}. Therefore we assume the neuromorphic platforms in group 2 could not implement the adaptive control benchmark. The BrainScales~2 system in group 3 comes with programmable plasticity, but since the neural network runs in accelerated time, it is unclear whether the neural activity of each time step can be used for the weight update. Also it is unclear how to interface robotic applications which require real time response with a neural network running in accelerated time. \subsection{Keyword Spotting}\label{result_keyword_spotting} \subsubsection{Memory Footprint}\label{result_keyword_spotting_memory} For the keyword spotting benchmark, the required SRAM memory mainly consists of 2 parts: weight memory and neuron input memory. The weight memory is the memory for storing the weights and biases, which are quantized as 8-bit integers. The required memory in bytes is \begin{equation} M_{w} \;=\; (D + 1) N \label{eq:M_w} \end{equation} where \(D\) is the number of input dimensions, \(N\) is the number of neurons. The neuron input memory is the memory for storing the results from the MAC array after the vector-matrix multiplication is complete. Each input is a 32 bit integer. The required memory in bytes is \begin{equation} M_{i} \;=\; 4N \label{eq:M_ic_kw} \end{equation} Since the ReLU unit doesn't need to hold its output value between inferences, which is the case for the LIF neuron model, there is no neuron memory needed. The total memory for a neural network on a PE is \begin{equation} M_{total} \;=\; M_{w}+M_{i} \label{eq:M_total_kw} \end{equation} Based on Eq. (\ref{eq:M_w}), (\ref{eq:M_ic_kw}), (\ref{eq:M_total_kw}) for memory footprint, the first hidden layer of the keyword spotting network would require ca. 100 KBytes of memory. For each PE, in total 128 KBytes of SRAM memory is available, which is used for the program code as well as the program data. In this work, it is assumed that each PE has 90 KBytes of SRAM memory available for the data of the neural network. So the first hidden layer is split into two PEs. \subsubsection{Computation Time and Comparison with Loihi}\label{result_keyword_spotting_time} In the keyword spotting benchmark, the computation times for the vector-matrix multiplication (\(T_{mm}\)) and the ReLU update (\(T_{relu}\)) are measured. After the measurement, polynomial models can be fitted by minimizing the mean-squared error. The number of clock cycles for the vector-matrix multiplication with the MAC array is found to be \begin{align} T_{mm} \;=\; 74.0 + 5.38 N \nonumber \\ + 0.13 N D + 24.0 D \label{eq:c_mm} \end{align} where \(N\) is the number of neurons and \(D\) is the number of input dimensions. The time for the vector-matrix multiplication is mostly reflected in \(0.13 N D\). Before the vector-matrix multiplication starts, the inputs to the network needs to be prepared for the MAC array. This pre-processing step is mostly reflected in \(24.0 D\). After the vector-matrix multiplication, a post-processing step is necessary for the resulting neuron input current. The computation time depends on both \(D\) and \(N\), and this is reflected in \(24.0 D\) and \(5.38 N\). For each of the computational steps, there is a constant overhead, which is reflected in the constant \(74.0\). The computation time for ReLU update with ARM core is found to be \begin{align} T_{relu} \;=\; 17.70 N + 117.5 \label{eq:c_relu_neuron_update} \end{align} The total time is \begin{align} T_{total} \;=\; T_{mm} + T_{relu} \label{eq:c_kw_total} \end{align} Based on Eq. (\ref{eq:c_mm}), (\ref{eq:c_relu_neuron_update}), (\ref{eq:c_kw_total}) for computation time, with the keyword spotting network split into 3 PEs (Fig. \ref{fig:keywordspotting_impl}), the computation of one time step consumes less than 21k clock cycles. With a safety margin of 4k clock cycles, one time step would take less than 25k clock cycles. When the PE is running with 250 MHz, this means the duration of one time step can be reduced to 0.1 ms. Since 10 time steps are combined to 1 time window to form one inference, a time step duration of 0.1 ms would correspond to 1000 inferences per second. In \cite{keyword_spotting_loihi19}, 296 inferences per second has been reported for Loihi. One reason for the reduced speed of Loihi might be that the inputs to the neural network are coming from an FPGA which could cause some latency, while the SpiNNaker 2 prototype is using inputs generated by one of the PEs of the same chip. \subsubsection{Energy Measurement and Comparison with Loihi}\label{result_keyword_spotting_power} Both QPEs are used for the measurement. In each QPE, 3 PEs are switched on to simulate a keyword spotting network. The measured result is then divided by 2 to obtain the energy per network. The energy is measured incrementally, similar to previous measurements on SpiNNaker 1 \cite{spinn1power} and on the first SpiNNaker 2 prototype \cite{hoeppner19tcas}. The idle energy is measured when in each time step the timer tick interrupt is handled but nothing is processed. The result we present in this section is the active energy which is obtained by subtracting the idle energy from the total energy. The resulting active energy per inference is 7.1 \(\mu\)J. The keyword spotting network is implemented as a normal DNN on the SpiNNaker 2 prototype. The MAC array is used for the computation of the connection matrix, and the ARM core is used for the computation of ReLU activation function. Since Loihi only supports SNN, the spiking version of the keyword spotting network is implemented on Loihi. This could be the reason that the SpiNNaker 2 prototype consumes less energy for each inference in the keyword spotting benchmark (Tab. \ref{tab:keyword_spotting}). Note that in \cite{keyword_spotting_loihi19}, the reported energy per inference on Loihi was 270 \(\mu\)J, including a 70 mW overhead presumably caused by the x86 processor on Loihi. In this work the overhead has been removed which results in 37 \(\mu\)J per inference. \begin{table}[htb] \begin{minipage}{0.47\textwidth} \centering \renewcommand{\arraystretch}{1.1} \caption{Comparison of the SpiNNaker 2 prototype (SpiNN) and Loihi for the keyword spotting task } \label{tab:keyword_spotting} \centering \footnotesize \begin{tabular}{lcc} \toprule Hardware & inference/sec & energy/inference (\(\mu\)J)\\ \midrule SpiNN & 1000 & 7.1 \\ Loihi & 296 & 37 \\ \bottomrule \end{tabular} \end{minipage} \end{table} \subsection{Adaptive Control}\label{result_adaptive_control} \subsubsection{Memory Footprint}\label{result_adaptive_control_memory} For an adaptive control network simulated on a PE, the required SRAM memory mainly consists of 4 parts: input weight matrix and bias memory, output weight matrix memory, neuron input current memory and neuron memory. The input weight matrix and bias memory is the memory for storing the input weight matrix and bias, which are quantized as 8-bit integers. The required memory in bytes is \begin{equation} M_{ib} \;=\; (D_{in} + 1) N \label{eq:M_e-b} \end{equation} where \(D_{in}\) is the number of input dimensions, \(N\) is the number of neurons. The output weight matrix memory is the memory for storing the output weight matrix, which are 16 bit floating point numbers. The required memory in bytes is \begin{equation} M_{o} \;=\; 2D_{out} N \label{eq:M_d} \end{equation} where \(D_{out}\) is the number of output dimensions. The neuron input current memory is the memory for storing the results from the MAC array after the input processing is complete. Each input current is a 32 bit integer. The required memory in bytes is \begin{equation} M_{ic} \;=\; 4N \label{eq:M_ic} \end{equation} The neuron memory is the memory to hold the LIF neuron parameters like the membrane potential and refractory time. Each of them has 32 bits. The required memory in bytes is \begin{equation} M_{n} \;=\; 8N \label{eq:M_n} \end{equation} The total memory for a neural network on a PE is \begin{equation} M_{total} \;=\; M_{ib} + M_{o} + M_{ic} + M_{n} \label{eq:M_total} \end{equation} Since it is assumed that each PE has 90 KBytes of SRAM memory available for the data of the neural network, the maximum number of output dimensions given the number of input dimensions and number of neurons in a neural network can be derived with Eq. (\ref{eq:M_e-b}), (\ref{eq:M_d}), (\ref{eq:M_ic}), (\ref{eq:M_n}), (\ref{eq:M_total}). The result is shown Fig. \ref{fig:adaptive_memory}. \begin{figure}[htb] \centering \includegraphics[width=0.48\textwidth]{figs/adaptive_control_memory.eps} \caption{Maximum number of output dimensions for each input dimension and number of neurons for a neural network simulated on a PE. }\label{fig:adaptive_memory} \end{figure} \subsubsection{Computation Time and Comparison with Loihi}\label{result_adaptive_control_time} \begin{figure}[htb] \centering \includegraphics[width=0.48\textwidth]{figs/ratio_encoding_with_without_mlacc_paper_v2} \caption{Speedup of input processing time with the MAC array }\label{fig:encoding2} \end{figure} \begin{figure*}[ht] \centering \includegraphics[width=1.0\textwidth]{figs/loihi_jib1_adaptive_control_comparison_time} \caption{Duration of a time step of SpiNNaker 2 prototype (with strips) and Loihi (without strips) for different number of neurons per core, different input and output dimensions for the adaptive control benchmark. No measurement result for the SpiNNaker 2 prototype is shown where the implementation is limited by memory. }\label{fig:loihi_jib1_comparison_time} \end{figure*} For adaptive control, the computation times for input processing (\(T_{i\_mlacc}\) / \(T_{i\_no\_mlacc}\)), neuron update (\(T_{n}\)), output processing (\(T_{o}\)) and weight update (\(T_{w}\)) are measured. After the measurement, polynomial models can be fitted by minimizing the mean-squared error. For input processing with MAC array, the number of clock cycles is \begin{align} T_{i\_mac} \;=\; 131.21 + 5.07 N \nonumber \\ + 0.13 N D_{in} + 35.79 D_{in} \label{eq:c_encoding_mac} \end{align} where \(N\) is the number of neurons, \(D_{in}\) is the number of input dimensions. Eq. (\ref{eq:c_encoding_mac}) is very similar to Eq. (\ref{eq:c_mm}), because the main computation is in both cases done by the MAC array. The difference is caused by the different data types. In keyword spotting, the inputs are assumed to be 8 bit integers, but in adaptive control, each input is assumed to be floating point. This is necessary because in general, the same implementation can be used as a building block for NEF implementation on SpiNNaker 2 to construct large-scale cognitive models as mentioned in Section \ref{adaptive_control}, so that the input data type needs to be the same as the output data type. Since the output weights are floating point, and their values change dynamically due to learning, an extra range check is performed for each input value, and an extra data type conversion is performed. This is reflected in \(35.79 D_{in}\) and the constant \(131.21\). The number of clock cycles without MAC array is \begin{align} T_{i\_no\_mac} \;=\; 102.52 + 22.54 N \nonumber \\ + 7.07 N D_{in} + 25.54 D_{in} \label{eq:c_encoding_no_mac} \end{align} The main benefit of MAC array is reflected in the reduction of \(7.07 N D_{in}\) in Eq. (\ref{eq:c_encoding_no_mac}) to \(0.13 N D_{in}\) in Eq. (\ref{eq:c_encoding_mac}), which is made possible by the SIMD operation of the MAC array. The speedup is higher for higher dimensions. Fig. \ref{fig:encoding2} shows the speedup of the computation time for input processing with the MAC array compared to without the MAC array. Unlike in keyword spotting, where the ReLU neuron model is used, in adaptive control, the LIF neuron model is used, which is the same as in Loihi. The neuron update time in terms of number of clock cycles is \begin{align} T_{n} \;=\; 28.19 N - 26.90 NP + 509.18 \label{eq:c_lif_neuron_update} \end{align} where \(P\) is the firing probability. The minus sign in \(-26.9 N P\) is because during the refractory period, the computation needed is reduced. Since this is event based, it depends on \(P\). The output processing time is \begin{equation} T_{o} \;=\; 5.8 ND_{out}P + 19.31 NP \label{eq:c_lif_decoding} \end{equation} where \(D_{out}\) is the number of output dimensions. The weight update time is \begin{equation} T_{w} \;=\; 8.28 ND_{out}P + 28.04N P \label{eq:c_lif_learning} \end{equation} The total time is \begin{align} T_{total} \;=\; T_{i\_mac} + T_{n} + T_{o} + T_{w} \label{eq:c_lif_total} \end{align} Since output processing and weight update are event based, the firing rate of 130 Hz corresponding to a firing probability \(P\) of 0.13, which is used for comparing the SpiNNaker 2 prototype with Loihi, would reduce the computation time by 87\% compared to a non-event-based implementation. Typically, the SpiNNaker system runs in real time with 1 ms time step. When the PE is running at 250 MHz, the available number of clock cycles for each time step is 250 000, which is the computational constraint. According to Eq. (\ref{eq:c_lif_total}), for the range of the parameters shown in Fig. \ref{fig:adaptive_memory}, the computation can be done within 1 ms. So the maximum implementable size of a network on a single PE in this benchmark is constrained by memory rather than computation. Although the SpiNNaker system runs with a constant timer tick, and within a timer tick, the Arm core enters sleep mode after the computation is done, the study of the computation time provides information about how much the time step can be potentially reduced, e.g. when instead of a 1 ms timer tick, a 0.5 ms timer tick is required. For the adaptive control benchmark task with different number of input dimensions, output dimensions and number of neurons, the duration of a time step of SpiNNaker 2 prototype and Loihi is compared and shown in Fig. \ref{fig:loihi_jib1_comparison_time}, with the mean population firing rate kept at around 130 Hz for both hardwares. Here the duration of a time step for the SpiNNaker 2 prototype refers to the time for the PE to complete the computation of a time step. From the comparison it is clear that for small number of input dimensions, Loihi is faster than the SpiNNaker 2 prototype, and for large number of input dimensions, the SpiNNaker 2 prototype is faster than Loihi. The maximum ratio of duration of a time step between both hardwares is summarized in Tab. \ref{tab:adaptive_control_relative_time}. Because of the MAC array, the computation time of the SpiNNaker 2 prototype increases less rapidly with the number of input dimensions, so that the SpiNNaker 2 prototype could catch up with Loihi in terms of computation time for higher input dimensions. \begin{table}[htb] \begin{minipage}{0.47\textwidth} \centering \renewcommand{\arraystretch}{1.1} \caption{Maximum ratio of duration of a time step between the SpiNNaker 2 prototype (SpiNN) and Loihi for the adaptive control task } \label{tab:adaptive_control_relative_time} \centering \footnotesize \begin{tabular}{lcc} \toprule Input Dimensions & 1 & 100 \\ Output Dimensions & 1 & 1 \\ Number of Neurons & 1024 & 512 \\ Duration of a Time Step SpiNN : Loihi & 1 : 0.37 & 0.49 : 1\\ \bottomrule \end{tabular} \end{minipage} \end{table} \subsubsection{Energy Measurement and Comparison with Loihi}\label{result_adaptive_control_power} \begin{figure*}[ht] \centering \includegraphics[width=1.0\textwidth]{figs/loihi_jib1_adaptive_control_comparison_energy.png} \caption{Active energy of SpiNNaker 2 prototype (with strips) and Loihi (without strips) for different number of neurons per core, different input and output dimensions for the adaptive control benchmark. No measurement result for the SpiNNaker 2 prototype is shown where the implementation is limited by memory. }\label{fig:loihi_jib1_comparison} \end{figure*} \begin{figure}[htb] \centering \includegraphics[width=0.48\textwidth]{figs/loihi_jib1_adaptive_control_comparison_breakdown.png} \caption{Breakdown of energy consumption per core per time step of the SpiNNaker 2 prototype into 4 energy components: input processing, neuron update, output processing and weight update. }\label{fig:jib1_energy_breakdown} \end{figure} The energy consumption of the SpiNNaker 2 prototype and Loihi is measured with the same parameters as in the computation time comparison. The result is shown in Fig. \ref{fig:loihi_jib1_comparison}. Similar to Section \ref{result_keyword_spotting_power}, only the active energy is shown. For small number of input dimensions, Loihi is more energy efficient than the SpiNNaker 2 prototype, and for large number of input dimensions, the SpiNNaker 2 prototype is more energy efficient than Loihi. The maximum ratio of active energy consumption between both hardwares is summarized in Tab. \ref{tab:adaptive_control_relative_energy}. \begin{table}[htb] \begin{minipage}{0.47\textwidth} \centering \renewcommand{\arraystretch}{1.1} \caption{Maximum ratio of active energy consumption between the SpiNNaker 2 prototype (SpiNN) and Loihi for the adaptive control task } \label{tab:adaptive_control_relative_energy} \centering \footnotesize \begin{tabular}{lcc} \toprule Input Dimensions & 1 & 100 \\ Output Dimensions & 1 & 1 \\ Number of Neurons & 1024 & 512 \\ Active Energy SpiNN : Loihi & 1 : 0.81 & 0.36 : 1 \\ \bottomrule \end{tabular} \end{minipage} \end{table} Similar to the computation time comparison, we see the benefit of MAC array especially for high input dimensions, when the MAC array is more extensively used. This is made more clear in the energy breakdown in Fig. \ref{fig:jib1_energy_breakdown}. Here, it is clear how the input processing energy increases with the input dimensions for the same number of neurons and output dimensions, how the neuron update energy increases with the number of neurons for the same input dimensions and output dimensions, and how the output processing and weight update energy increases with the number of output dimensions for the same input dimensions and number of neurons. \subsubsection{Robotic Demo}\label{result_adaptive_control_demo} The SpiNNaker 2 prototype running the adaptive control benchmark is connected to a robotic arm built with Lego Mindstorms EV3 robot kit. The setup is based on \cite{terry15}. The input to the neural network is the position and velocity of the motor and the output of the neural network is the motor control signal to be combined with the PD controller output, as described in Section \ref{adaptive_control}. In this demo we consider two situations: the normal case and the simulated aging case (Fig. \ref{fig:robotic_demo1}, upper part). In the case of simulated aging an extra weight is added to the robotic arm to resemble the aging effect or unknown disturbance. For each case the performance of the adaptive controller is compared with a normal PID controller. In the normal case, both controllers perform equally well, but in the simulated aging case, the PID controller cannot adapt itself to the new situation, while the adaptive controller can learn from the error feedback and adapt its parameters to improve the performance (Fig. \ref{fig:robotic_demo1}, lower part). \begin{figure}[h] \centering \includegraphics[width=0.48\textwidth]{figs/robotic_demo7-eps-converted-to.pdf} \caption{Robotic demo. Upper part: In the normal case (left), there is no extra weight attached to the robotic arm. In the simulated aging case (right), an extra weight is attached to resemble the aging effect. Lower part: Performance of the PID Controller and the adaptive controller in the normal case and the simulated aging case. The red curve shows the actual position of the arm, and the green curve shows the target position. The shown position is the normalized angle position of the motor. In the normal case, both the PID Controller and the adaptive controller perform well. But in the simulated aging case, the PID Controller cannot adapt to the new situation, while the adaptive controller can adapt to the new situation by learning from error feedback, thus improving the performance, as seen in the improvement from the first to second motor commands. }\label{fig:robotic_demo1} \end{figure} \subsection{System Overview}\label{sys_ove} SpiNNaker \cite{furber14} is a digital neuromorphic hardware system based on low-power Arm processors originally built for real-time simulation of spiking neural networks (SNNs). In the second generation of SpiNNaker (SpiNNaker 2), which is currently being developed in the Human Brain Project \cite{amunts2016human}, several improvements are being made. The SpiNNaker 2 architecture is based on Processing Elements (PEs) which contain an Arm Cortex-M4F core, 128 KBytes local SRAM, hardware accelerators for exponential functions \cite{partzsch17} and true- and pseudo random numbers \cite{felix16,synsampling19} and multiply-accumulate (MAC) accelerators. Additionally, the PEs include advanced dynamic voltage and frequency scaling (DVFS) features \cite{hoeppner17iscas,hoeppner19tcas}. The PEs are arranged in Quad-Processing Elements (QPEs) containing four PEs and a Network-on-Chip (NoC) router for packet based on-chip communication. The QPEs can be placed in a array scheme without any additional flat toplevel routing to form the SpiNNaker 2 many core SoC. SpiNNaker 2 will be implemented in GLOBALFOUNDRIES 22FDX technology ~\cite{glofo16}. This FDSOI technology allows the application of adaptive body biasing (ABB) for low-power operation at ultra-low supply voltages in both forward \cite{Hoeppner2019a} and reverse bias schemes \cite{Walter2020}. For maximum energy efficiency and reasonable clock frequencies, 0.50V nominal supply voltage is chosen and ABB in a forward bias scheme is applied. The ABB aware implementation methodology from \cite{Hoeppner2019b} has been used. This allows to achieve \SI{>200}{\MHz} clock frequency at 0.50V nominal supply voltage at the first DVFS performance level PL1 and \SI{>400}{\MHz} from 0.60V supply at the second DVFS performance level PL2. The second SpiNNaker 2 prototype chip has been implemented and manufactured in 22FDX \textcolor{red}{(cite Jib1 paper)}. It contains 2 QPEs with 8 PEs in total to allow the execution of neuromorphic applications. Fig.~\ref{fig:pe_schematic} shows the simplified block diagram of the testchip PE array. The chip photo is shown in Fig.~\ref{fig:chipphoto}. The testchip includes peripheral components for host communication, a prototype of the SpiNNaker router for chip-to-chip spike communication and some shared on-chip SRAM. \begin{figure}[htb] \centering \includegraphics[width=0.48\textwidth]{figs/qpe_schematic2.eps} \caption{Simplified schematic of the second SpiNNaker 2 prototype with 2 QPEs. Each QPE contains 4 PEs. Each PE contains a MAC array, an Arm core and a local SRAM. The NoC router is responsible for the communication. }\label{fig:pe_schematic} \end{figure} \begin{figure}[htb] \centering \includegraphics[width=0.25\textwidth]{figs/jib1_chipphoto.eps} \caption{Chip photo of the SpiNNaker 2 prototype in 22FDX technology }\label{fig:chipphoto} \end{figure} \subsection{MAC Array}\label{mac_acc} The MAC array has 64 MAC units in a 4 x 16 layout. Fig. \ref{fig:mac_schematic} illustrates the MAC array. The data of operand A and operand B are arrays of 8 bit integer values. In each clock cycle, 16 values from the array of operand A and 4 values from the array of operand B are fed into the MAC array. Every MAC unit in the same column is fed with the same value from operand A, and every MAC unit in the same row is fed with the same value from operand B. The software running on the Arm core is responsible for arranging the data in the SRAM and notifying the MAC array the address and length of the data to be processed. After the data is processed, the results are written back to predefined addresses in the memory. The result of each MAC unit is 29-bit. \begin{figure}[htb] \centering \includegraphics[width=0.4\textwidth]{figs/mac.eps} \caption{Schematic of the MAC array. Each square in the 4 x 16 block represents one MAC unit. The squares around the block represent the data to be executed. In each clock cycle, 4 values from operand B and 16 values from operand A are fed into the MAC array simultaneously, as indicated by the arrows. }\label{fig:mac_schematic} \end{figure} When computing a matrix multiplication, a general purpose processor like the Arm core needs to: 1. fetch the operand A and operand B into the registers, 2. do the multiply-accumulate, 3. write the result back, 4. check the condition of the loop, 5. compute the addresses of the data in the next iteration. While the MAC array essentially does the same, it is more efficient due to the Single Instruction Multiple Data (SIMD) operation. In particular, the efficiency is made possible by: 1. 64 MAC operations can be done in one clock cycle in parallel. 2. 16 x 8 bits of data of operand A and 4 x 8 bits of data of operand B can be fetched in one clock cycle in parallel 3. control logic and data transfer in parallel to MAC operations, hiding the overhead of data transfer for the next iteration. \subsection{Keyword Spotting} The keyword spotting network consists of 2 computational steps: vector-matrix multiplication which is done with the MAC array and ReLU update which is done with the ARM core. Because of memory constraints (see Section \ref{result_keyword_spotting_memory}) layer 1 is split into 2 PEs. The weights in this network are the same as in \cite{keyword_spotting_loihi19}. The input to the network is a 390 dimensional vector of 8 bit integers. The ReLU activations of each layer are also 8 bit integers. The ReLU activations of layer 2 are directly sent back to host PC, where the vector-matrix multiplication for the output layer with 29 dimensions is performed, the same as in \cite{keyword_spotting_loihi19}. Fig. \ref{fig:keywordspotting_impl} shows the implementation of the keyword spotting network on the SpiNNaker 2 prototype. \begin{figure}[htb] \centering \includegraphics[width=0.48\textwidth]{figs/keyword_spotting_impl3.eps} \caption{Implementation of keyword spotting network on the SpiNNaker 2 prototype }\label{fig:keywordspotting_impl} \end{figure} \subsection{Adaptive Control} The implementation of adaptive control on the SpiNNaker 2 prototype is based on \cite{mundy15} and \cite{knight2016}. There are mainly 4 computational steps: input processing, neuron update, output processing and weight update. In input processing, the inputs to the network are multiplied with the input weight matrix to produce the input current for each neuron in the hidden layer. The weights are quantized to 8 bit integers with stochastic rounding. The vector-matrix multiplication with only ARM core and without MAC array is also implemented and serves as reference. The rest of the computation is implemented on the ARM core which allows event based processing. In neuron update, the neuron dynamics is updated according to the input current. The Leaky-Integrate-and-Fire (LIF) neuron model is used in the hidden layer to allow for event based processing of the spikes in the following steps. In output processing, the outputs of the neurons are multiplied with the output weight matrix. In the case of non-spiking neuron models like ReLU, this process is a vector-matrix multiplication. In the case of spiking neuron models, a connection is only activated when there is a spike, so this output processing step corresponds to adding the weights associated with the neuron which has spiked to the output of the network. In weight update, the output weight matrix is updated according to the neuron activity and error signal. In order to do weight update in an event based manner, the low pass filter mentioned in section \ref{adaptive_control} has been removed, similar to \cite{knight2016}. Because of the short time constant of the low pass filter in this application, this modification doesn't affect the performance. Since the learning rate is normally very small, floating point data type is chosen for the weights in the output weight matrix. In this work, we focus on the adaptive control network implemented on a single PE. The implementation is done with scalability in mind. In the case that the size of a neuron population exceeds the memory limit of a PE, it can be split into many PEs \cite{mundy15}. In this work, the PE additionally simulates the PD controller. The overhead is negligible. The computational steps and the hardware component used for each step is summarized in Fig. \ref{fig:nef_mlacc}. The PD controller is not shown since the computation is relatively simple. \begin{figure}[htb] \centering \includegraphics[width=0.48\textwidth]{figs/nef_mlacc2.eps} \caption{Main computational steps and hardware component for each step in adaptive control }\label{fig:nef_mlacc} \end{figure} \subsection{Keyword Spotting}\label{keyword_spotting} Keyword spotting is a speech processing problem which deals with identifying keywords in utterances. A practical use case is the identification of wake words for virtual assistants (e.g. "Alexa"). In this work, the keyword spotting network we implement on the SpiNNaker 2 prototype is the same as in \cite{keyword_spotting_loihi19}, which consists of 1 input layer with 390 input values, 2 dense layers each with 256 neurons and 1 output layer with 29 output values (Fig. \ref{fig:keyword_spotting_algo}). Also, the same as in \cite{keyword_spotting_loihi19}, no training is involved and only inference is considered. The 390 dimensional input to the network is the Mel-frequency cepstral coefficient (MFCC) features of an audio waveform in each time step. The 29 dimensional output of the network basically corresponds to the alphabetical characters, with additional special characters for e.g. silence etc. One 'inference' with this network involves passing 10 time steps of the MFCC features into the network. The outputs are then postprocessed to form a result for the inference. The difference to the implementation on Loihi is that on the SpiNNaker 2 prototype, we implement the network with normal DNN with ReLU activations, whereas on Loihi, the SNN version was implemented since Loihi only supports SNNs. \begin{figure}[htb] \centering \includegraphics[width=0.4\textwidth]{figs/keyword_spotting_architecture2.eps} \caption{Keyword Spotting Network Architecture }\label{fig:keyword_spotting_algo} \end{figure} \subsection{Adaptive Control}\label{adaptive_control} For our second benchmark task, we use the adaptive control algorithm proposed as a benchmark in \cite{terry15} and further investigated in \cite{nengo_adaptive_loihi2020}. This benchmark consists of a single-hidden-layer neural network, where the input is the sensory state of the system to be controlled (such as a robot arm) and the output is the extra force that should be applied to compensate for the intrinsic dynamics and forces on the arm (gravity, friction, etc.) The only non-linearities are in the hidden layer (i.e. there is no non-linear operation directly on the input or output). The input weights are fixed and randomly chosen, and the output weights $\omega_{ij}$ are initialized to zero and then adjusted using a variant of the delta rule \cite{eliasmith2011} (Eq. \ref{eq:adaptive_control}), where $\alpha$ is a learning rate, $a_i$ is the current level of activity of the $i$th neuron, and $E_j$ is an error signal. \begin{align} \Delta \omega_{ij} = \alpha a_i E_j \label{eq:adaptive_control} \end{align} Crucially, if we use the output of a PD-controller to be this error signal $E_j$, and if we take the output of this network and add it to the control signal produced by a PD-controller, then the resulting system will act as a stable adaptive controller \cite{dewolf16}. This is a variant of the adaptive control algorithm developed by Jean-Jacques Slotine \cite{slotine87}. One way to think of this is that the neural network is acting somewhat like the I term in a PID-controller, but since the I value is being produced by the neural network, it can be different for different parts of the sensory space. It can thus learn to, for example, apply extra positive torque when a robot arm is leaning far to one side, and extra negative torque when the arm is leaning far to the other side. When used with spiking neurons, we also apply a low-pass filter to the $a_i$ term, producing a continuous value representative of the recent spiking activity of the neuron. While this benchmark was originally proposed for its simplicity and applicability across a wide range of neuromorphic hardware and controlled devices, there is one further important reason for us to choose this benchmark. The core network that it requires has a single hidden layer non-linearity, and the inputs and outputs are generally of much lower dimensionality than the number of neurons in the hidden layer. This is exactly the sort of network that forms the core component of the Neural Engineering Framework (NEF) \cite{eliasmith2003a}. The NEF has been used to create large-scale biologically-based neural models \cite{eliasmith2012} by chaining these smaller networks together. By sending the output from one of these networks to the inputs of another network, we are effectively factoring the weight matrix between the hidden layers of the two networks. This has been shown to be a highly efficient method for implementing neural models on the original SpiNNaker 1 hardware \cite{mundy15}, and we expect the same to be the case on SpiNNaker 2. \begin{figure}[htb] \centering \includegraphics[width=0.48\textwidth]{figs/adaptive_control_algo2.eps} \caption{Adaptive Control Network Architecture }\label{fig:adaptive_algo} \end{figure}
{'timestamp': '2020-09-21T02:17:20', 'yymm': '2009', 'arxiv_id': '2009.08921', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08921'}
arxiv
\section{Introduction} Privacy-preserving machine learning is critical to the deployment of data-driven solutions in applications involving sensitive data. Differential privacy (DP) \cite{dwork2006calibrating} is a de-facto standard for designing algorithms with strong privacy guarantees for individual data. Large-scale industrial deployments -- e.g.\ by Apple \cite{appledp}, Google \cite{erlingsson2014rappor} and the US Census Bureau \cite{abowd2018us} -- and general purpose DP tools for machine learning \cite{tfprivacy} and data analysis \cite{DBLP:journals/corr/abs-1907-02444,wilson2019differentially} exemplify that existing methods are well-suited for simple data analysis tasks (e.g.\ averages, histograms, frequent items) and batch learning problems where the training data is available beforehand. While these techniques cover a large number of applications in the central and (non-interactive) local models, they are often insufficient to tackle machine learning applications involving other threat models. This includes federated learning problems \cite{kairouz2019advances,li2019federated} where devices cooperate to learn a joint model while preserving their individual privacy, and, more generally, interactive learning in the spirit of the reinforcement learning (RL) framework \cite{sutton2018reinforcement}. In this paper we contribute to the study of reinforcement learning from the lens of differential privacy. We consider sequential decision-making tasks where users interact with an agent for the duration of a fixed-length episode. At each time-step the current user reveals a state to the agent, which responds with an appropriate action and receives a reward generated by the user. Like in standard RL, the goal of the agent is to learn a policy that maximizes the rewards provided by the users. However, our focus is on situations where the states and rewards that users provide to the agent might contain sensitive information. While users might be ready to reveal such information to an agent in order to receive a service, we assume they want to prevent third parties from making unintended inferences about their personal data. This includes external parties who might have access to the policy learned by the agent, as well as malicious users who can probe the agent's behavior to trigger actions informed by its interactions with previous users. For example, \cite{DBLP:conf/atal/PanWZLYS19} recently showed how RL policies can be probed to reveal information about the environment where the agent was trained. The question we ask in this paper is: how should the learnings an agent can extract from an episode be balanced against the potential information leakages arising from the behaviors of the agent that are informed by such learnings? We answer the question by making two contributions to the analysis of the privacy-utility trade-off in reinforcement learning: (1) we provide the first privacy-preserving RL algorithm with formal accuracy guarantees, and (2) we provide lower bounds on the regret and number of sub-optimal episodes for any differentially private RL algorithm. To measure the privacy provided by episodic RL algorithms we introduce a notion of episodic joint differential privacy (JDP) under continuous observation, a variant of joint differential privacy \cite{DBLP:conf/innovations/KearnsPRU14} that captures the potential information leakages discussed above. \paragraph{Overview of our results.} We study reinforcement learning in a fixed-horizon episodic Markov decision process with $S$ states, $A$ actions, and episodes of length $H$. We first provide a meaningful privacy formulation for this general learning problem with a strong relaxation of differential privacy: joint differential privacy (JDP) under continual observation, controlled by a privacy parameter $\epsilon \geq 0$ (larger $\epsilon$ means less privacy). Under this formulation, we give the first known RL sample complexity and regret upper and lower bounds with formal privacy guarantees. First, we present a new algorithm, \texttt{PUCB}, which satisfies $\varepsilon$-JDP in addition to two utility guarantees: it finds an $\alpha$-optimal policy with a sample complexity of $$\tilde O\left( \frac{SAH^4}{\alpha^2} + \frac{S^2AH^4 }{\varepsilon\alpha}\right) \enspace,$$ and achieves a regret rate of $$\tilde O\left(H^2 \sqrt{SAT} + \frac{SAH^3 + S^2 A H^3}{\varepsilon} \right)$$ over $T$ episodes. In both of these bounds, the first terms $\frac{SAH^4}{\alpha^2}$ and $H^2 \sqrt{SAT}$ are the non-private sample complexity and regret rates, respectively. The privacy parameter $\varepsilon$ only affects the lower order terms -- for sufficiently small approximation $\alpha$ and sufficiently large $T$, the ``cost'' of privacy becomes negligible. We also provide new lower bounds for $\varepsilon$-JDP reinforcement learning. Specifically, by incorporating ideas from existing lower bounds for private learning into constructions of hard MDPs, we prove a sample complexity bound of $$\tilde \Omega\left(\frac{SAH^2}{\alpha^2} + \frac{SAH}{\varepsilon\alpha} \right)$$ and a regret bound of $$\tilde \Omega\left( \sqrt{HSAT} + \frac{SAH}{\varepsilon}\right) \enspace.$$ As expected, these lower bounds match our upper bounds in the dominant term (ignoring $H$ and polylogarithmic factors). We also see that necessarily the utility cost for privacy grows linearly with the state space size, although this does not match our upper bounds. Closing this gap is an important direction for future work. \subsection{Related Work} Most previous works on differentially private interactive learning with partial feedback concentrate on bandit-type problems, including on-line learning with bandit feedback \cite{thakurta2013nearly,agarwal2017price}, multi-armed bandits \cite{mishra2015nearly,tossou2016algorithms,tossou2017achieving,tossou2018differential}, and linear contextual bandits \cite{DBLP:conf/icml/NeelR18,shariff2018differentially}. These works generally differ on the assumed reward models under which utility is measured (e.g.\ stochastic, oblivious adversarial, adaptive adversarial) and the concrete privacy definition being used (e.g.\ privacy when observing individual actions or sequences of actions, and privacy of reward or reward and observation in the contextual setting). \cite{basu2019differential} provides a comprehensive account of different privacy definitions used in the bandit literature. Much less work has addressed DP for general RL. For policy evaluation in the batch case, \cite{DBLP:conf/icml/BalleGP16} propose regularized least-squares algorithms with output perturbation and bound the excess risk due to the privacy constraints. For the control problem with private rewards and public states, \cite{NIPS2019_9310} give a differentially private Q-learning algorithm with function approximation. On the RL side, as we are initiating the study of RL with differential privacy, we focus on the well-studied tabular setting. While a number of algorithms with utility guarantees and lower bound constructions are known for this setting~\cite{Kakade2003,azar2017minimax,dann2017unifying}, we are not aware of any work addressing the privacy issues that are fundamental in high-stakes applications. \section{Lower Bounds}\label{sec:lower} In this section we prove the following lower bounds on the sample complexity and regret for any PAC RL agent providing joint differential privacy. \begin{theorem}[PAC Lower Bound]\label{thm:lowerbound} Let $\cM$ be an RL agent satisfying $\varepsilon$-JDP. Suppose that $\cM$ is $(\alpha, \beta)$-PAC for some $\beta \in (0,1/8)$. Then, there exists a fixed-horizon episodic MDP where the number of episodes until the algorithm's policy is $\alpha$-optimal with probability at least $1 - \beta$ satisfies \begin{align*} \Ex{n_\cM} \geq \Omega\left( \frac{SAH^2}{\alpha^2} + \frac{SAH}{\alpha\epsilon} \ln\left(\frac{1}{\beta}\right)\right) \enspace. \end{align*} \end{theorem} \begin{theorem}[Private Regret Lower Bound]\label{thm:regretlower} For any $\varepsilon$ JDP-algorithm $\cM$ there exist an MDP $M$ with $S$ states $A$ actions over $H$ time steps per episode such that for any initial state $s\in\cS$ the expected regret of $\cM$ after $T$ steps is \begin{align*} \Ex{\mathrm{Regret}(T)} = {\Omega}\left (\sqrt{HSA T} + \frac{S A H\log(T)}{\varepsilon}\right) \end{align*} for any $T \geq S^{1.1}$. \end{theorem} Here we present the proof steps for the sample complexity lower bound in Theorem~\ref{thm:lowerbound}. The proof for the regret lower bound in Theorem~\ref{thm:regretlower} follows from a similar argument and is deferred to the appendix. To obtain Theorem~\ref{thm:lowerbound}, we go through two intermediate lower bounds: one for private best-arm identification in multi-armed bandits problems (Lemma~\ref{lem:privMAB}), and one for private RL in a relaxed scenario where the initial state of each episode is considered public information (Lemma~\ref{lem:lowerboundpublic}). At first glance our arguments look similar to other techniques that provide lower bounds for RL in the non-private setting by leveraging lower bounds for bandits problems, e.g.\ \cite{strehl2009reinforcement,dann2015sample}. However, getting this strategy to work in the private case is significantly more challenging because one needs to ensure the notions of privacy used in each of the lower bounds are compatible with each other. Since this is the main challenge to prove Theorem~\ref{thm:lowerbound}, we focus our presentation on the aspects that make the private lower bound argument different from the non-private one, and defer the rest of details to the appendix. \subsection{Lower Bound for Best-Arm Identification}\label{sec:mablb} The first step is a lower bound for best-arm identification for differentially private multi-armed bandits algorithms. This considers mechanisms $\cM$ interacting with users via the MAB protocol described in \cref{alg:mabprotocol}, where we assume arms $a^{(t)}$ come from some finite space $\cA$ and rewards are binary, $r^{(t)} \in \{0,1\}$. Recall that $T$ denotes the total number of users. Our lower bound applies to mechanisms for this protocol that satisfy standard DP in the sense that the adversary has access to all the outputs $\cM(U) = (a^{(1)}, \ldots, a^{(T)},\hat{a})$ produced by the mechanism. \begin{definition} A MAB mechanism $\cM$ is $\epsilon$-DP if for any neighboring user sequences $U$ and $U'$ differing in a single user, and all events $E \subseteq \cA^{T+1}$ we have \begin{align*} \Pr[\cM(U) \in E] \leq e^{\epsilon} \Pr[\cM(U') \in E] \enspace. \end{align*} \end{definition} To measure the utility of a mechanism for performing \emph{best-arm identification} in MABs we consider a stochastic setting with independent arms. In this setting each arm $a \in \cA$ produces rewards following a Bernoulli distribution with expectation $\bar{P}_a$ and the goal is to identify high probability an optimal arm $a^*$ with expected reward $\bar{P}_{a^*} = \max_{a \in \cA} \bar{P}_a$. A problem instance can be identified with the vector of expected rewards $\bar{P} = (\bar{P}_a)_{a \in \cA}$. \begin{algorithm}[h] \caption{MAB Protocol for Best-Arm Identification}\label{alg:mabprotocol} \KwIn{Agent $\cM$ and users $u_1, \ldots, u_T$} \For{$t \in [T]$}{ $\cM$ sends arm $a^{(t)}$ to $u_t$ \\ $u_t$ sends reward $r^{(t)}$ to $\cM$ } $\cM$ releases arm $\hat{a}$ \end{algorithm} The lower bound result relies on the following adaptation of the coupling lemma from \citep[Lemma 6.2]{karwa2017finite}. \begin{lemma}\label{lem:KarwaVadhanMAB} Fix any arm $a \in [k]$. Now consider any pair of MAB instances $\mu, \nu \in [0,1]^k$ both with $k$ arms and time horizon $T$, such that $\|\mu_a - \nu_a \|_{tv} < \alpha$ and $\|\mu_{a'} - \nu_{a'} \|_{tv} = 0$ for all $a' \neq a$. Let $R \sim B(\mu)^T$ and $Q \sim B(\nu)^T$ be the sequence of $T$ rounds of rewards sampled under $\mu$ and $\nu$ respectively, and let $\cM$ be any $\epsilon$-DP multi-armed bandit algorithm. Then, for any event $E$ such that under event $E$ arm $a$ is pulled less than $t$ times, \begin{align*} \prob{\cM,R}{E} \leq e^{6 \epsilon t \alpha}\prob{\cM,Q}{E} \end{align*} \end{lemma} \begin{lemma}[Private MAB Lower Bound]\label{lem:privMAB} Let $\cM$ be a MAB best-arm identification algorithm satisfying $\epsilon$-DP that succeeds with probability at least $1-\beta$, for some $\beta \in (0,1/4)$. For any MAB instance $\bar{P}$ and any $\alpha$-suboptimal arm $a$ with $\alpha > 0$ (i.e.\ $\bar{P}_a = \bar{P}_{a^*} - \alpha$), the number of times that $\cM$ pulls arm $a$ during the protocol satisfies \begin{align*} \Ex{n_a} > \frac{1}{24 \epsilon \alpha}\ln{\left(\frac{1}{4\beta}\right)} \enspace. \end{align*} \end{lemma} \begin{proof} Let $a^*$ be the optimal arm under $\bar{P}$ and $a$ an $\alpha$-suboptimal arm. We construct an alternative MAB instance $\bar{Q}$ by exchanging the rewards of $a$ and $a^*$: $\bar{Q}_a = \bar{P}_{a^*}$, $\bar{Q}_{a^*} = \bar{P}_a$, and the rest of rewards are identical on both instances. Note that now $a^*$ is $\alpha$-suboptimal under $\bar{Q}$. Let $t_a = \frac{1}{24\epsilon \alpha}\ln{\left(\frac{1-2\beta}{2\beta}\right)}$ and $n_a$ is the number of times the policy $\cM$ pulls arm $a$. We suppose that $\ex{\bar{P}}{n_a} \leq t_a$ and derive a contradiction. Define $A$ to be the event that arm $n_a$ is pulled less than $4 t_a$ times, that is $A := \{n_a \leq 4 t_a\}$. From Markov's inequality we have \begin{align} \label{eq:assump} t_a \geq \ex{\bar{P}}{n_a} &\geq 4 t_a \prob{\bar{P}}{n_a > 4 t_a} \\ \label{eq:A} & = 4 t_a\left(1- \prob{\bar{P}}{n_a \leq 4 t_a} \right) \enspace, \end{align} where the first inequality \eqref{eq:assump} comes from the assumption that $\Ex{n_a} \leq t_a$. From \eqref{eq:A} above it follows that $\prob{\bar{P}}{A} \geq 3/4$. We also let $B$ be the event that arm $a^*$ is selected. Since arm $a^*$ is optimal under $\bar{P}$, our assumption on $\cM$ implies $\prob{\bar{P}}{B} \geq 1-\beta$. Now let $E$ be the event that both $A$ and $B$ occur, that is $E = A\cap B$. We combine the lower bound of $\prob{\bar{P}}{A}$ and $\prob{\bar{P}}{B}$ to get a lower bound for $\prob{\bar{P}}{E}$. First we show that $\prob{\bar{P}}{B|A} \geq 3/4 -\beta$: \begin{align*} 1-\beta &\leq \prob{\bar{P}}{B|A}\prob{\bar{P}}{A} + \prob{\bar{P}}{B|A^c}\prob{\bar{P}}{A^c} \\ &\leq \prob{\bar{P}}{B|A} + \prob{\bar{P}}{A^c} \leq \prob{\bar{P}}{B|A} + 1/4 \enspace. \\ \end{align*} By replacing in the lower bounds for $\prob{\bar{P}}{A}$ and $\prob{\bar{P}}{B|A}$ we obtain: \begin{align*} \prob{\bar{P}}{E} &= \prob{\bar{P}}{A}\prob{\bar{P}}{B|A} \geq \frac{3}{4} \left(\frac{3}{4} - \beta \right) \enspace. \end{align*} On instance $\bar{Q}$ arm $a^*$ is suboptimal, hence we have that $\prob{\bar Q}{E} \leq \beta$. Now we apply the group privacy property (Lemma~\ref{lem:KarwaVadhanMAB}) where the number of observations is $4 t_a$ and $t_a = \frac{1}{24\varepsilon\alpha}\ln\left(\frac{1/2 -\beta}{\beta}\right)$ to obtain \begin{align} \frac{3}{4} \left(\frac{3}{4} - \beta \right) &\leq \prob{\bar{P}}{E} \leq e^{6\epsilon \alpha 4 t_a} \prob{\bar{Q}}{E} \notag \\ &\leq e^{6\epsilon \alpha 4 t_a} \beta = \frac{1}{2}-\beta \label{eq:grouplem} \enspace. \end{align} But $\frac{3}{4} \left(\frac{3}{4} - \beta \right)>\frac{1}{2}-\beta$ for $\beta \in (0,1/4)$, therefore \eqref{eq:grouplem} is a contradiction. \end{proof} \subsection{Lower Bound for RL with Public Initial State}\label{sec:rlpslb} To leverage the lower bound for private best-arm identification in the RL setting we first consider a simpler setting where the initial state of each episode is public information. This means that we consider agents $\cM$ interacting with a variant of the protocol in Algorithm~\ref{alg:rlprotocol} where each user $t$ releases their first state $s_1^{(t)}$ in addition to sending it to the agent. We model this scenario by considering agents whose inputs $(U,S_1)$ include the sequence of initial states $S_1 = (s_1^{(1)},\ldots,s_1^{(T)})$, and define the privacy requirements in terms of a different notion of neighboring inputs: two sequences of inputs $(U,S_1)$ and $(U',S_1')$ are $t$-neighboring if $u_{t'} = u'_{t'}$ for all $t \neq t'$ and $S_1 = S_1'$. That is, we do not expect to provide privacy in the case where the user that changes between $U$ and $U'$ also changes their initial state, since in this case making the initial state public already provides evidence that the user changed. Note, however, that $u_t$ and $u_t'$ can provide different rewards for actions taken by the agent on state $s_1^{(t)}$. \begin{definition}\label{def:jdppublic} A randomized RL agent $\cM$ is $\epsilon$-JDP under continual observation in the \emph{public initial state} setting if for all $t \in [T]$, all $t$-neighboring user-state sequences $(U,S_1)$, $(U',S_1')$, and all events $E \subseteq A^{H \times [T-1]} \times \Pi$ we have \begin{align*} \pr{\cM_{-t}(U,S_1) \in E } \leq e^\epsilon \pr{\cM_{-t}(U',S_1') \in E} \enspace. \end{align*} \end{definition} \begin{figure}[h] \begin{equation*} \tikzfig{figures/hard_MDP2} \end{equation*} \caption{Class of hard MDP instances used in the lower bound.}\label{fig:hardMDP} \end{figure} We obtain a lower bound on the sample complexity of PAC RL agents that satisfy JDP in the public initial state setting by constructing a class of hard MDPs shown in Figure~\ref{fig:hardMDP}. An MDP in this class has state space $\cS \coloneqq [n] \cup \{+,-\}$ and action space $\cA \coloneqq \{0,\ldots,m\}$. On each episode, the agent starts on one of the initial states $\{1, \ldots, n\}$ chosen uniformly at random. On each of the initial states the agent has $m+1$ possible actions and transitions can only take it to one of two possible absorbing states $\{+,-\}$. Lastly, if the current state is either one of $\{ +, - \}$ then the only possible transition is a self loop, hence the agent will in that state until the end of the episode. We assume in these absorbing states the agent can only take a fixed action. Every action which transitions to state $+$ provides reward $1$ while actions transitioning to state $-$ provide reward $0$. In particular, in each episode the agent either receives reward $H$ or $0$. Such an MDP can be seen as consisting of $n$ parallel MAB problems. Each MAB problem determines the transition probabilities between the initial state $s \in\{1, \ldots, n\}$ and the absorbing states $\{+,-\}$. We index the possible MAB problems in each initial state by their optimal arm, which is always one of $\{0,\ldots,m\}$. We write $I_s \in \{0,\ldots,m\}$ to denote the MAB instance in initial state $s$, and define the transition probabilities such that $\pr{+|s,0} = 1/2+\alpha'/2$ and $\pr{+|s,a'} = 1/2$ for $a' \neq I_s$ for all $I_s$, and for $I_s \neq 0$ we also have $\pr{+|s,I_s} = 1/2 + \alpha'$. Here $\alpha'$ is a free parameter to be determined later. We succinctly represent an MDP in the class by identifying the optimal action (i.e.\ arm) in each initial state: $I \coloneqq (I_1,\ldots,I_n)$. To show that our MAB lower bounds imply lower bounds for an RL agent interacting with MDPs in this class we prove that collecting the first action taken by the agent in all episodes $t$ with a fixed initial state $s_1^{(t)} = s \in [n]$ simulates the execution of an $\epsilon$-DP MAB algorithm. Let $\cM$ be an RL agent and $(U,S_1)$ a user-state input sequence with initial states from some set $\cS_1$. Let $\cM(U,S_1) = (\vec{a}^{(1)},\ldots,\vec{a}^{(T)},\pi) \in \cA^{H \times T} \times \Pi$ be the collection of all outputs produced by the agent on inputs $U$ and $S_1$. For every $s \in \cS_1$ we write $\cM_{1,s}(U,S_1)$ to denote the restriction of the previous trace to contain just the first action from all episodes starting with $s$ together with the action predicted by the policy at states $s$: \begin{align*} \cM_{1,s}(U,S_1) \coloneqq \left(a_1^{(t_{s,1})}, \ldots, a_1^{(t_{s,T_s})}, \pi(s)\right) \enspace, \end{align*} where $T_s$ is the number of occurrences of $s$ in $S_1$ and $t_{s,1}, \ldots, t_{s,T_s}$ are the indices of these occurrences. Furthermore, given $s \in \cS_1$ we write $U_s = (u_{t_{s,1}},\ldots,u_{t_{s,T_s}})$ to denote the set of users whose initial state equals $s$. \begin{lemma}\label{lem:jdptodp} Let $(U,S_1)$ be a user-state input sequence with initial states from some set $\cS_1$. Suppose $\mathcal{M}$ is an RL agent that satisfies $\varepsilon$-JDP in the public initial state setting. Then, for any $s \in \cS_1$ the trace $\cM_{1,s}(U,S_1)$ is the output of an $\epsilon$-DP MAB mechanism on input $U_s$. \end{lemma} Using Lemmas~\ref{lem:privMAB} and~\ref{lem:jdptodp} and a reduction from RL lower bounds to bandits lower bounds yields the second term in the following result. The first terms follows directly from the non-private lower bound in \cite{dann2015sample}. \begin{lemma}\label{lem:lowerboundpublic} Let $\cM$ be an RL agent satisfying $\varepsilon$-JDP in the public initial state setting. Suppose that $\cM$ is $(\alpha, \beta)$-PAC for some $\beta \in (0,1/8)$. Then, there exists a fixed-horizon episodic MDP where the number of episodes until the algorithm's policy is $\alpha$-optimal with probability at least $1 - \beta$ satisfies \begin{equation* \Ex{n_\cM} \geq \Omega\left( \frac{S A H^2}{\alpha^2} + \frac{S A H}{\alpha\epsilon}\ln\left(\frac{1}{\beta} \right)\right) \enspace. \end{equation*} \end{lemma} Finally, Theorem~\ref{thm:lowerbound} follows from Lemma~\ref{lem:lowerboundpublic} by observing that any RL agent $\cM$ satisfying $\varepsilon$-JDP also satisfies $\varepsilon$-JDP in the public state setting (see lemma \ref{lem:publicvsprivatestates} and see appendix for proof). \begin{lemma}\label{lem:publicvsprivatestates} Any RL agent $\cM$ satisfying $\varepsilon$-JDP also satisfies $\varepsilon$-JDP in the public state setting. \end{lemma} \section{Conclusion} In this paper, we initiate the study of differentially private algorithms for reinforcement learning. On the conceptual level, we formalize the privacy desiderata via the notion of joint differential privacy, where the algorithm cannot strongly base future decisions off sensitive information from previous interactions. Under this formalism, we provide a JDP algorithm and establish both PAC and regret utility guarantees for episodic tabular MDPs. Our results show that the utility cost for privacy is asymptotically negligible in the large accuracy regime. We also establish the first lower bounds for reinforcement learning with JDP. A natural direction for future work is to close the gap between our upper and lower bounds. A similar gap remains open for tabular RL \emph{without} privacy considerations, but the setting is more difficult with privacy, so it may be easier to establish a lower bound here. We look forward to pursuing this direction, and hope that progress will yield new insights into the non-private setting. Beyond the tabular setup considered in this paper, we believe that designing RL algorithms providing state and reward privacy in non-tabular settings is a promising direction for future work with considerable potential for real-world applications. \section{Upper Bound} For any fixed $s,a,h \in \cS\times\cA\times[H]$ we introduce the following notation to count events that ocurred right before episode $t$: $\widehat{n}_t(s,a,h)$ is the number of times state $(s,a,h)$ is visited , $\widehat{r}_t(s,a,h)$ is the cumulative reward sum, and $\widehat{m}_t(s,a,s',h)$ is the transition count from state $s$ to state $s'$ after taking action $a$. We use the follwing shorthand notation for the confidence intervals that we'll use. \begin{align*} &\SamplingConfSign \coloneqq \SamplingConfVal \\ &\SamplingNoiseConfSign \coloneqq \SamplingNoiseConfVal \\ &\PrivacyConfSign \coloneqq \PrivacyConfVal \end{align*} where $E_{\eps} \coloneqq \frac{3}{\eps}H\log\left(\frac{2SAH+S^2AH}{\beta'}\right)\log\left(\Tmax\right)^{5/2}$. We denote by $w_{t}(s,a,h)$ the probability that state $s,a$ is visited on time step $h$ on episode $t$. \subsection{Error Bounds} \begin{lemma}\label{appex:lem:nfail} The event that there is an episode $t$ and $s,a,h\in \cS\times\cA\times[H]$ such that \begin{align*} \widehat{n}_t(s,a,t) < \sum_i^t w_{t}(s,a,h) - \ln{\frac{5SAH}{\beta}} \end{align*} happends with probability at most $\beta/5$. \end{lemma} \begin{lemma}\label{appex:lem:rewardfail} Let $r(s,a,h)$ be the mean reward. Then the event that there is an episode $t$ and $s,a,h\in \cS\times\cA\times[H]$ such that \begin{align*} \left| \frac{\widehat{r}_t(s,a,h)}{\widehat{n}_t(s,a,t)} -r(s,a,h) \right| > \SamplingConfSign \end{align*} happends with probability at most $\beta/5$. \end{lemma} \begin{lemma}\label{appex:lem:Vfail} Let $\cP(s,a,h)$ be the true transition distribution for state action pair $s,a,h$. And let $V^*$ be the optimal value function. We use the shorthand notation $\widehat{\cP}_t$ to denote the empirical transition distribution given by $\widehat{\cP}_t(s'|s,a,h)\coloneqq\frac{\widehat{m}_t(s,a,s',h)}{\widehat{n}_t(s,a,h)}$. Then the event that there is an episode $t$ and $s,a,h\in \cS\times\cA\times[H]$ such that \begin{align*} \left| \left(\widehat{\cP}_t(s,a,h) - \cP(s,a,h)\right)V^* \right| > H \SamplingConfSign \end{align*} happends with probability at most $\beta/5$. \end{lemma} \begin{lemma} Then the event that there is an episode $t$ and $s,a,h\in \cS\times\cA\times[H]$ such that \begin{align*} \left| \widetilde{n}_t(s,a,h) - \widehat{n}_t(s,a,h) \right| > E_{\eps} \end{align*} happends with probability at most $\beta/5$. \end{lemma} \begin{definition} We define the fail event $F$ as the event that one of the events defined in lemmas \ref{appex:lem:nfail}, \ref{appex:lem:rewardfail}, \ref{appex:lem:Vfail} is realized. After applying union bound we get that the fail event $F$ occurs with probability at most $\beta$. \end{definition} \begin{definition}\label{appex:def:failevents} \text{Let } $$E_{\eps} = \frac{3}{\eps}H\log\left(\frac{2SAH+S^2AH}{\beta'}\right)\log\left(\Tmax\right)^{5/2}$$ and define the following fail event: $$F = \bigcup_t \left[ F_t^N \cup F_t^R F_t^V \cup F_t^{PR} \cup F_t^{PN} \cup F_t^{PM} \right]$$ \noindent where \begin{align} F_t^N &= \bigg\{ \exists s,a,h: \widehat{n}_t(s,a,h) < \frac{1}{2} \sum_{i<t} w_{i,h}(s,a) \\ &\quad\quad\quad \quad\quad-\ln\frac{SAH}{\beta'}\bigg\} \\ F_t^R &= \Bigg\{ \exists s,a,t : \left| \frac{\widehat{r}(s,a,h)}{\widehat{n}(s,a,h)} - r(s,a,h)\right| \geq \\ &\quad\quad \sqrt{\frac{\left( 2\ln\ln(\widehat{n}_t(s,a,h)) + \ln\frac{3SAH}{\beta'} \right)}{\widehat{n}_t(s,a,h)} } \Bigg\}\\ F_t^V &= \bigg\{ \exists{s,a,h} : |(\hat{\mathcal{P}}_t(s,a,h) - \mathcal{P}(s,a,h))^{\top} V_{h+1}^*| \geq \\ &\quad\quad\quad H\sqrt{ \frac{\left( 2\text{llnp}( \widehat{n}_t(s,a,h))+ \ln\frac{3SAH}{\beta'} \right)}{\widehat{n}_t(s,a,h)}} \bigg\}\\ F_t^{PR} &= \left\{ \exists{s,a,h} : |\widetilde{r}_t(s,a,h) - \widehat{r}_t(s,a,h)| \geq E \right\}\\ F_t^{PN} &= \left\{ \exists{s,a,h} : |\widetilde{n}_t(s,a,h) - \widehat{n}_t(s,a,h)| \geq E \right\}\\ F_t^{PM} &= \{ \exists{s,a,s',h} : \\ &\quad\quad\quad|\widetilde{m}_t(s,a,s',h) - \widehat{m}_t(s,a,s',h)| \geq E \} \end{align} \end{definition} \subsection{Nice episodes} \begin{definition}[Definition 2 in \cite{dann2017unifying}] Let $w_{t,h}(s',a')$ be the probability of visiting state $s'$ and taking action $a'$ during episode $t$ and time-step $h$ after following policy $\pi_t$. An episode $t$ is nice if and only if for all $s,s'\in \cS$, $a,a'\in\cA$ and $h\in [H]$ the following two conditions hold: $$w_{t,h}(s,a) \leq w_{min} \quad \vee \quad \frac{1}{4}\sum_{i<t} w_{i,h}(s,a) \geq \ln\frac{SAH}{\beta'} + E_{\eps}$$ \end{definition} \begin{lemma}[]\label{lem:niceepisode} Let $\widetilde{n}_{t}(s,a, h)$ be the value of $\widetilde{n}(s, a, h)$ after planning in episode $t$. Then, if an episode $t$ is nice, then on $F^c$ for all $s\in\cS$, $a\in\cA$ and $h\in[H]$ the following holds: $$w_{t,h}(s,a) \leq w_{min} \quad \vee \quad \widetilde{n}_t(s,a,h) \geq \frac{1}{4}\sum_{i<t} w_{i,h}(s,a)$$ \end{lemma} \begin{proof} Since we consider the event ${F_t^N}^c$ and event ${F_t^{PN}}$, it holds for all $s,a,h$ triples with $w_{t,h}(s,a)>w_{min}$ \begin{align*} \widetilde{n}_t(s,a,h)\geq \frac{1}{2}\sum_{i<k}w_{i,h}(s,a) -\ln\frac{SAH}{\beta'} - E_{\eps} \\ \geq \frac{1}{4}\sum_{i<t} w_{i,h}(s,a) \end{align*} \end{proof} \begin{lemma}[Lemma E.1 in \cite{dann2017unifying}] \label{appex:lem:notnice} On the good event $F^c$, the number of episodes that are not nice is at most $$\frac{120S^2AH^4}{\alpha\varepsilon}\mathrm{polylog}(S,A,H, 1/\beta)$$ \end{lemma} \begin{proof} If an episode $t$ is not nice, then there is $s,a,h$ with $w_{t,h}(s,a)>w_{min}$ and $\sum_{i<t} < \ln\left(\frac{4SAH}{\beta'}\right) + 4E_{\eps}$. With $E_{\eps} \coloneqq \frac{3H}{\varepsilon} polylog(S,A,H)$ Since the sum of this inequality increases by at least $w_{min} \coloneqq \frac{\alpha}{4SH^2}$ when this happens and the right hand side stays constant, this situation can occur at most \begin{align*} \frac{4SAH}{w_{min}}\left( \ln\frac{SAH}{\beta'} + E_{\eps} \right) \\ \leq \frac{120S^2AH^4}{\alpha\varepsilon} \mathrm{polylog}(S,A,H, 1/\beta) \end{align*} \end{proof} \begin{lemma}[Main rate lemma. Lemma E.2 in \cite{dann2017unifying}] \label{appex:lem:mainrate} Let $r\geq 1$ fix and $C>0$ which can depend polynomially on que relevant quantities and $\alpha'>0$ and let $D\geq D$ which can depend poly-logarithmically on the relevant quantities. Then $$\sum_{h}^H\sum_{s,a\in L_{t,k}}w_{t,h}(s,a)\left( \frac{C(\llnp{n_t(s,a,h)} + D)}{n_t(s,a,h)} \right)^{1/r}\leq \alpha'$$ on all but at most $$\frac{8CSAH^r}{(\alpha')^r}\text{polylog}(S,A,H,(\beta')^{-1}, (\alpha')^{-1})$$ nice episodes. \end{lemma} \begin{lemma}[Privacy rate. similar to Lemma E.2 in \cite{dann2017unifying}] \label{appex:lem:privacyrate} Fix $C>0$ and $\alpha'>0$. Let $E$ be the error bound of the counting mechanisms on all episodes such that for any $s,a,h$ $$|\widetilde{n}(s,a,h)-\widehat{n}(s,a,h)| \leq E$$ then $$\sum_{h}^H\sum_{s,a\in L_{t,k}}w_{t,h}(s,a) \frac{CE}{\widetilde{n}_t(s,a,h)} \leq \alpha'$$ \ on all but at most $$\frac{SAHCE}{\alpha'}\text{polylog}(S,A,H,(\beta')^{-1}, (\alpha')^{-1})$$ nice episodes. \end{lemma} \begin{proof} Define $$\Delta_t = \sum_{h}^H\sum_{s,a\in L_{t,k}}w_{t,h}(s,a) \frac{CE_t}{\widetilde{n}_t(s,a,h)}$$ Using lemma \ref{lem:niceepisode} and the property of nice episodes and the fact \begin{equation} \begin{aligned} \sum_{i<t} w_{i,h}(s,a) &\geq 4\ln \frac{SAH}{\delta'} \geq 2 \\ \end{aligned}\end{equation} which implies \begin{equation} \begin{aligned} 2\sum_{i<t} w_{i,h}(s,a) &\geq 2 + \sum_{i<t} w_{i,h}(s,a)\\ \implies 2\sum_{i<t} w_{i,h}(s,a) &\geq w_{t,h}(s,a)+ \sum_{i<t} w_{i,h}(s,a)\\ \implies \sum_{i<t} w_{i,h}(s,a) &\geq \frac{1}{2} \sum_{i\leq t} w_{i,h}(s,a)\\ \end{aligned}\end{equation} we have $$\widetilde{n}_t(s,a,h) \geq \frac{1}{4}\sum_{i<t} w_{i,h}(s,a) \geq \frac{1}{8} \sum_{i\leq t} w_{i,h}(s,a)$$ We can bound the gap as follows \begin{equation*} \Delta_t \leq 8\sum_{h}^H\sum_{s,a\in L_{t,k}}w_{t,h}(s,a) \frac{CE_t}{\sum_{i\leq t} w_{i,h}(s,a)} \end{equation*} Assume that the gap on episode $t$ is $\Delta_t > \alpha'$. In this cas there exist at least one $(s,a,h)$ with $w_{t,h}(s,a)>w_{min}$ and \begin{equation}\begin{aligned}\label{eq:} 8SAH\frac{CE_t}{\sum_{i\leq t} w_{i,h}(s,a)} > \alpha'\\ \implies 8CSAH^2\log(1/\delta')\frac{\log(t)^{5/2}}{\sum_{i\leq t} w_{i,h}(s,a)} > \alpha'\\ \implies \frac{8CSAH^2}{\alpha'} > \frac{\sum_{i\leq t} w_{i,h}(s,a)}{\log(t)^{5/2}} \end{aligned} \end{equation} \end{proof} \subsection{Optimally gap} This section provides the main analysis of the PAC sample complexity. We procede by using optimism of the Q-value policy. \begin{lemma}{$Q$-optimism}\label{appex:lem:optimism} On the event $F^c$, the noisy Q-function $\widetilde{Q}$ is an optimistic estimator of the true value policy $Q^*$. That is, with high probability, for all $s,a\in\cS\times\cA$, we have $\widetilde{Q}(s, a, h) \geq Q^*(s,a, h)$ \end{lemma} First we provide a lemma and two claims that will be used to prove lemma \ref{lem:optimism}. \begin{claim}\label{claim:fracbound} Given any $\alpha>0$, let $n,E >0$. If $n\geq \frac{(1+\alpha)E}{\alpha}$, then $$\frac{1}{n-E} \leq \frac{1+\alpha}{n}$$ \end{claim} \begin{claim}\label{claim:oneOverN} For any $n>0$ and $0\leq E< n$, we have that $$\frac{1}{n-E} \leq \frac{1}{n} + \frac{e + e^2}{n^2}$$ \end{claim} \begin{proof}{(of claim \ref{claim:oneOverN})} Case 1: $n-1 \leq e$: We have that $n-1 \leq e$ \begin{align*} \frac{1}{n} + \frac{e}{n^2} + \frac{e^2}{n^2} \geq \frac{1}{n} + \frac{n-1}{n} + \frac{(n-1)^2}{n^2} \\ = \frac{1}{n} + 1 - \frac{1}{n} + \frac{(n-1)^2}{n^2} = 1 + \frac{(n-1)^2}{n^2} \geq 1 = \\ \frac{1}{\max(1,n-e)} \end{align*} Case 2: $n-e>1$: We have that $\left(\frac{1}{n-e}\right) < 1$ \begin{align*} \frac{1}{n-e} &= \frac{1}{n}+ \frac{e}{n^2} + \frac{e^2}{n^3}+\ldots \quad \quad (\text{Taylor expansion})\\ &= \frac{1}{n}+\frac{e}{n^2}+\frac{e^2}{n^2}\left(\frac{1}{n}+\frac{e}{n^2}+\frac{e^2}{n^3}+\ldots \right) \\ &= \frac{1}{n}+\frac{e}{n^2}+\frac{e^2}{n^2}\left(\frac{1}{n-e}\right) \\ &< \frac{1}{n}+\frac{e}{n^2}+\frac{e^2}{n^2} \quad\quad (\text{use } 1/(n-e) < 1 ) \end{align*} \end{proof} \begin{claim}\label{claim:qlowerbound} Given a target accuracy $\alpha'$. Let $E$ be the error bound from the $\BM{.}$ for round $t$. Then on the event $F^c$, for all $a\in\cA$, $s,s' \in \cS$, $h \in [H]$, if $\widetilde{n}(s,a,h)>\frac{(1+\alpha')E}{\alpha'}$ we have \begin{align} \frac{\widetilde{r}(s,a,h) + E + \sum_{s' \in \cS} \widetilde{V}_h(s')(\widetilde{m}(s,a, s' , h) + E) }{\max(1, \widetilde{n}(s,a,h) - E)} \\ \leq \frac{\widetilde{r}(s,a,h) + \sum_{s'\in \cS}\widetilde{V}(s')\widetilde{m}(s,a,s',h)}{\widetilde{n}(s,a,h)}\\ \quad\quad+ \frac{(1+\alpha')(E + HSE)}{\widetilde{n}(s,a,h)} + (H+1)\alpha' \end{align} \end{claim} \begin{lemma}\label{appex:lem:Qhat} Let $\widehat{Q}$ be the optimistic empirical Q-value of algorithm \ref{alg:privateplanning} before adding noise, defined by \begin{align*} \widehat{Q}(s,a,h) = \frac{\widehat{r}(s,a,h) + \sum_{s'\cS} \widetilde{V}_h(s')\widehat{m}(s,a,s', h)}{\widehat{n}(s,a,h)} \\ + \phibound \\ + (H-h)\phibound \end{align*} then on any time step for all $s,a,h \in \cS\times\cA\times [H]$, \begin{align} \widetilde{Q}(s,a,h) \geq \widehat{Q}(s,a,h) \end{align} \end{lemma} \begin{proof} On event $F^c$ we get from definition \ref{def:failevents} that $|\widetilde{r}(s,a,h) - \widehat{r}(s,a,h)| \leq E$, $|\widetilde{n}(s,a,h) - \widehat{n}(s,a,h)| \leq E$, and $|\widetilde{m}(s,a,s', h) - \widehat{m}(s,a,s',h)| \leq E$. Therefore we can upper bound $\widehat{Q}$ by \begin{align*} \widehat{Q}(s,a,h)\\ \leq \frac{\widetilde{r}(s,a,h) + E + \sum_{s'\cS} \widetilde{V}_h(s')(\widehat{m}(s,a,s', h) + E) }{\widehat{n}(s,a,h) - E} \\ + \phi + (H-h)\phi\ \end{align*} where $\phi = \phiboundWithE$. Then using claim \ref{claim:qlowerbound} with $\alpha' = \frac{\alpha}{5H(H+1)}$ we have can upper bound the first term of the equation: \begin{align*} \widehat{Q}(s,a,h) \leq \frac{\widetilde{r}(s,a,h) + \sum_{s'\in \cS}\widetilde{V}(s')\widetilde{m}(s,a,s',h)}{\widetilde{n}(s,a,h)}\\ \quad\quad+ \frac{(1+\alpha')(E + HSE)}{\widetilde{n}(s,a,h)} + \frac{\alpha }{5H} + \phi + (H-h)\phi \\ \equiv \widetilde{Q}(s,a,h) \end{align*} \end{proof} \begin{lemma}[Value function optimism]\label{appex:lem:Voptimism} Fix any episode $t$. On the event $F^c$, the value function from algorithm \ref{alg:privateplanning} is optimismtic. i.e. for all $s\in\cS$ and all $h\in[H]$ $$\widetilde{V}_h(s) \geq V^*_{h}(s)$$ \end{lemma} \begin{proof} The proof proceeds by induction. Fixing any state $s\in\cS$, we must show that $\widetilde{V}_h(s)\geq V^*_h(s)$ for all $h\in[H]$. For the base case, note that $\widetilde{V}_{H+1}(s)=V^*_h(s)=0$. Now assume that for any $h\leq H$, $\widetilde{V}_{h+1}(s) \geq V_{h+1}^*(s)$. Then we must show that $\widetilde{V}_h(s) \geq V_h^*(s)$: First write out the equation for $V^*_h(s)$: \begin{align}\label{eq:vstar} V^*_h(s) = \max_{a} \left( r(s,a,h) + P(s,a,h)V^*_{h+1} \right) \end{align} Let $a^*$ be the action corresponding to equation ($\ref{eq:vstar}$). Next we write out the equation for $\widetilde{V}_h(s)$ \begin{align*} \widetilde{V}_h(s) &= \max_{a} \frac{\widetilde{r}(s,a,h)+ \sum_{s'} \widetilde{V}_{h+1}\widetilde{m}(s,a,s',h)}{\widetilde{n}(s,a,h)} \\ &\quad\quad + \widetilde{\conf}(s,a,h) \\ &\geq \frac{\widetilde{r}(s,a^*,h)+ \sum_{s'} \widetilde{V}_{h+1}\widetilde{m}(s,a^*,s',h)}{\widetilde{n}(s,a^*,h)} \\ &\quad\quad + \widetilde{\conf}(s,a^*,h) \\ & \coloneqq \widetilde{Q}(s,a^*,h) \end{align*} Next we use lemma \ref{lem:optimismQhat} which says that on event $F^c$, $\widetilde{Q}(s,a^*,h)\geq \widehat{Q}(s,a^*,h)$ to get a lower bound for $\widetilde{V}_h$: \begin{align*} \widetilde{V}_h(s) \geq \frac{\widehat{r}(s,a^*,h) + \sum_{s'\cS} \widetilde{V}_h(s')\widehat{m}(s,a^*,s', h)}{\widehat{n}(s,a^*,h)} \\ + (H+1)\phihatconfL{s,a^*,h} \end{align*} Letting \begin{align*} \frac{\sum_{s'\cS} \widetilde{V}_h(s')\widehat{m}(s,a^*,s', h)}{\widehat{n}(s,a^*,h)} = \widehat{P}(s,a^*,h)\widetilde{V}_{h+1} \end{align*} and applying the inductive step (i.e. $\forall_s \widetilde{V}_{h+1}(s)\geq V^*_{h+1}(s)$) we get \begin{align*} &\widetilde{V}_h(s) \geq \frac{\widehat{r}(s,a^*,h)}{\widehat{n}(s,a^*,h)} + \widehat{P}(s,a^*,h)V^*_{h+1} + \\ &\quad\quad (H+1)\phihatconfL{s,a^*,h} \end{align*} Next we use the concentration bound from definition \ref{def:failevents} \begin{align*} \widehat{P}(s,a^*,h)V^*_{h+1}\geq P(s,a^*,h)V^*_{h+1} - (H)\widehat{\phi}(s,a^*, h) \end{align*} and then we use the definition of $V^*_h(s)$ \begin{align*} P(s,a^*,h)V^*_{h+1} = - r(s,a^*, h) +V^*_{h}(s) \end{align*} to get \begin{align*} &\widetilde{V}_h(s) \\ &\geq \frac{\widetilde{r}(s,a^*,h)}{\widetilde{n}(s,a^*,h)} + P(s,a^*,h)V^*_{h+1} + \widehat{\phi}(s,a^*, h) \\ &= \frac{\widetilde{r}(s,a^*,h)}{\widetilde{n}(s,a^*,h)} - r(s,a^*, h) + \widehat{\phi}(s,a^*, h) + V^*_{h}(s) \end{align*} Next note that on event $F^c$, we have \begin{align*} \frac{\widetilde{r}(s,a^*,h)}{\widetilde{n}(s,a^*,h)} - r(s,a^*, h) + \widehat{\phi}(s,a^*, h)> 0 \end{align*} Hence it follows that $\widetilde{V}_h(s) \geq V_h^*(s)$, completing the proof. \end{proof} \begin{proof}{of lemma \ref{lem:optimism}} Let $\widehat{Q}$ be the optimistic empirical Q-value before adding noise. On lemma \ref{lem:Qhat}, we showed that $\widetilde{Q}(s,a,h) \geq \hat{Q}(s,a,h) $ $\forall s,a,h$. Next, it only remains to show that $\widehat{Q} \geq Q^*$. Let the empirical mean reward be $\bar{r}(s,a,h) = \frac{\widehat{r}(s,a,h)}{\widehat{n}(s,a,h)}$ and let $\hat{P} \widetilde{V}_{h+1} = \frac{\widetilde{V}_h(s')(\widehat{m}(s,a,s', h)}{\widehat{n}(s,a,h)}$. No we can write $\widehat{Q}$ as $$\widehat{Q}(s,a,h) = \bar{r}(s,a,h) + \hat{P}\widetilde{V}_{h+1}$$ \noindent On the event $F^c$ we have that $\frac{\widehat{r}(s,a,h)}{\widehat{n}(s,a,h)} - r(s,a,h) \leq \phi$ and $(\widehat{P} - P )V^*_{h+1} \leq H \phi$. Furthermore, from the value function optimism lemma (\ref{lem:Voptimism}) we have that for all $s \in \cS$, and all $h\in[H]$, $\widetilde{V}_h(s) \geq V_h^*(s)$. Putting it all together: \begin{align} &\widehat{Q}(s,a,h) - Q^*(s,a,h)\\ & = \bar{r}(s,a,h) - r(s,a,h) + \widehat{P}\widetilde{V}_{h+1} - P V^*_{h+1}\\ & \quad\quad+ (H-h+1)\phi \\ &\geq \bar{r}(s,a,h) - r(s,a,h) + (\widehat{P} - P )V^*_{h+1} \\ & \quad\quad+ \phi + (H-h)\phi \\ &\geq 0 \end{align} \end{proof} \begin{lemma} \label{appex:lem:optgap} Let $\pi_t$ be the policy played by algorithm \ref{alg:prl} during episode $t$. Let $w_{t,h}(s,a)$ be the probability of visiting $s$ and taking action $a$ on episode $t$ and time $h\in[H]$. Then the optimality gap is bounded by \begin{equation}\begin{aligned} V^\star - V^\pi_t &\leq \sum_{h=1}^H \mathbb{E}_{s_h \sim \pi_t} \widetilde{\conf}(s_h,\pi_t(s_h)) \\ &\leq \sum_{h=1}^H \sum_{s',a'\in\cS}w_{t,h}(s',a') \widetilde{\conf}(s_h,\pi_t(s_h)) \\ \end{aligned}\end{equation} \end{lemma} \begin{proof} \noindent Let $\mathbb{E}_{s_h \sim \pi_t}\widetilde{r}_h $ be the expected reward received during time step $h \in [H]$ given that we follow policy $\pi_t$. Let $s_1, \ldots, s_H$ be random variables, where each $s_h$ represents the state visited during time-step $h$ after following policy $\pi_t$. Next observe that \begin{align}\label{eq:qtilinequality} \left| \mathbb{E}_{\pi_t}\widetilde{Q}_1(s_1,\pi_t(s_1)) - \mathbb{E}_{\pi_t}\left( \widetilde{r}_1 + \widetilde{Q}_2(s_2,\pi_t(s_2)) \right) \right| \\ \leq \mathbb{E}_{\pi_t}\widetilde{\conf}(s_1,\pi_t(s_1)) \end{align} \noindent Equation \ref{eq:qtilinequality} can be verified by rewriting the two terms as: $$\mathbb{E}_{\pi_t} \widetilde{Q}(s_1, \pi_t(s_1)) = \mathbb{E}_{\pi_t}\widetilde{r}_1 + \mathbb{E}_{\pi_t} \widetilde{V}(s_2) + \mathbb{E}_{\pi_t}\widetilde{\conf}(s_1, a_1, 1)$$ \noindent and $$\mathbb{E}_{\pi_t} \widetilde{Q}_2(s_2, \pi_t(s_2)) = \mathbb{E}_{\pi_t} \widetilde{V}(s_2)$$ \noindent Then the optimality gap on episode $t$ is \begin{equation}\label{eq:gapboundA} \begin{aligned} V^\star - V^\pi_t &= V^\star - \sum_{h=1}^H \mathbb{E}_{\pi_t}r_h \\ &= \mathbb{E}_{\pi_t} Q_1^\star(s_1,\pi^ \star(s_1)) - \sum_{h=1}^H \mathbb{E}_{\pi_t}r_h \\ & (\text{Optimism}) \\ &\leq \mathbb{E}_{\pi_t} \widetilde{Q}_1(s_1,\pi^*(s_1)) - \sum_{h=1}^H \mathbb{E}_{\pi_t}r_h \\ & (\text{Greedy of policy } \pi_t) \\ &\leq \mathbb{E}_{\pi_t} \widetilde{Q}_1(s_1,\pi_t(s_1)) - \sum_{h=1}^H \mathbb{E}_{\pi_t}r_h \\ &\leq \mathbb{E}_{\pi_t} \widetilde{Q}_1(s_1,\pi_t(s_1)) - \mathbb{E}_{\pi_t}r_1 - \sum_{h=2}^H \mathbb{E}_{\pi_t}r_h \\ & (\text{Equation \ref{eq:qtilinequality}}) \\ &\leq \mathbb{E}_{ \pi_t} \widetilde{\conf}(s_1,\pi_t(s_1), 1) + \mathbb{E}_{\pi_t} \widetilde{Q}_2(s_2,\pi_t(s_2)) \\ &\quad \quad - \sum_{h=2}^H \mathbb{E}_{\pi_t}r_h \end{aligned} \end{equation} \noindent Since $\widetilde{Q}_{H+1}(s_h, a_h) = 0$, applying equation (\ref{eq:qtilinequality}) $H-1$ more times, we get \begin{equation}\begin{aligned} (\text{equation } \ref{eq:gapboundA}) &\leq \sum_{h=1}^H \mathbb{E}_{s_h \sim \pi_t} \widetilde{\conf}(s_h,\pi_t(s_h), h) \end{aligned}\end{equation} \end{proof} \section{Other proofs} Proof of claim \ref{claim:oneoverNbound}. \begin{claim}\label{appex:claim:oneoverNbound} Let $e \in \mathbb{R}$ be any positive real number. Then for all $x \in \mathbbm{R}$ with $x\geq 2e$ it holds that \begin{align} \label{eq:oneoverNinequality} \frac{1}{x - e} \leq \frac{1}{x} + \frac{2e}{x^2} \end{align} \end{claim} \begin{proof} To prove lemma \ref{claim:oneoverNbound} we will induction on the positive real numbers following the tools from \ref{clark2012instructor}. This case procceds by induction. The base case $x =2e$ is easy to show. \begin{align*} \frac{1}{x} + \frac{2e}{x^2} = \frac{1}{2e} + \frac{2e}{(2e)^2} = \frac{1}{2e} + \frac{1}{2e} = \frac{1}{e} = \frac{1}{x-y} \end{align*} where the last equality follows because $x=2e$. Thus we have shown that inequality \ref{eq:oneoverNinequality} holds when $x = 2e$. For the inductive step we must show that for any $z\geq 2e$ if $\frac{1}{x-e} \leq \frac{1}{x} + \frac{2e}{x^2}$ holds on all $x\in [2e, z]$ then $\frac{1}{y-e} \leq \frac{1}{y} + \frac{2e}{y^2}$ holds on all $y\in [z, w)$ for some some $w>z$. Secondly we must show that for any $z> 2e$, if $\frac{1}{x-e} \leq \frac{1}{x} + \frac{2e}{x^2}$ holds on all $x\in [2e, z)$ then $\frac{1}{z-e} \leq \frac{1}{z} + \frac{2e}{z^2}$ holds. We proceed by contradiction: Let $z \geq 2e$. For the first step let $x \in [2e, z]$ and $y\in [z, w)$ for some $w>z$. Then assume that $\frac{1}{x-e} \leq \frac{1}{x} + \frac{2e}{x^2}$ holds and that $\frac{1}{y-e} > \frac{1}{y} + \frac{2e}{y^2}$. \begin{align} \notag &\frac{1}{y-e} > \frac{1}{y} + \frac{2e}{y^2} \\ \notag \Leftrightarrow & \frac{y^2}{y-e} > y + 2e && \text{Multiply by $y^2$}\\ \notag \Leftrightarrow & \frac{y^2}{y-e} + (x-y)> x + 2e \\ \notag \Leftrightarrow & \frac{y^2}{(y-e)x^2} + \frac{(x-y)}{x^2} > \frac{1}{x} + \frac{2e}{x^2} && \text{Divide by $x^2>0$}\\ \notag \Leftrightarrow & \frac{y^2}{(y-e)x^2} + \frac{(x-y)}{x^2} > \frac{1}{x-e} && \text{Apply inductive assumption} \\ \notag \Leftrightarrow & y^2 > \frac{(y-e)x^2}{x-e} -(y-e)(x-y) && \text{Multiply by $(y-e)x^2$} \\ \notag \Leftrightarrow & y^2 > \frac{(y-e)x^2}{x-e} + y^2 - ye - xy + xe && \text{Multiply by $(y-e)x^2$} \\ \notag \Leftrightarrow & y(x+e) > \frac{(y-e)x^2}{x-e} + xe && \text{Expand} \\ \notag \Leftrightarrow & y(x+e)(x-e) > (y-e)x^2 + xe(x-e) && \text{Multiply by $(x-e)$} \\ \notag \Leftrightarrow & yx^2 -yex + yex - ye^2 > yx^2-ex^2 + ex^2 -xe^2 && \text{Expand} \\ \notag \Leftrightarrow & - ye^2 > -xe^2 && \text{Simplify} \\ \label{eq:contradiction} \Leftrightarrow & x > y && \text{Divide by $e^2$} \end{align} Equation \ref{eq:contradiction} contradicts the assumption that $y\geq x$. Therefore we have shown that $\frac{1}{y-e} \leq \frac{1}{y} + \frac{2e}{y^2}$ holds. For the next step in the proof, let $x\in [2e, z)$ and assume $\frac{1}{x-e} \leq \frac{1}{x}+ \frac{2e}{x^2}$, then we must show that $\frac{1}{z-e} \leq \frac{1}{z}+ \frac{2e}{z^2}$. To show this we apply the same derivation as in the previous step to arrive at the contradiction $x>z$ which completes the proof. \end{proof} \subsection{Nice episodes} The goal in this section is to bound the number of suboptimal episodes. We use a similar approach as in \cite{dann2017unifying} which uses the concept of nice episodes but we modify their definition of nice episodes to to account for the noise the algorithm adds in order to preserve privacy. We formally define nice episodes in definition \ref{def:nice}. The rest of the proof proceeds by bounding the number of episodes that are not nice and bounding the number of nice suboptimal episodes. Recal that $\widetilde{n}_t(s,a,h)$ represents the private count of the number of times state triplet $s,a,h$ has been visited right before episode $t$. And $E_{\eps}$ is the error of the $\varepsilon$-differentially private counter, that is, on any episode $t$ \[ \left|\widetilde{n}_t(s,a,h) - \widehat{n}_t(s,a,h) \right| < E_{\eps} \] where $\widehat{n}_t(s,a,h)$ is the true count. \begin{definition}[Nice Episodes. Similar to definition 2 in \cite{dann2017unifying}] \label{def:nice} Let $w(s,a,h)$ be the probability of visiting state $s$ and taking action $a$ during episode $t$ and time-step $h$ after following policy $\pi_t$. An episode $t$ is nice if and only if for all $s,\in \cS$, $a,\in\cA$ and $h\in [H]$ the following two conditions hold: \begin{align*} w_t(s,a, h) \leq w_{min} \quad \vee \quad \frac{1}{4}\sum_{i<t} w_{i}(s,a,h) \geq \ln\frac{SAH}{\beta'} + 2E_{\eps} \end{align*} \end{definition} \begin{lemma}\label{lem:niceproperties} If an episode $t$ is nice, then on $F^c$ for all $s,a,h$ the following statement holds \begin{align*} w_t(s,a,h) < w_{min} \quad\vee\quad \widetilde{n}_t(s,a,h) > \frac{1}{4}\sum_{i<t} w_{i}(s,a,h) + E_{\eps} \end{align*} Plus, it follows that if $w_t(s,a,h)>w_{min}$ then $\widetilde{n}_t(s,a,h)>2E_{\eps}$. \end{lemma} \begin{proof} Since we consider the event $F^c$ it holds for all $s,a,h$ triplets \[ \widehat{n}_t(s,a,h) > \frac{1}{2}\sum_{i<t} w_{i}(s,a,h) - \ln\frac{SAH}{\delta'} \] and \begin{align*} \widetilde{n}_t(s,a,h) > \widehat{n}_t(s,a,h) - E_{\eps} > \frac{1}{2}\sum_{i<t} w_{i}(s,a,h) - \ln\frac{SAH}{\delta'}- E_{\eps} > \frac{1}{4}\sum_{i<t} w_{i}(s,a,h) \end{align*} \end{proof} \begin{lemma}[Non-nice Episodes. \cite{dann2017unifying}] \label{lem:notnice} On the good event $F^c$, the number of episodes that are not nice is at most \[ \frac{120S^2AH^4}{\alpha\varepsilon}\mathrm{polylog}(S,A,H, 1/\beta) \] \end{lemma} \begin{lemma}[Nice Episodes rate. \cite{dann2017unifying}] \label{lem:mainrate} Let $r\geq 1$ and fix $C>0$ which can depend polynomially on the relevant quantities and let $D\geq 1$ which can depend poly-logarithmically on the relevant quantities. Finally let $\alpha'>0$ be the target accuracy and let $\widetilde{n}_t(s,a,h)$ be the private estimate count with error $E_{\eps}$. Then \begin{align*} \sum_{(s,a,h)\notin L_{t}}w_h(s,a,h) \left( \frac{C(\log{(T)} + D)}{\widetilde{n}_t(s,a,h) - E_{\eps}} \right)^{1/r} \leq \alpha' \end{align*} on all but at most \begin{align*} \frac{8CSAH^r}{(\alpha')^r}\mathrm{polylog}(T,S,A,H,1/\varepsilon,1/\beta', 1/\alpha') \end{align*} nice episodes. \end{lemma} \begin{proof} The proof follows mostly from the argument in \cite[Lemma E.3]{dann2017unifying}. Let $x\coloneqq (s,a,h)$ denote a state tuple. Define the gap in episode $t$ by \begin{align*} \Delta_t =\sum_{\text{x}\notin L_t}w_t(\text{x})\left(\frac{C(\log(T)+D)}{\widetilde{n}_t(\text{x})-E_{\eps}}\right)^{\tfrac{1}{r}} =\sum_{\text{x}\notin L_t}w_t(\text{x})^{1-\tfrac{1}{r}} \left(w_t(\text{x})\frac{C(\log(T)+D)}{\widetilde{n}_t(\text{x})-E_{\eps}}\right)^{\tfrac{1}{r}} \end{align*} Using H\"{o}lder's inequality \begin{align*} \Delta_t \leq \left(\sum_{\text{x}\notin L_t}C H^{r-1}w_t(\text{x})\frac{C(\log(T)+D)}{\widetilde{n}_t(\text{x})-E_{\eps}}\right)^{\tfrac{1}{r}} \end{align*} Now we the properties of nice episodes from lemma \ref{lem:niceproperties} and the fact that $\sum_{i<t}w_t(\text{x}) \geq 4\ln(SAH/\delta')\geq 2$. Then on the good event $F^c$ we have the following bound \begin{align*} \widetilde{n}_t(\text{x}) \geq \frac{1}{4}\sum_{i<t}w_i(\text{x}) + E_{\eps} \geq \frac{1}{8}\sum_{i\leq t}w_i(\text{x}) + E_{\eps} \end{align*} The function $\frac{\ln(T) + D}{ x}$ is monotonically decreasing for $x\geq 0$. Then we bound \begin{align*} \Delta_t^r &\leq\sum_{\text{x}\notin L_t}C H^{r-1}w_t(\text{x})\frac{C(\log(T)+D)}{\widetilde{n}_t(\text{x})-E_{\eps}}\\ &\leq 8C H^{r-1}\sum_{\text{x}\notin L_t}w_t(\text{x})\frac{(\log(T)+D)}{\sum_{i\leq t}w_i(\text{x})}\\ \end{align*} Let the set of nice episodes be $N = \left\{ t : w_t(\text{x}) < w_{min} \text{ or } \frac{1}{4}\sum_{i<t} w_i(\text{x}) \geq \ln\frac{SAH}{\beta'} + 2E_{\eps}\right\}$ and define a set $M = \{ t : \Delta_t > \alpha' \}\cap N$ to be the set of suboptimal nice epidoes. We know that $|M|\leq T$. Finally we can bound the total number of suboptimal nice episodes by \begin{align*} \sum_{t\in M} \Delta_t^r &\leq \sum_{t\in M}8C H^{r-1}(\log(T)+D)\sum_{\text{x}\notin L_t}\frac{w_t(\text{x})}{\sum_{i\leq t}w_i(\text{x})} \\ &\leq 8C H^{r-1}(\log(T)+D)\sum_{\text{x}\notin L_t}\sum_{t\in K}\frac{w_t(\text{x})}{\sum_{i\leq t}w_i(\text{x})\mathbbm{1}(w_i(\text{x})>w_{\text{min}})} \end{align*} For every $x=(s,a,h)$ consider the sequence $w_i(\text{x}) \in [w_{\text{min}}, 1]$ with $i \in I = \{ w_i(\text{x}) \geq w_{\text{min}}\}$ and apply lemma \ref{lem:lnbound} to get \begin{align*} \sum_{t\in M}\frac{w_t(\text{x})}{\sum_{i\leq t}w_i(\text{x})\mathbbm{1}(w_i(\text{x})>w_{\text{min}})} \leq \ln\left(\frac{Te}{w_{\text{min}}} \right) \end{align*} Therefore we have \begin{align*} \sum_{t\in M} \Delta_t^r \leq 8C S A H^r(\log(T)+D)\ln\left(\frac{Te}{w_{\text{min}}} \right) \end{align*} \end{proof} Since each episode has to contribute at least $(\alpha')^r$ to this bound we have \begin{align*} |M| \leq \frac{8C S A H^r(\log(T)+D)\ln\left(\frac{Te}{w_{\text{min}}} \right)} {(\alpha')^2} \end{align*} Completing the proof. \begin{lemma}{\cite[Lemma E.5]{dann2017unifying}} \label{lem:lnbound} Let $a_i$ be a sequence taking values in $[a_{min}, 1]$ with $a_{min}>0$ and $m>0$, then $\sum_{k=1}^m \frac{a_i}{\sum_{i=1}^k a_i}\leq \ln(\frac{me}{a_{min}})$ \end{lemma} \section{PAC and Regret Analysis of $\texttt{PUCB}$} Now that we have established $\texttt{PUCB}$ is JDP, we turn to utility guarantees. We establish two forms of utility guarantee namely a PAC sample complexity bound, and a regret bound. In both cases, comparing to \texttt{UBEV}, we show that the price for JDP is quite mild. In both bounds the privacy parameter interacts quite favorably with the ``error parameter.'' We first state the PAC guarantee. \begin{theorem}[PAC guarantee for $\texttt{PUCB}$] \label{thm:PUCBPAC} Let $T$ be the maximum number of episodes and $\varepsilon$ the JDP parameter. Then for any $\alpha \in (0,H]$ and $\beta \in (0,1)$, algorithm $\texttt{PUCB}$ with parameters $(\varepsilon,\beta)$ follows a policy that with probability at least $1-\beta$ is $\alpha$-optimal on all but \begin{align*} O\left(\left(\frac{SAH^4}{\alpha^2} + \frac{S^2AH^4}{\varepsilon\alpha}\right) \mathrm{polylog}\left(T,S,A,H,\tfrac{1}{\alpha},\tfrac{1}{\beta}, \tfrac{1}{\varepsilon}\right)\right) \end{align*} episodes. \end{theorem} The theorem states that if we run $\texttt{PUCB}$ for many episodes, it will act near-optimally in a large fraction of them. The number of episodes where the algorithm acts suboptimally scales polynomially with all the relevant parameters. In particular, notice that in terms of the utility parameter $\alpha$, the bound scales as $1/\alpha^2$. In fact the first term here matches the guarantee for the non-private algorithm \texttt{UBEV} up to polylogarithmic factors. On the other hand, the privacy parameter $\varepsilon$ appears only in the term scaling as $1/\alpha$. In the common case where $\alpha$ is relatively small, this term is typically of a lower order, and so the price for privacy here is relatively low. Analogous to the PAC bound, we also have a regret guarantee. \begin{theorem}[Regret bound for \texttt{PUCB}] \label{thm:PUCBRegret} With probability at least $1-\beta$, the regret of $\texttt{PUCB}$ up to episode $T$ is at most \begin{align*} O\left(\left(H^2\sqrt{SAT} + \frac{SAH^3 + S^2AH^3}{\varepsilon}\right) \mathrm{polylog}\left(T, S, A, H, \tfrac{1}{\beta}, \tfrac{1}{\varepsilon}\right)\right) \enspace. \end{align*} \end{theorem} A similar remark to the PAC bound applies here: the privacy parameter only appears in the $\mathrm{polylog}(T)$ terms, while the leading order term scales as $\sqrt{T}$. In this guarantee it is clear that as $T$ gets large, the utility price for privacy is essentially negligible. We also remark that both bounds have ``lower order'' terms that scale with $S^2$. This is quite common for tabular reinforcement algorithms~\cite{dann2017unifying,azar2017minimax}. We find it quite interesting to observe that the privacy parameter $\varepsilon$ interacts with this term, but not with the so-called ``leading'' term in these guarantees. \paragraph{Proof Sketch.} The proofs for both results parallel the arguments in~\citep{dann2017unifying} for the analysis of \texttt{UBEV}. The main differences arises from the fact that we have adjusted the confidence interval $\widetilde{\conf}$ to account for the noise in the releases of $\widetilde{r},\widetilde{n},\widetilde{m}$. In~\citep{dann2017unifying} the bonus is crucially used to establish optimism, and the final guarantees are related to the over-estimation incurred by these bonuses. We focus on these two steps in this sketch, with a full proof deferred to the appendix. First we verify optimism. Fix episode $t$ and state tuple $(s,a,h)$, and let us abbreviate the latter simply by $\text{x}$. Assume that $\widetilde{V}_{h+1}$ is private and optimistic in the sense that $\widetilde{V}_{h+1}(s) \geq V_{h+1}^*(s)$, for all $s \in \cS$. First define the empirical Q-value \begin{align*} \widehat{Q}_t(\text{x}) = \frac{\widehat{r}_t(\text{x}) + \sum_{s'\in\cS}\widetilde{V}_{h+1}(s')\widehat{m}_t(\text{x},s')}{\widehat{n}_t(\text{x})} \enspace. \end{align*} The optimistic Q-function, which is similar to the one used by~\citep{dann2017unifying}, is given by \begin{align*} \widehat{Q}^{+}_t(\text{x}) = \widehat{Q}_t(\text{x}) + (H+1)\phihatconfL{\text{x}} \enspace, \end{align*} where $\phihatconfL{\text{x}} = \phihatconfR{\text{x}}$. A standard concentration argument shows that $\widehat{Q}^{+}_t\geq Q^\star$, assuming that $\widetilde{V}_{h+1} \geq V^\star_{h+1}$. Of course, both $\widehat{Q}_t$ and $\widehat{Q}^{+}_t$ involve the non-private counters $\widehat{r},\widehat{n},\widehat{m}$, so they are \emph{not} available to our algorithm. Instead, we construct a surrogate for the empirical Q-value using the private releases: \begin{align*} &\widetilde{Q}_t(\text{x})= \frac{\widetilde{r}_t(\text{x}) +\sum_{s'\in\cS}\widetilde{V}_{h+1}(s')\widetilde{m}_t(\text{x},s')}{\widetilde{n}_t(\text{x})} \enspace. \end{align*} Our analysis involves relating $\widetilde{Q}_t$ which the algorithm has access to, with $\widehat{Q}_t$ which is non-private. To do this, note that by the guarantee for the counting mechanism, we have \begin{align} \widehat{Q}_t(\text{x}) \leq\frac{\widetilde{r}_t(\text{x})+E_{\eps} +\sum_{s'\in\cS}\widetilde{V}_{h+1}(s')(\widetilde{m}_t(\text{x},s')+E_{\eps})}{\widetilde{n}_t(\text{x})-E_{\eps}} \enspace.\label{eq:qhat_upper} \end{align} Next, we use the following elementary fact. \begin{claim} \label{claim:main:oneoverNbound} Let $y \in \mathbb{R}$ be any positive real number. Then for all $x \in \mathbbm{R}$ with $x\geq 2y$ it holds that $\frac{1}{x - y} \leq \frac{1}{x} + \frac{2y}{x^2}$. \end{claim} If $\widetilde{n}_t(\text{x}) \geq 2E_{\eps}$, then we can apply claim~\ref{claim:main:oneoverNbound} to equation~\eqref{eq:qhat_upper}, along with the facts that $\widetilde{V}_{h+1}(s') \leq H$ and $\widetilde{r}_t(\text{x}) \leq \widetilde{n}_t(\text{x}) + 2E_{\eps}\leq 2\widetilde{n}_t(\text{x})$, to upper bound $\widehat{Q}_t$ by $\widetilde{Q}_t$. This gives: \begin{align*} \widehat{Q}_t(\text{x}) &\leq \widetilde{Q}_t(\text{x}) + \left(\frac{1}{\widetilde{n}_t(\text{x})} + \frac{2E_{\eps}}{\widetilde{n}_t(\text{x})^2}\right)\cdot(1+SH)E_{\eps}\\ & = \widetilde{Q}_t(\text{x}) + \psitilconfL{\text{x}} \enspace. \end{align*} Therefore, we see that $\widetilde{Q}_t(\text{x})+\psitilconfL{\text{x}}$ dominates $\widehat{Q}_t(\text{x})$. Accordingly, if we inflate by $\phitilconfL{\text{x}}$ -- which is clearly an upper bound on $\phihatconfL{\text{x}}$ -- we account for the statistical fluctuations and can verify optimism. In the event that $\widetilde{n}_t(\text{x}) \leq 2E_{\eps}$, we simply upper bound $Q^* \leq H$. For the over-estimation, the bonus we have added is $\phitilconfL{\text{x}} + \psitilconfL{\text{x}}$, which is closely related to the original bonus $\phihatconfL{\text{x}}$. The essential property for our bonus is that it is not significantly larger than the original one $\phihatconfL{\text{x}}$. Indeed, $\phihatconfL{\text{x}}$ scales as $1/\sqrt{\widetilde{n}_t(\text{x})}$ while $\psitilconfL{\text{x}}$ scales roughly as $E_{\eps}/\widetilde{n}_t(\text{x}) + E_{\eps}^2/\widetilde{n}_t(\text{x})^2$, which is lower order in the dependence on $\widetilde{n}_t(\text{x})$. Similarly, the other sources of error here only have lower order effects on the over-estimation. In detail, there are three sources of error. First, $\phitilconfL{\text{x}}$ is within a constant factor of $\phihatconfL{\text{x}}$ since we are focusing on rounds where $\widetilde{n}_t(\text{x}) \geq 2E_{\eps}$. Second, as the policy suboptimality is related to the bonuses on the states and actions we are likely to visit, we cannot have many rounds where $\widetilde{n}_t(\text{x}) \leq 2E_{\eps}$, since all of the private counters are increasing. A similar argument applies for $\psitilconfL{\text{x}}$: we can ignore states that we visit infrequently, and the private counters $\widetilde{n}_t(\text{x})$ for states that we visit frequently increase rapidly enough to introduce minimal additional error. Importantly, in the latter two arguments, we have terms of the form $E_{\eps}/\widetilde{n}_t(\text{x})$, while $\phihatconfL{\text{x}}$ itself scales as $\sqrt{1/\widehat{n}_t(\text{x})}$, which dominates in terms of the accuracy parameter $\alpha$ or the number of episodes $T$. As such we obtain PAC and regret guarantees where the privacy parameter $\varepsilon$ does not appear in the dominant terms. \section{The $\texttt{PUCB}$ Algorithm} In this section, we introduce the Private Upper Confidence Bound algorithm ($\texttt{PUCB}$), a JDP algorithm with both PAC and regret guarantees. The pseudo-code for $\texttt{PUCB}$ is in algorithm~\ref{alg:pucb}. At a high level, the algorithm is a private version of the \texttt{UBEV} algorithm~\citep{dann2017unifying}. \texttt{UBEV} keeps track of three types of statistics about the history, including (a) the average empirical reward for taking action $a$ in state $s$ at time $h$, denoted $\widehat{r}_t(s,a,h)$, (b) the number of times the agent has taken action $a$ in state $s$ at time $h$, denoted $\widehat{n}_t(s,a,h)$, and (c) the number of times the agent has taken action $a$ in state $s$ at time $h$ and transitioned to $s'$, denoted $\widehat{m}_t(s,a,s',h)$. In each episode $t$, \texttt{UBEV} uses these statistics to compute a policy via dynamic programming, executes the policy, and updates the statistics with the observed trajectory.~\cite{dann2017unifying} compute the policy using an optimistic strategy and establish both PAC and regret guarantees for this algorithm. \input{pseudocode/PUCB} Of course, as the policy depends on the statistics from the previous episodes, $\texttt{UBEV}$ as is does not satisfy JDP. On the other hand, the policy executed only depends on the previous episodes \emph{only} through the statistics $\widehat{r}_t,\widehat{n}_t,\widehat{m}_t$. If we maintain and use private versions of these statistics, and we set the privacy level appropriately, we can ensure JDP. To do so $\texttt{PUCB}$ initializes one private counter mechanism for each $\widehat{r}_t, \widehat{n}_t,\widehat{m}_t$ ($2SAH + S^2AH$ counters in total). At episode $t$, we compute the policy using optimism as in $\texttt{UBEV}$, but we use only the private counts $\widetilde{r}_t,\widetilde{n}_t,\widetilde{m}_t$ released from the counter mechanisms. We require that each set of counters is $(\varepsilon/3)$ JDP, and so with $$E_{\eps} = \frac{3}{\eps}H\log\left(\frac{2SAH+S^2AH}{\beta'}\right)\log\left(\Tmax\right)^{5/2},$$ we can ensure that with probability at least $1-\beta$: \begin{align*} \forall t \in [T]: \left|\widetilde{n}_t(s,a,h) - \widehat{n}_t(s,a,h)\right| < E_{\eps} \enspace, \end{align*} where $\widehat{n}_t,\widetilde{n}_t$ are the count and release at the beginning of the $t$-th episode. The guarantee is uniform in $(s,a,h)$ and also holds simultaneously for $\widetilde{r}$ and $\widetilde{m}$. To compute the policy, we define a bonus function $\widetilde{\conf}(s,a,h)$ for each $(s,a,h)$ tuple, which can be decomposed into two parts $\phitilconfL{s,a,h}$ and $\psitilconfL{s,a,h}$, where \begin{align*} &\phitilconfL{s,a,h}=\phitilconfR{s,a,h} \enspace,\\ &\psitilconfL{s,a,h}=\psitilconfR{s,a,h} \enspace. \end{align*} The term $\phitilconfL{\cdot}$ roughly corresponds to the sampling error, while $\psitilconfL{\cdot}$ corresponds to errors introduced by the private counters. Using this bonus function, we use dynamic programming to compute an optimistic private Q-function in Algorithm~\ref{alg:privateplanning}. The algorithm here is a standard batch Q-learning update, with $\widetilde{\conf}(\cdot)$ serving as an optimism bonus. The resulting Q-function, called $\widetilde{Q}^{+}$, encodes a greedy policy, which we use for the $t$-th episode. \section{Privacy Analysis of $\texttt{PUCB}$} We show that releasing the sequence of actions by algorithm $\texttt{PUCB}$ satisfies JDP with respect to any user on an episode changing his data. Formally, \begin{theorem}\label{thm:jdp} Algorithm (\ref{alg:pucb}) \texttt{PUCB}~is $\varepsilon$-JDP. \end{theorem} To prove theorem \ref{thm:jdp}, we use the \emph{billboard lemma} due to \cite{hsu2016private} which says that an algorithm is JDP if the output sent to each user is a function of the user's private data and a common signal computed with standard differential privacy. We state the formal lemma: \begin{lemma}[Billboard lemma \cite{hsu2016private}]\label{lem:billboard} Suppose $\cM:U \rightarrow \mathcal{R}$ is $\varepsilon$-differentially private. Consider any set of functions $f_i : U_i\times \mathcal{R} \rightarrow \mathcal{R}'$ where $U_i$ is the portion of the database containing the $i$'s user data. The composition $\{f_i(\Pi_i U, \cM(U))\}$ is $\varepsilon$-joint differentially private, where $\Pi_i:U\rightarrow U_i$ is the projection to $i$'s data. \end{lemma} Let $U_{<t}$ denote the data of all users before episode $t$ and $u_t$ denote the data of the user during episode $t$. Algorithm \texttt{PUCB} keeps track of all events on users $U_{<t}$ in a differentially-private way with private counters $\widetilde{r}_t, \widetilde{n}_t, \widetilde{m}_t$. These counters are given to the procedure \texttt{PrivQ}~ which computes a $Q$-function $\widetilde{Q}^{+}_t$, and induces the policy $\pi_t(s,h) \coloneqq \max_a \widetilde{Q}^{+}_t(s,a,h)$ to be use by the agent during episode $t$. Then the output during episode $t$ is generated the policy $\pi_t$ and the private data of the user $u_t$ according to the protocol \ref{alg:rlprotocol}, the output on a single episode is: $\left(\pi_t\left(s^{(t)}_1, 1\right), \ldots, \pi_t\left(s^{(t)}_H, H\right)\right)$. By the billboard lemma \ref{lem:billboard}, the composition of the output of all T episodes, and the final policy $\left(\left\{\left( \pi_t(s^{(t)}_1, 1), \ldots, \pi_t(s^{(t)}_H, H)\right) \right\}_{t\in [T]}, \pi_T\right) $ satisfies $\varepsilon$-JDP if the policies $\{\pi_t\}_{t\in [T]}$ are computed with a $\varepsilon$-DP mechanism. Then it only remains to show that the noisy counts satisfy $\varepsilon$-DP. First, consider the counters for the number of visited states. The algorithm $\texttt{PUCB}$ runs $SAH$ parallel private counters, one for each state tuple $(s,a,h)$. Each counter is instantiated with a $\varepsilon/(3H)$-differentially private mechanism which takes an input an event stream $\widehat{n}(s,a,h) = \{0,1\}^T$ where the $i$th bit is set to 1 if a user visited the state tuple $(s,a,h)$ during episode $i$ and 0 otherwise. Hence each stream $\widehat{n}(s,a,h)$ is the data for a private counter. The next claim says that the total $\ell_1$ sensitivity over all streams is bounded by $H$: \begin{claim}\label{claim:sensitivity} Let $U, U'$ be two $t$-neighboring user sequences, in the sense that they are only different in the data for episode $t$. For each $(s,a,h)\in\cS\times\cA\times [H]$, let $\widehat{n}(s,a,h)$ be the event stream corresponding to user sequence U and $\widehat{n}'(s,a,h)$ be the event stream corresponding to $U'$. Then the total $\ell_1$ distance of all stream is given by the following claim: \begin{align*} \sum_{(s,a,h)\in \cS\times\cA\times [H]} \|\widehat{n}(s,a,h) -\widehat{n}'(s,a,h)\|_1\leq H \end{align*} \end{claim} \begin{proof} The proof follows from the fact that on any episode $t$ a user visits at most $H$ states. \end{proof} Finally we use a result from \citep[Lemma 34]{hsu2016private} which states that the composition of the $SAH$ $(\varepsilon/3H)$-DP counters for $\widehat{n}(\cdot)$ satisfy $(\varepsilon/3)$-DP as long as the $\ell_1$ sensitivity of the counters is $H$ as shown in claim \ref{claim:sensitivity}. We can apply the same analysis to show that the counters corresponding to the empirical reward $\widehat{r}(\cdot)$ and the transitions $\widehat{m}(\cdot)$ are both also $(\varepsilon/3)$-DP. Putting it all together releasing the noisy counters is $\varepsilon$-differentially private. \subsection{Proofs from Section~\ref{sec:mablb}} The lower bound result relies on the following adaptation of the coupling lemma from \citep[Lemma 6.2]{karwa2017finite}. \begin{lemma}[\cite{karwa2017finite}]\label{lemma:KarwaVadhan} For every pair of distributions $\mathbb{D}_{\theta_0}$ and $\mathbb{D}_{\theta_1}$, every $(\epsilon, \delta)$-differentially private mechanism $M(x_1, \ldots, x_n)$, if $\mathbb{M}_{\theta_0}$ and $\mathbb{M}_{\theta_1}$ are two induced marginal distributions on the output of $M$ evaluated on input dataset $X_1, \ldots, X_n$ sampled i.i.d from $\mathbb{D}_{\theta_0}$ and $\mathbb{D}_{\theta_1}$ respectively, $\epsilon' = 6\epsilon n \|\mathbb{D}_{\theta_0}-\mathbb{D}_{\theta_1}\|_{tv}$ and $\delta' = 4\delta e^{\epsilon'}\|\mathbb{D}_{\theta_0}-\mathbb{D}_{\theta_1}\|_{tv}$, then, for every event $E$, \begin{align*} \mathbb{M}_{\theta_0}(E) \leq e^{\epsilon'}\mathbb{M}_{\theta_1}(E) + \delta' \end{align*} \end{lemma} \begin{lemma*}[Lemma \ref{lem:KarwaVadhanMAB}.] Fix any arm $a \in [k]$. Now consider any pair of MAB instances $\mu, \nu \in [0,1]^k$ both with $k$ arms and time horizon $T$, such that $\|\mu_a - \nu_a \|_{tv} < \alpha$ and $\|\mu_{a'} - \nu_{a'} \|_{tv} = 0$ for all $a' \neq a$. Let $R \sim B(\mu)^T$ and $Q \sim B(\nu)^T$ be the sequence of $T$ rounds of rewards sampled under $\mu$ and $\nu$ respectively, and let $\cM$ be any $\epsilon$-DP multi-armed bandit algorithm. Then, for any event $E$ such that under event $E$ arm $a$ is pulled less than $t$ times, \begin{align*} \prob{\cM,R}{E} \leq e^{6 \epsilon t \alpha}\prob{\cM,Q}{E} \end{align*} \end{lemma*} \begin{proof} We can think of algorithm $M(R)$ as taking as input a tape of $t$ pre-generated rewards for arm $a$, denote this tape as $R = (r_1, \ldots r_t)$. If $M(R)$ is executed with input tape $R$, then when $M(R)$ pulls arm $a$ for the $j^{th}$ time the $j^{th}$ entry $R_j$ is revealed and removed from $R$. If $M(R)$ runs out of the tape $R$ then the reward is drawn from the real distribution of arm $a$ (i.e. $P_a$). Lastly, if $M(R)$ pulls some arm $a' \neq a$ then the reward is drawn from the real distribution $P_{a'}$. Note that if $R$ is sampled from the real distribution of arm $a$ i.e $R \sim P_a^t$, then $M$ and $M(R)$ are equivalent. That is, for any event $E$, $$\prob{M,P}{E} = \prob{M(R), P}{E}$$ Under this construction, the event that $M(R)$ pulls arm $a$ less than $t$ times, is the same as the event that $M(R)$ consumes less than $t$ entries of the tape $R$. By the assumption of the event $E$ under consideration, if $M(R)$ consumes at least $t$ entries of the tape then we can say that event $E$ fails to happen. Therefore, in order to evaluate the event $E$ we only need to initialize $M(R)$ with tapes of size $t$. Furthermore, we treat the input tape $R$ as the data of $M$ and we claim that $M(R)$ is ($\epsilon, \delta$)-differentially private on $R$. Now we apply lemma (\ref{lemma:KarwaVadhan}) to bound the probability of $E$ under $M(R_p)$ and $M(R_q)$, where $R_p$ and $R_q$ are the input tapes each generated with $t$ i.i.d samples from distribution $P_a$ and $Q_a$ respectively. $$\prob{M(R_p),P}{E} \leq e^{6 \epsilon t \Delta_a} \prob{M(R_q),Q}{E}$$ This implies $\prob{M,P}{E} \leq e^{6 \epsilon t \Delta_a}\prob{M,Q}{E}$. \end{proof} \subsection{Proofs from Section~\ref{sec:rlpslb}} \begin{lemma*}[Lemma \ref{lem:jdptodp}.] Let $(U,S_1)$ be a user-state input sequence with initial states from some set $\cS_1$. Suppose $\mathcal{M}$ is an RL agent that satisfies $\varepsilon$-JDP in the public initial state setting. Then, for any $s \in \cS_1$ the trace $\cM_{1,s}(U,S_1)$ is the output of an $\epsilon$-DP MAB mechanism on input $U_s$. \end{lemma*} \begin{proof}[Proof of Lemma~\ref{lem:jdptodp}] \newcommand{\bar E_{-t}^{|\vec{a}} }{\bar E_{-t}^{|\vec{a}} } \newcommand{\bar E_{>t}^{|\vec{a}} }{\bar E_{>t}^{|\vec{a}} } \newcommand{\bar E_{<t}^{|\vec{a}} }{\bar E_{<t}^{|\vec{a}} } Fix $(U,S_1)$, $s$ and $U_s$ as in the statement. Recall that $T_s$ is the number of times state $s$ is in $S_1$. Observe that $\cM_{1,s}(U,S_1)$ has the output type expected from a MAB mechanism on input $U_s$. Fix an event $E \subseteq \cA^{T_s+1}$ on the first action from all episodes starting with $s$ together with the action predicted by the policy at state $s$. For any $\bar{a} = (\bar a^{(1)},\ldots,\bar a^{(T_s)},\hat{a}) \in E$ we define the event $E_{\bar{a}} \subseteq \cA^{H \times T} \times \Pi$ by \begin{align*} E_{\bar{a}} = \{ (a_h^t)_{h\in[H], t\in [T]}, \pi | a_1^{(t_1)} = \bar a^{(1)}, \ldots, a_1^{(t_{T_s})} = \bar a^{(T_s)}, \pi(s) = \hat{a}\} \enspace. \end{align*} where $a_1^{t_i}$ is the first action in the $i$th episode where state $s$ is the first state. The the event $\bar E$ is the union of all events $E_{\bar a}$, defined as \begin{align*} \bar{E} = \cup_{\bar{a} \in E} E_{\bar{a}} \subseteq \cA^{H \times T} \times \Pi \end{align*} Let $\bar{E}_{-t} \subseteq \cA^{H \times (T-1)}\times \Pi$ be the collection of outputs from $\bar{E}$ truncated to length $T-1$ and including the output policy. Furthermore, let $\bar{E}_{< t} \subseteq \cA^{H \times [t-1]}$ be the collection of outputs from $\bar{E}$ truncated to length $t-1$ and similarly let $\bar{E}_{> t} \subseteq \cA^{H \times (T - t)}$ be the sequences truncated to length $T-t$ . For any $\vec{a} \in \cA^{H}$ we define the following notation \begin{align*} &\bar E_{-t}^{|\vec{a}} =\left\{e \in \bar{E}_{-t} : (\vec{a},e) \in \bar{E} \right\} \\ &\bar E_{>t}^{|\vec{a}} = \left\{e \in \bar{E}_{>t}: \exists_{ {b}^{(1)},\ldots,{b}^{(t-1)}\in \cA^{H}} \left( {b}^{(1)},\ldots,{b}^{(t-1)}, \vec{a},e\right) \in \bar{E} \right\} \\ &\bar E_{<t}^{|\vec{a}} = \left\{e \in \bar{E}_{<t}: \exists_{ {b}^{(1)},\ldots,{b}^{(T-t)}\in \cA^{H}} \left({b}^{(1)},\ldots,{b}^{(T-t)}, \vec{a},e\right) \in \bar{E} \right\} \enspace. \end{align*} For the remaining of the proof, denote by $\cM_t(U,S_1)$ the output during episode $t$, $\cM_{<t}(U,S_1)$ all the outputs before episode $t$, $\cM_{>t}(U,S_1)$ all the outputs after episode $t$, and $\cM_{-t}(U,S_1)$ are all the outputs except for the output during episode $t$ and it includes the final output policy. For any $\vec{a}\in \cA^H$ It is easy to show that \begin{align}\label{eq:Eequiv} \text{ } \cM_{-t}(U,S_1) \in \bar E_{-t}^{|\vec{a}} \text { if and only if } \cM_{>t}(U,S_1) \in \bar E_{>t}^{|\vec{a}} \text{ and } \cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} \end{align} Observe that since $\cM$ processes its inputs incrementally we have that \begin{align} \label{eq:futureconditioned} \pr{\cM_{t}(U,S_1) = \vec{a} \land \cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} ~\bigg| \cM_{>t}(U,S_1) \in \bar E_{>t}^{|\vec{a}} } = \pr{\cM_{t}(U,S_1) = \vec{a} \land \cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} } \end{align} The equation \eqref{eq:futureconditioned} says that conditioning on the output of future events does not affect the probability of the present event. Now take $(U',S_1)$ to be a $t$-neighboring user-state sequence and note $U'_s$ is a neighboring sequence of $U_s$ in the sense used in the definition of DP for MAB mechanisms. The next equation says that the output of $\cM_t$ on episode $t$, is not distinguishable on the user-state sequences $(U, S_1)$ and $(U', S_1)$. This is because $U$ and $U'$ match on all episodes before episode $t$ and they share the same initial state on every episode. We have that \begin{align} \label{eq:neighborevent} \pr{\cM_t(U, S_1)} = \pr{\cM_t(U', S_1)} \end{align} We will use the following simple application of Baye's Rule: \begin{align} \label{eq:bayes} \pr{A | B,C } = \frac{\pr{A \land B | C}}{\pr{B|C}} \end{align} Next We want to show that \begin{align}\label{eq:UtoUprime} \pr{\cM_{t}(U,S_1) = \vec{a} ~\bigg| \cM_{-t}(U,S_1) \in \bar E_{-t}^{|\vec{a}} } = \pr{\cM_{t}(U',S_1) = \vec{a} ~\bigg| \cM_{-t}(U',S_1) \in \bar E_{-t}^{|\vec{a}} } \end{align} Let fix one $\vec{a}$ for now, then from \eqref{eq:Eequiv}, \eqref{eq:futureconditioned}, \eqref{eq:neighborevent}, and \eqref{eq:bayes} we have \begin{align*} &\pr{\cM_{t}(U,S_1) = \vec{a} ~\bigg| \cM_{-t}(U,S_1) \in \bar E_{-t}^{|\vec{a}} } \\ &= \pr{\cM_{t}(U,S_1) = \vec{a} ~\bigg| \cM_{>t}(U,S_1) \in \bar E_{>t}^{|\vec{a}} \land \cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} } \quad \text{equation } \eqref{eq:Eequiv}\\ &= \frac{ \pr{\cM_{t}(U,S_1) = \vec{a} \land \cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} ~\bigg| \cM_{>t}(U,S_1) \in \bar E_{>t}^{|\vec{a}} }} {\pr{\cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} ~\bigg| \cM_{>t}(U,S_1) \in \bar E_{>t}^{|\vec{a}} }} \quad \text{equation } \eqref{eq:bayes} \\ &= \frac{ \pr{\cM_{t}(U,S_1) = \vec{a} \land \cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} }} {\pr{\cM_{<t}(U,S_1) \in \bar E_{<t}^{|\vec{a}} }} \quad \text{equation } \eqref{eq:futureconditioned} \\ &= \frac{ \pr{\cM_{t}(U',S_1) = \vec{a} \land \cM_{<t}(U',S_1) \in \bar E_{<t}^{|\vec{a}} }} {\pr{\cM_{<t}(U',S_1) \in \bar E_{<t}^{|\vec{a}} }} \quad \text{equation } \eqref{eq:neighborevent} \\ &= \frac{ \pr{\cM_{t}(U',S_1) = \vec{a} \land \cM_{<t}(U',S_1) \in \bar E_{<t}^{|\vec{a}} ~\bigg| \cM_{>t}(U',S_1) \in \bar E_{>t}^{|\vec{a}} }} {\pr{\cM_{<t}(U',S_1) \in \bar E_{<t}^{|\vec{a}} ~\bigg| \cM_{>t}(U',S_1) \in \bar E_{>t}^{|\vec{a}} }} \quad \text{equation } \eqref{eq:futureconditioned} \\ &= \pr{\cM_{t}(U',S_1) = \vec{a} ~\bigg| \cM_{>t}(U',S_1) \in \bar E_{>t}^{|\vec{a}} \land \cM_{<t}(U',S_1) \in \bar E_{<t}^{|\vec{a}} } \quad \text{equation } \eqref{eq:bayes}\\ &=\pr{\cM_{t}(U',S_1) = \vec{a} ~\bigg| \cM_{-t}(U',S_1) \in \bar E_{-t}^{|\vec{a}} } \end{align*} Combined with the $\epsilon$-JDP assumption on $\cM$ this implies that \begin{align*} & \pr{\cM(U,S_1) \in \bar{E}} \\ &= \sum_{\vec{a} \in \cA^H} \pr{\cM_t(U,S_1) = \vec{a} \land \cM_{-t}(U, S_1) \in \bar E_{-t}^{|\vec{a}} } \\ &= \sum_{\vec{a} \in \cA^H} \pr{\cM_{t}(U,S_1) = \vec{a} ~\bigg| \cM_{- t}(U,S_1) \in \bar E_{-t}^{|\vec{a}} } \pr{\cM_{- t}(U,S_1) \in \bar E_{-t}^{|\vec{a}} } \\ &= \sum_{\vec{a} \in \cA^H} \pr{\cM_{t}(U',S_1) = \vec{a} ~\bigg| \cM_{- t}(U',S_1) \in \bar E_{-t}^{|\vec{a}} } \pr{\cM_{- t}(U,S_1) \in \bar E_{-t}^{|\vec{a}} } \quad\quad \hfill \text{ Equation } \eqref{eq:UtoUprime} \\ &\leq \sum_{\vec{a} \in \cA^H} \pr{\cM_{t}(U',S_1) = \vec{a} ~\bigg| \cM_{- t}(U',S_1) \in \bar E_{-t}^{|\vec{a}} } e^{\varepsilon}\pr{\cM_{-t}(U',S_1) \in \bar E_{-t}^{|\vec{a}} } \quad\quad \hfill \cM \text{ satisfies } \varepsilon\text{-JDP} \\ &= e^{\varepsilon} \pr{\cM(U',S_1) \in \bar{E}} \enspace. \end{align*} Finally, using the inequality above, and by the construction of $\cM_{1,s}$ and $\bar{E}$ we have \begin{align*} \pr{\cM_{1,s}(U,S_1) \in E} &= \pr{\cM(U,S_1) \in \bar{E}} \\ &\leq e^{\epsilon} \pr{\cM(U',S_1) \in \bar{E}} \\ &= e^{\epsilon}\pr{\cM_{1,s}(U',S_1) \in E} \enspace. \end{align*} \end{proof} To prove the lower bound we consider the class of MDPs shown in Figure~\ref{fig:hardMDP}. An MDP in this class has state space $\cS \coloneqq [n] \cup \{+,-\}$ and action space $\cA \coloneqq \{0,\ldots,m\}$. On each episode, the agent starts on one of the initial states $\{1, \ldots, n\}$ chosen uniformly at random. The state labelled $0$ is a dummy state which represents the initial transition to any state $s \in \{1, \ldots, n\}$ with uniform probability. On each of the initial states the agent has $m+1$ possible actions and transitions can only take it to one of two possible absorbing states $\{+,-\}$. Lastly, if the current state is either one of $\{ +, - \}$ then the only possible transition is a self loop, hence the agent is stays in that state until the end of the episode. We assume in these absorbing states the agent can only take a fixed action. Every action which transitions to state $+$ provides reward $1$ while actions transitioning to state $-$ provide reward $0$. In particular, in each episode the agent either receives reward $H$ or $0$. Such an MDP can be seen as consisting of $n$ parallel MAB problems. Each MAB problem determines the transition probabilities between the initial state $s \in\{1, \ldots, n\}$ and the absorbing states $\{+,-\}$. We index the possible MAB problems in each initial state by their optimal arm, which is always one of $\{0,\ldots,m\}$. We write $I_s \in \{0,\ldots,m\}$ to denote the MAB instance in initial state $s$, and define the transition probabilities such that $\pr{+|s,0} = 1/2+\alpha'/2$ and $\pr{+|s,a'} = 1/2$ for $a' \neq I_s$ for all $I_s$, and for $I_s \neq 0$ we also have $\pr{+|s,I_s} = 1/2 + \alpha'$. Here $\alpha'$ is a free parameter to be determined later. We succinctly represent an MDP in the class by identifying the optimal action (i.e.\ arm) in each initial state: $I \coloneqq (I_1,\ldots,I_n)$. \begin{figure}[h] \begin{equation*} \tikzfig{figures/hard_MDP2} \end{equation*} \caption{Hard MDP}\label{fig:hardMDP} \end{figure} \begin{proof}[Proof of Lemma~\ref{lem:lowerboundpublic}] We start by noting that the first term in the lower bound comes from the corresponding lower bound for the non-private episodic RL setting \citep[Theorem 2]{dann2015sample}, which also holds for our case. Now let $I = (I_1,\ldots,I_n)$ encode an MDP from the class above with $n+2$ states and $m+1$ actions. The optimal policy on this MDP is given by $\pi^*(s) = I_s$ for $s \in [n]$, and we write $\rho_I^*$ to denote the total expected reward of the optimal policy on a single episode. Define $G_s$ to be the event that policy $\pi$ produced by algorithm $\cM$ finds the optimal arm in state $s$, that is $\pi(s)=I_s$. We denote by $\rho_I^{\pi}$ the total expected reward per episode of this policy. Then, for any episode, the difference $\rho_I^*-\rho_I^\pi$ between total rewards is at least $$ \rho_I^*-\rho_I^\pi \geq H \left(1 - \frac{1}{n}\sum_{s=1}^n \mathbbm{1}\{G_s\} \right) \alpha'/2 \enspace. $$ Thus, $\pi$ cannot by $\alpha$-optimal unless we have: \begin{align} &\alpha \geq H \left(1 - \frac{1}{n}\sum_{s=1}^n \mathbbm{1}\{G_s\} \right) \alpha'/2 \notag \\ \iff &\frac{2\alpha}{H \alpha'} \geq\left(1 - \frac{1}{n}\sum_{s=1}^n \mathbbm{1}\{G_s\} \right) \notag\\ \iff &\frac{1}{n}\sum_{i=1}^n\mathbbm{1}\{G_s\} \geq \left( 1 - \frac{2\alpha}{H \alpha'} \right)\coloneqq \phi \enspace. \label{eq:epsOptFrac} \end{align} Here choose $\phi = 6/7$ and set $\alpha' = \frac{14 \alpha}{H}$. Equation \eqref{eq:epsOptFrac} says that in order to make $\pi$ an $\alpha$-optimal policy we must solve at least a $\phi$ fraction of the MAB instances. Hence, to get an $\alpha$-optimal with probability at least $1-\beta$ we require \begin{equation*} 1-\beta \leq \prob{I}{\rho_I^*-\rho_I^\pi \leq \alpha} \leq \prob{I}{\frac{1}{n}\sum_{s=1}^n\mathbbm{1}\{G_s\} \geq \phi} \enspace, \end{equation*} and by Markov's inequality we have \begin{align*} \prob{I}{\frac{1}{n}\sum_{s=1}^n\mathbbm{1}\{G_s\} \geq \phi} \leq \frac{1}{n \phi}\sum_{s=1}^n\prob{I}{G_s} \enspace. \end{align*} Each $\mathbbm{1}\{G_s\}$ is independent from each other be construction of the MDP. Now letting $\beta_s$ be an upper bound for the fail probability of each $\{G_s\}$, the derivation above implies that $1-\beta \leq \frac{1}{n \phi}\sum_{s=1}^n (1 - \beta_s)$, or, equivalently, that $\sum_{s} \beta_s \leq n (1 - \phi (1 - \beta))$. Now note that Lemma~\ref{lem:jdptodp} implies that all interactions between $\cM$ and $I$ that start on state $s$ constitute the execution of an $(\epsilon,\delta)$-DP algorithm on the MAB instance at state $s$. Hence, by Lemma~\ref{lem:privMAB} we can only have $\prob{I}{G_s} \geq 1 - \beta_s$ for some $\beta_s < 1/4$ if the number of episodes starting at $s$ where $\cM$ chooses an $\alpha'$-suboptimal arm satisfies \begin{align*} \Ex{n_s} &> \frac{(A-1)}{24 \epsilon \alpha'}\ln{\left(\frac{1}{4\beta_s}\right)}\mathbbm{1}[\beta_s < 1/4] \\ &= \frac{H(A-1)}{336 \epsilon \alpha}\ln{\left(\frac{1}{4\beta_s}\right)}\mathbbm{1}[\beta_s < 1/4] \\ &\geq \frac{H(A-1)}{336 \epsilon \alpha} \ln{\left(\frac{1}{4\beta_s}\right)}\mathbbm{1}[\beta_s \leq 1 - \phi(1-\beta)] \enspace, \end{align*} where we used that $\phi = 6/7$ and $\beta < 1/8$ imply $1 - \phi(1-\beta) < 1/4$, and that each MAB instance has $A - 1$ arms which are $\alpha'$-suboptimal. Thus, we can find a lower bound $\Ex{n_{\cM}} \geq \sum_s \Ex{n_s}$ by minimizing the sum of the lower bound on $\Ex{n_s}$ under the constraint that $\sum_{s} \beta_s \leq n (1 - \phi (1 - \beta))$. Here we can apply the argument from \citep[Lemma D.1]{dann2015sample} to see that the optimal choice of probabilities is given by $\beta_s = 1 - \phi(1-\beta)$ for all $s$. Plugging this choice in the lower bound leads to \begin{align*} \Ex{n_{\cM}} &\geq \frac{H S (A-1)}{336 \epsilon \alpha} \ln{\left(\frac{7}{4+24\beta}\right)} \enspace. \end{align*} \end{proof} \begin{lemma*}[Lemma \ref{lem:publicvsprivatestates}] Any RL agent $\cM$ satisfying $\varepsilon$-JDP also satisfies $\varepsilon$-JDP in the public state setting. \end{lemma*} \begin{proof} Suppose that algorithm $\cM$ satisfies $\varepsilon$-JDP. Let $(U, S_1)$ and $(U', S_1')$ be two $t$-neighboring user-state sequences such that $S_1 = S_1'$. Then for all events $E \subseteq \cA^{H \times [T-1]} \times \Pi$ we have \begin{align*} \pr{\cM_{-t}(U,S_1) \in E } \leq e^\varepsilon \pr{\cM_{-t}(U', S_1') \in E} \end{align*} Therefore $\cM$ satisfies the condition for $\varepsilon$-JDP in the public state setting as in definition \ref{def:jdppublic}. \end{proof} \section{Preliminaries} \subsection{Markov Decision Processes} A fixed-horizon \emph{Markov decision process} (MDP) with time-dependent dynamics can be formalized as a tuple $M = \left( \cS, \cA, \cR, \cP, p_0, H \right)$. $\cS$ is the state space with cardinality $S$. $\cA$ is the action space with cardinality $A$. $\cR(s_h, a_h, h)$ is the reward distribution on the interval $[0,1]$ with mean $r(s_h, a_h, h)$. $\cP$ is the transition kernel, given time step $h$, action $a_h$ and, state $s_h$ the next state is sampled from $s_{t+1} \sim \cP(.|s_h, a_h,h)$. Let $p_0$ be the initial state distribution at the start of each episode, and $H$ be the number of time steps in an episode. In our setting, an agent interacts with an MDP by following a (deterministic) policy $\pi \in \Pi$, which maps states $s$ and timestamps $h$ to actions, i.e., $\pi(s,h) \in \cA$. The \emph{value function} in time step $h\in [H]$ for a policy $\pi$ is defined as: \begin{align*} V_h^\pi(s) &\;= \Ex{\sum_{i=h}^H r(s_i, a_i, i) \bigg| s_h = s, \pi} \\ &\;= r(s, \pi(s,h), h) + \sum_{s'\in \cS} V_{h+1}^\pi(s') \cP(s'|s,\pi(s,h), h) \enspace. \end{align*} The \emph{expected total reward} for policy $\pi$ during an entire episode is: $$\rho^\pi = \Ex{\sum_{i=1}^H r(s_i, a_i, i) \bigg| \pi} = p_0^\top V_1^\pi \enspace.$$ The \emph{optimal value function} is given by $V_h^*(s) = \max_{\pi \in \Pi} V_h^{\pi}(s)$. Any policy $\pi$ such that $V_h^{\pi}(s) = V_h^*(s)$ for all $s \in \cS$ and $h \in [H]$ is called optimal. It achieves the optimal expected total reward $\rho^* = \max_{\pi \in \Pi} \rho^{\pi}$. The goal of an RL agent is to learn a near-optimal policy after interacting with an MDP for a finite number of episodes $T$. During each episode $t \in [T]$ the agent follows a policy $\pi_t$ informed by previous interactions, and after the last episode it outputs a final policy $\pi$. \begin{definition} An agent is \emph{$(\alpha,\beta)$-probably approximately correct} (PAC) with sample complexity $f(S,A,H,\tfrac{1}{\alpha}, \log(\tfrac{1}{\beta}))$, if with probability at least $1-\beta$ it follows an $\alpha$-optimal policy $\pi$ such that $\rho^* - \rho^\pi \leq \alpha$ except for at most $f(S,A,H,\tfrac{1}{\alpha}, \log(\tfrac{1}{\beta}))$ episodes. \end{definition} \begin{definition} The (expected cumulative) \emph{regret} of an agent after $T$ episodes is given by \begin{align*} \mathrm{Regret}(T) = \sum_{t=1}^T (\rho^* - \rho^{\pi_t}) \enspace, \end{align*} where $\pi_1, \ldots \pi_T$ are the policies followed by the agent on each episode. \end{definition} \subsection{Privacy in RL} In some RL application domains such as personalized medical treatments, the sequence of states and rewards received by a reinforcement learning agent may contain sensitive information. For example, individual users may interact with an RL agent for the duration of an episode and reveal sensitive information in order to obtain a service from the agent. This information affects the final policy produced by the agent, as well as the actions taken by the agent in any subsequent interaction. Our goal is to prevent damaging inferences about a user's sensitive information in the context of the interactive protocol in \cref{alg:rlprotocol} summarizing the interactions between an RL agent $\cM$ and $T$ distinct users. \begin{algorithm}[h] \caption{Episodic RL Protocol}\label{alg:rlprotocol} \KwIn{ Agent $\cM$ and users $u_1, \ldots, u_T$} \For{$t \in [T]$}{ \For{$h \in [H]$}{ $u_t$ sends state $s_h^{(t)}$ to $\cM$ \\ $\cM$ sends action $a_h^{(t)}$ to $u_t$ \\ $u_t$ sends reward $r_h^{(t)}$ to $\cM$ \\ } } $\cM$ releases policy $\pi$ \end{algorithm} Throughout the execution of this protocol the agent observes a collection of $T$ state-reward trajectories of length $H$. Each user $u_t$ gets to observe the actions chosen by the agent during the $t$-th episode, as well as the final policy $\pi$. To preserve the privacy of individual users we enforce a (joint) differential privacy criterion: upon changing one of the users in the protocol, the information observed by the other $T-1$ participants will not change substantially. This criterion must hold even if the $T-1$ participants collude adversarially, by e.g., crafting their states and rewards to induce the agent to reveal information about the remaining user Formally, we write $U = (u_1,\ldots,u_T)$ to denote a sequence of $T$ users participating in the RL protocol. Technically speaking a user can be identified with a tree of depth $H$ encoding the state and reward responses they would give to all the $A^H$ possible sequences of actions the agent can choose. During the protocol the agent only gets to observe the information along a single root-to-leaf path in each user's tree. For any $t \in [T]$, we write $\cM_{-t}(U)$ to denote all the outputs excluding the output for episode $t$ during the interaction between $\cM$ and $U$. This captures all the outputs which might leak information about the $t$-th user in interactions after the $t$-th episode, as well as all the outputs from earlier episodes where other users could be submitting information to the agent adversarially to condition its interaction with the $t$-th users. We also say that two user sequences $U$ and $U'$ are $t$-neighbors if they only differ in their $t$-th user. \begin{definition}\label{def:jdp} A randomized RL agent $\cM$ is \emph{$\epsilon$-jointly differentially private under continual observation} (JDP) if for all $t \in [T]$, all $t$-neighboring user sequences $U$, $U'$, and all events $E \subseteq \cA^{H \times [T-1]} \times \Pi$ we have \begin{align*} \pr{\cM_{-t}(U) \in E }\leq e^\epsilon \pr{\cM_{-t}(U') \in E} \enspace. \end{align*} \end{definition} This definition extends to the RL setting the one used in \cite{shariff2018differentially} for designing privacy-preserving algorithms for linear contextual bandits. The key distinctions is that in our definition each user interacts with the agent for $H$ time-steps (in bandit problems one usually has $H=1$), and we also allow the agent to release the learned policy at the end of the learning process. Another distinction is that our definition holds for all past and future outputs. In contrast, the definition of JDP in \cite{shariff2018differentially} only captures future episodes; hence, it only protects against collusion from future users. To demonstrate that our definition gives a stronger privacy protection, we use a simple example. Consider an online process that takes as input a stream of binary bits $u=(u_1, \ldots, u_T)$, where $u_t\in\{0,1\}$ is the data of user $t$, and on each round $t$ the mechanism outputs the partial sum $m_t(u) = \sum_{i=1}^t u_i$. Then the following trivial mechanism satisfies JDP (in terms of future episodes as in the JDP definition of \cite{shariff2018differentially}): First, sample once from the Laplace mechanism $\xi \sim \text{Lap}(\varepsilon)$ before the rounds begin, and on each round output $\widetilde{m}_t(u) = m_t(u) + \xi$. Note that the view of any future user $t’>t$ is $\widetilde{m}_{t'}(u)$. Now let $u$ be a binary stream with user $t$ bit on and let $w$ be identical to $u$ but with user $t$ bit off. Then, by the differential-privacy guarantee of the Laplace mechanism, a user $t'>t$ cannot distinguish between $\widetilde{m}_{t'}(u)$ and $\widetilde{m}_{t'}(w)$. Furthermore, any coalition of future users cannot provide more information about user $t$. Therefore this simple mechanism satisfies the JDP definition from \cite{shariff2018differentially}. However, the simple counting mechanism with one round of Laplace noise does not satisfy JDP for past and future outputs as in our JDP (\cref{def:jdp}). To see why, suppose that user $t-1$ and user $t+1$ collude in the following way: For input $u$, the view of user $t-1$ is $\widetilde{m}_{t-1}(u)$ and the view of user $t+1$ is $\widetilde{m}_{t+1}(u)$. They also know their own data $u_{t-1}$, $u_{t+1}$. Then they can recover the data of the $t$-th user as follows \begin{align*} \widetilde{m}_{t+1}(u) - u_{t+1} - \widetilde{m}_{t-1}(u) = m_{t+1}(u) + \xi - u_{t+1} - m_{t-1}(u) - \xi = \sum_{i=1}^{t+1}u_i - u_{t+1} - \sum_{i=1}^{t-1}u_i =u_t \end{align*} \begin{remark} 1. would the algorithm leak more info for the returning user? yes, but we could bound using group privacy. 2. would other users be affected? no, because JDP prevents arbitrary collusion \end{remark} \subsection{Counting Mechanism} The algorithm we describe in the next section maintains a set of counters to keep track of events that occur when interacting with the MDP. We denote by $\widehat{n}_t(s,a,h)$ the count of visits to state tuple $(s,a,h)$ right before episode $t$, where $a\in\cA$ is the action taken on state $s\in\cS$ and time-step $h\in [H]$. Likewise $\widehat{m}_t(s,a,s',h)$ is the count of going from state $s$ to $s'$ after taking actions $a$ before episode $t$. Finally, we have the counter $\widehat{r}_t(s,a,h)$ for the total reward received by taking action $a$ on state $s$ and time $h$ before episode $t$. Then, on episode $t$, the counters are sufficient to create an estimate of the MDP dynamics to construct a policy for episode $t$. The challenge is that the counters depend on the sequence of states and actions, which is considered sensitive data in this work. Therefore the algorithm must release the counts in a privacy-preserving way, and we do this the private counters proposed by \cite{chan2011private} and \cite{dwork2010differential}. A private counter mechanism takes as input a stream $\sigma = (\sigma_1\ldots, \sigma_T)\in [0,1]^T$ and on any round $t$ releases and approximation of the prefix count $c(\sigma)(t) = \sum_{i=1}^t \sigma_i$. In this work we will denote $\text{PC} $ as the binary mechanism of \cite{chan2011private} and \cite{dwork2010differential} with parameters $\epsilon$ and $T$. This mechanism produces a monotonically increasing count and satisfies the following accuracy guarantee: Let $\mathcal{M} \coloneqq \BM{T, \varepsilon}$ be a private counter and $c(\sigma)(t)$ be the true count on episode $t$, then given a stream $\sigma$, with probability at least $1-\beta$, simultaneously for all $1\leq t \leq T$, we have \begin{align*} \left| \mathcal{M}(\sigma)(t) - c(\sigma)(t) \right| \leq \frac{4}{\varepsilon}\ln(1/\beta)\log(T)^{5/2} \enspace. \end{align*} While the stated bound above holds for a single $\varepsilon$-DP counter, our algorithm needs to maintain more than $S^2 A H$ many counters. A naive allocation of the privacy budget across all these counters will require noise with scale polynomially with $S, A$, and $H$. However, we will leverage the fact that the total change across all counters a user can have scales with the length of the episode $H$, which allows us to add a much smaller amount of noise that scales linearly in $H$. \section{Private Counters} We use the binary mechanism of \citep{chan2011private} and \cite{dwork2010differential} to keep track of important events in a differentially private way. \begin{algorithm}[h] \caption{Binary Meachanism $\mathcal{B}$} \label{alg:BM} \KwIn{ Time upper bound $T$, privacy parameter $\epsilon$, stream $\sigma \in \{0,1\}^T$} $\epsilon' \leftarrow \epsilon / \log T$\\ \For{$t\leftarrow 1$ \textbf{ to } $ T$}{ Express $t$ in binary form: $t = \sum_j \text{Bin}_j(j) \cdot 2^j$\\ Let $i := \min\{j: \text{Bin}_j(j)\neq0\}$\\ $\alpha_i \leftarrow \sum_{j<i}\alpha_j + \sigma(t)$\\ \For{ $j \longleftarrow 0$ \textbf{to} $i-1$ }{ $\alpha_j\leftarrow 0, \hat{\alpha}_j \leftarrow 0$ } $\hat{\alpha_i} \leftarrow \alpha_i + \text{Lap}\left(\frac{1}{\epsilon'}\right)$\\ Output at time $t$ $\mathcal{B}(t) \leftarrow \sum_{j:\text{Bin}_j(T)=1} \hat{\alpha}_j$\\ } \end{algorithm} The error of the counter is given by the following theorem: \begin{theorem}[Theorem 4.1 in \cite{dwork2010differential} ] \label{thm:counterAccuracy} The counter algorithm \ref{alg:BM} run with parameters $T, \varepsilon, \beta$, yields a $T$-bounded counter with $\varepsilon$-differential privacy, such that with probability at least $1-\beta$ the error for all prefixes $1\leq t \leq T$ is at most $\tfrac{4}{\varepsilon}\log(1/\beta)\log^{2.5}\left(T\right)$. \end{theorem} \section{PAC and Regret Analysis of algorithm \texttt{PUCB}} In this section we provide the complete PAC and Regret analysis of algorithm \texttt{PUCB}~ corresponding to theorem \ref{thm:PUCBPAC} and \ref{thm:PUCBRegret} respectively. We begin by analyzing the PAC sample complexity. \subsection{PAC guarantee for \texttt{PUCB}. Proof of theorem \ref{thm:PUCBPAC}} \input{docs/appendix_pac_upper} \subsection{Regret bound for \texttt{PUCB}. Proof of theorem \ref{thm:PUCBRegret}} \input{docs/appendix_regret_upper} \subsection{Error bounds} \input{docs/fail_events} \subsection{$Q$-optimism}\label{sec:optimism} \input{docs/optimism} \subsection{Optimality gap}\label{subsec:optimalitygap} \input{docs/optimality_gap} \subsection{Nice Episodes}\label{subsec:niceepisodes} \input{docs/nice_episodes} \section{PAC and Regret Lower Bound Proofs} \subsection{PAC Lower Bound. Proof of theorem \ref{thm:lowerbound}} \input{docs/appendix_lower_bound} \subsection{Regret Lower Bound. Proof of theorem \ref{thm:regretlower}} \input{docs/appendix_regret_lower} \section{Acknowledgements} Giuseppe Vietri has been supported by the GAANN fellowship from the U.S. Department of Education. We want to thank Matthew Joseph, whose comments improved our definition of joint-differential-privacy. \newpage \bibliographystyle{alpha}
{'timestamp': '2020-09-22T02:02:37', 'yymm': '2009', 'arxiv_id': '2009.09052', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09052'}
arxiv
\section{Related Work} \input{sections/background} \input{sections/models} \section{Empirical Evaluation} \label{sec:experiments} \input{sections/experiments} \section{Conclusion and Future Work} \label{sec:conclusion} \input{sections/conclusion} \section{Acknowledgements} \label{sec:acknowledgements} \input{sections/acknowledgements} \section{Appendix} \label{sec:appendix} \subsection{Probabilistic Soft Logic} Probabilistic soft logic (\PSL) is a statistical relational learning (SRL) framework that uses arithmetic and first order like logical syntax to define a specific type of probabilistic graphical model called a hinge-loss Markov random field (HL-MRF) \cite{bach:jmlr17}. To do this, \PSL \, derives potential functions from the provided rules which take the form of hinges. Data is used to instantiate several potential functions in a process called grounding. The resulting potential functions are then used to define the HL-MRF. The formal definition of a HL-MRF is as follows: \begin{definition}{Hinge-loss Markov random field.} Let $\mathbf{y} = (y_{1}, \cdots, y_{n})$ be a vector of $n$ variables and $\mathbf{x} = (x_{1}, \cdots, x_{n'})$ a vector of $n'$ variables with joint domain $\mathbf{D} = [0, 1]^{n + n'}$. Let $\mathbf{\phi} = (\phi_{1}, \cdots , \phi_{m})$ be a vector of $m$ continuous potentials of the form $\phi_{i}(\mathbf{y}, \mathbf{x}) = (\max\{\ell_{i}(\mathbf{y}, \mathbf{x}), 0\})^{p_{i}}$, where $\ell_{i}$ is a linear function of $\mathbf{y}$ and $\mathbf{x}$ and $p_{i} \in \{1,2\}$. Let $\mathbf{c} = (c_{1}, \cdots, c_{r})$ be a vector of $r$ linear constraint functions associated with index sets denoting equality constraints $\mathcal{E}$ and inequality constraints $\mathcal{I}$, which define the feasible set . \begin{equation*} \Tilde{\mathbf{D}} = \left\{ (\mathbf{y},\mathbf{x}) \in \mathbf{D} \, \Bigg \vert \begin{array}{lr} c_{k}(\mathbf{y}, \mathbf{x}) = 0,& \forall k \in \mathcal{E}\\ c_{k}(\mathbf{y}, \mathbf{x}) \leq 0,& \forall k \in \mathcal{I}\\ \end{array} \right\} \end{equation*} Then, for $(\mathbf{y}, \mathbf{x}) \in \Tilde{\mathbf{D}}$, given a vector of $m$ nonnegative parameters, i.e., weights, $\mathbf{w} = (w_{1}, \cdots, w_{m})$, a \textbf{hinge-loss Markov random field} $\mathcal{P}$ over random variables $\mathbf{y}$ and conditioned on $\mathbf{x}$ is a probability density defined as: \begin{equation} P(\mathbf{y} \vert \mathbf{x}) = \begin{cases} \frac{1}{Z(\mathbf{w}, \mathbf{x})} \exp (-\sum_{j = 1}^{m} w_{j} \phi_{j}(\mathbf{y}, \mathbf{x})) & (\mathbf{y}, \mathbf{x}) \in \Tilde{\mathbf{D}} \\ 0 & o.w. \end{cases} \label{eq:HL-MRF_Dist} \end{equation} where $Z(\mathbf{w}, \mathbf{x}) = \int_{\mathbf{y} \vert (\mathbf{y}, \mathbf{x} \in \Tilde{\mathbf{D}})} \exp(-f_{\mathbf{w}}(\mathbf{y}, \mathbf{x})) d\mathbf{y}$ is the partition function for the conditional distribution. \end{definition} Rules in a \PSL \, model capture interactions between variables in the domain and can be in the form of a first order logical implication or a linear arithmetic relation. Each rule is made up of predicates with varying numbers of arguments. Substitution of the predicate arguments with constants present in the data generate ground atoms that can take on a continuous value in the range $[0, 1]$. A logical rule must have a conjunctive clause in the body and a disjunctive clause in the head, while an arithmetic rule must be an inequality or equality relating two linear combinations of predicates. A logical rule is translated as a continuous relaxation of Boolean connectives using \textit{Lukasiewicz} logic. Specifically, $P \psland Q$ results in the potential $\max(0.0, P \pslsum Q - 1.0)$, $P \pslor Q$ results in the potential $\min(1.0, P \pslsum Q)$, and $\pslneg Q$ results in the potential $1.0 - Q$. Each grounding of an arithmetic rule is manipulated to $\ell(\mathbf{y}, \mathbf{x}) \leq 0$ and the resulting potential takes the form $\max \{\ell(\mathbf{y}, \mathbf{x}), 0\}$. We now illustrate the process of instantiating a HL-MRF using \PSL \, with an example in the context of recommender systems. \begin{center} \begin{tabular}{ |l|r| } \hline $\pslpred{SimUser}(\pslarg{U1},\pslarg{U2}) \psland \pslpred{Rating}(\pslarg{U1}, \pslarg{M}) \pslthen \pslpred{Rating}(\pslarg{U2}, \pslarg{M})$ & (1) \\ $\pslneg \pslpred{SimUser}(\pslarg{U1}, \pslarg{U2}) \pslor \pslneg \pslpred{Rating}(\pslarg{U1}, \pslarg{M}) \pslor \pslpred{Rating}(\pslarg{U2}, \pslarg{M})$ & (2) \\ $min\{1.0, (1.0 - \pslpred{SimUser}(\pslarg{Alice}, \pslarg{Bob}) \pslsum (1.0 - \pslpred{Rating}(\pslarg{Alice}, \pslarg{Alien})) \pslsum \pslpred{Rating}(\pslarg{Bob}, \pslarg{Alien})\}$ & (3) \\ \hline \end{tabular} \end{center} \begin{exmp} Consider a movie recommendation setting where the task is to predict the ratings users will provide movies that they have not yet rated. We can encode the idea that similar users are likely to enjoy the same movies using the logical statement (1). Here, \pslpred{SimUser} is an observed predicate that represents the similarity between two users, and \pslpred{Rating} is the predicate that we are trying to predict, i.e., the rating a user will give a movie. \PSL \, first converts the rule to its disjunctive normal form, (2). Then, all possible substitutions of constants for the variable arguments in the predicates of the rule are made to make ground atoms. Then, all possible combinations of atoms that can form a ground rule are made. Finally, by utilizing the \textit{Lukasiewicz} relaxation, the following hinge-loss function is created. For instance, let us assume we have data with users $\pslarg{U} = \{Alice, Bob\}$ and movies $\pslarg{M} = \{Alien\}$. This will result in the hinge-loss function (3). \end{exmp} We refer the reader to \cite{bach:jmlr17} for a more detailed description of \PSL. \commentout{ \subsection{Fairness Metrics} In this work, we focus on the fairness metrics non-parity and value unfairness. The definitions of these metrics are provided in \tabref{tab:fairness_metrics}. The two user groups we have selected to define as the protected and unprotected groups are are female and male, respectively. For the remainder of this paper we will let $g$ represent the set of female users, and $\neg g$ the set of male users, $\textbf{R}$ is the set of ratings in the dataset, $m$ is the number of predictions made by the model, $n$ is the number of unique items in the dataset, and $v_{i,j}$ and $r_{i,j}$ are the predicted and true rating user $i$ gives item $j$, respectively. For the fairness metric definitions we use $E_{g}[v]$ and $E_{\neg g}[v]$ to represent the average predicted ratings for $g$ and $\neg g$, respectively, $E_{g}[v]_{j}$ and $E_{\neg g}[v]_{j}$ represent the average predicted ratings for movie $j$ for $g$ and $\neg g$, respectively, and $E_{g}[r]_{j}$ and $E_{\neg g}[r]_{j}$ represent the average true ratings for movie $j$ for $g$ and $\neg g$, respectively \begin{table*}[h] \caption{Fairness Metrics} \centering \begin{tabular}{l l} \hline Metric & Definition \\ \hline \textit{Non-Parity} \cite{DBLP:journals/corr/YaoH17, FairnessAwareRegularizer}& $U_{par}(v) = |(E_{g}[v] - E_{\neg g}[v])|$\\ \textit{Value} \cite{DBLP:journals/corr/YaoH17} & $U_{val}(y) = \frac{1}{n} \sum_{j=1}^{n} |(E_{g}[v]_{j}] - E_{g}[r]_{j}]) - (E_{\neg g}[v]_{j} - E_{\neg g}[r]_{j}])|$\\ \hline \end{tabular} \label{tab:fairness_metrics} \end{table*} } \section{Background} \label{sec:background} We begin by briefly reviewing related work upon which our approach builds. \subsection{Fairness in Recommender Systems} Methods for addressing fairness can occur at three stages of a recommender pipeline: pre-process, in-process, and post-process \cite{mehrabi2019survey}. Pre-processing techniques transform the data so that discrimination characteristics are removed prior to model training \cite{lahoti2019ifair, NIPS2017_6988}. In-processing techniques attempt to remove discrimination during the model training process by incorporating changes into the objective function. Post-processing techniques treat the learned model as a black box and modify the output to remove discrimination \cite{FairnessExposureInRankings:Singh, equalityOfOpportunity:Hardt, LinkedInReRanking:Geyik, MatchmakingFairness:Paraschakis, fair-Reranking:recsys:2019}. Post-processing techniques are particularly attractive to industry since their treatment of the predictor as a black-box makes for a manageable integration into an existing pipeline \cite{AdressingAlgorithmicBias:Gathright, LinkedInReRanking:Geyik}. Recent work has shown the effectiveness of both adversarial learning \cite{AdversariallyLearningFairRepresentations:Beutel, Louizos:CoRR2016, Madras:CoRR2018} and regularization \cite{FairnessAwareRegularizer, DBLP:journals/corr/YaoH17, PairwiseFairness}. Our methods can be used as either an in-processing or post-processing method, and builds upon the line of research that addresses fairness via regularization. \commentout{ Methods for addressing unfairness can fall into three stages of a pipeline: pre-process, in-process, and post-process \cite{mehrabi2019survey}. Pre-processing techniques transform the data so that discrimination characteristics are removed prior to model training \cite{lahoti2019ifair, NIPS2017_6988}. Our work does not fit into this category of techniques but instead can be viewed as either an in-processing or post-processing method. Post-processing techniques treat the learned model as a black box and modify the output to remove discrimination \cite{FairnessExposureInRankings:Singh, equalityOfOpportunity:Hardt, LinkedInReRanking:Geyik, MatchmakingFairness:Paraschakis, fair-Reranking:recsys:2019}. Post-processing techniques are particularly attractive to industry since their treatment of the predictor as a black-box makes for a manageable integration into an existing pipeline \cite{AdressingAlgorithmicBias:Gathright, LinkedInReRanking:Geyik}. In-processing techniques attempt to remove discrimination during the model training process by incorporating changes into the objective function. Recent work has shown the effectiveness of both adversarial learning \cite{AdversariallyLearningFairRepresentations:Beutel, Louizos:CoRR2016, Madras:CoRR2018} and regularization \cite{FairnessAwareRegularizer, DBLP:journals/corr/YaoH17, PairwiseFairness} as in-processing methods for addressing fairness. Our work specifically builds upon the line of research that addresses fairness via regularization. } \subsection{Hybrid Recommenders using Probabilistic Soft Logic} \label{sec:Hyper} Probabilistic soft logic (\PSL) is a probabilistic programming language that has been shown to be effective for hybrid recommender systems \cite{kouki:recsys15}. \PSL's advantages include the ability to easily write interpretable, extendable, and explainable hybrid systems \cite{kouki:recsys17}. \PSL \, models specify probabilistic dependencies using logical and arithmetic rules; the rules, combined with data, are translated into a conditional random field referred to as a \emph{hinge-loss Markov random field (HL-MRF)} \cite{bach:jmlr17}. Given a set of evidence $\mathbf{x}$ and continuous unobserved variables $\mathbf{y}$, the inference objective is given by: \vspace{-1mm} \begin{equation} \min_{\mathbf{y} \in [0, 1]^n} \quad \sum_{i}^{k} w_{i} \phi_{i}(\mathbf{y}, \mathbf{x}) \label{eq:Rec_Obj} \end{equation} \noindent where $k$ is the number of unique hinge-loss potential functions, $\phi_i(\cdot)$, and $w_i$ are the corresponding scalar weights. In addition to expressivity, an important advantage of HL-MRFs is their scalability; inference is convex, and a variety of specialized optimizers have been proposed \cite{srinivasan:aaai20} (more details about \PSL \, in \secref{sec:appendix}). Following Kouki et al. \cite{kouki:recsys15}, the following collection of rules expresses a simple, intuitive hybrid recommender model: \paragraph{\bf Demographic and Content Similarity:} \, Demographic-based approaches are built upon on the observation that users with similar demographic properties will tend to make similar ratings. Likewise, content-based approaches are built upon on the observation that items with similar content will be rated similarly by users. This is different from the collaborative filtering approach as the rating patterns of users and items is strictly not considered in the similarity calculation. \vspace{-1mm} \begin{gather*} \pslpred{Rating}(\pslarg{U1}, \pslarg{I}) \psland \pslpred{SimUserDemo}(\pslarg{U1}, \pslarg{U2}) \pslthen \pslpred{Rating}(\pslarg{U2}, \pslarg{I}) \\ \pslpred{Rating}(\pslarg{U}, \pslarg{I1}) \psland \pslpred{SimItemContent}(\pslarg{I1}, \pslarg{I2}) \pslthen \pslpred{Rating}(\pslarg{U}, \pslarg{I2}) \end{gather*} \vspace{-1mm} The predicate $\pslpred{Rating}(\pslarg{U}, \pslarg{I})$ represents the normalized value of the rating that user $\pslarg{U}$ provided for item $\pslarg{I}$.\\ $\pslpred{SimUserDem}(\pslarg{U1}, \pslarg{U2})$ and $\pslpred{SimItemContent}(\pslarg{I1}, \pslarg{I2})$ represent the similarity of users $\pslarg{U1}$ and $\pslarg{U2}$ and items $\pslarg{I1}$ and $\pslarg{I2}$. \paragraph{\bf Neighborhood-based Collaborative Filtering:} \, Neighborhood-based collaborative filtering methods capture the notion that users that have rated items similarly in the past will continue to rate new items similarly. An analogous and transposed notion applies to items, i.e., items that have been rated similarly by many of the same users will continue to be rated similarly. Similarity in this context is based solely on rating patterns and can be measured using various metrics. \vspace{-1mm} \begin{gather*} \pslpred{Rating}(\pslarg{U1}, \pslarg{I}) \psland \pslpred{SimUsers}(\pslarg{U1}, \pslarg{U2}) \pslthen \pslpred{Rating}(\pslarg{U2}, \pslarg{I}) \\ \pslpred{Rating}(\pslarg{U}, \pslarg{I1}) \psland \pslpred{SimItems}(\pslarg{I1}, \pslarg{I2}) \pslthen \pslpred{Rating}(\pslarg{U}, \pslarg{I2}) \end{gather*} \vspace{-1mm} $\pslpred{SimUsers}(\pslarg{U1}, \pslarg{U2})$ and $\pslpred{SimItems}(\pslarg{I1}, \pslarg{I2})$ represent the similarity of users $\pslarg{U1}$ and $\pslarg{U2}$ and items $\pslarg{I1}$ and $\pslarg{I2}$, respectively. \paragraph{\bf Local Predictor Prior:} \, One of the advantages of the \Hyper \, system is its ability to combine multiple recommendation algorithms into a single model in a principled fashion. Recommender predictions are incorporated as non-uniform priors in the \PSL \, model using the pattern shown below. \begin{gather*} \pslpred{LocalPredictor}(\pslarg{U}, \pslarg{I}) = \pslpred{Rating}(\pslarg{U}, \pslarg{I}) \end{gather*} The predicate $\pslpred{LocalPredictor}(\pslarg{U}, \pslarg{I})$ represents the prediction made by the external recommendation algorithm. \paragraph{\bf Mean-Centering Priors:} \, Based on the above rules, ratings are propagated across similar users, and if two users have different average ratings, then these ratings may actually bias one another too much. To counter this effect, the following rules bias ratings towards the average user and item rating calculated from the observed ratings: \begin{gather*} \pslpred{AverageUserRating}(\pslarg{U}) = \pslpred{Rating}(\pslarg{U}, \pslarg{I}) \\ \pslpred{AverageItemRating}(\pslarg{I}) = \pslpred{Rating}(\pslarg{U}, \pslarg{I}) \end{gather*} The predicates $\pslpred{AverageItemRating}(\pslarg{I})$ and $\pslpred{AverageUserRating}(\pslarg{U})$ represent the average normalized value of the ratings associated with user $\pslarg{U}$ and item $\pslarg{I}$, respectively. \subsection{FairPSL} Farnadi et al. \cite{fairHyper:RecSys} introduced two collections of rules that can be added to a \PSL \, recommender system to address disparities derived from training data and observations. The authors use the same metrics we consider as proxies to measure this notion of disparity. Our work is different in that we give the modeler a finer level of control. Rather than attempting to capture multiple notions of fairness at once, we propose techniques that integrate specific fairness metrics into the \PSL\, inference objective as regularizers. In this way, the modeler is able to tune the degree of the specific metric to the domain they are working in simply by adjusting the weight of the additional rules. \commentout{ \subsection{Fairness Metrics} In this work, we focus on the fairness metrics non-parity and value unfairness. The definitions of these metrics are provided in \tabref{tab:fairness_metrics}. The two user groups we have selected to define as the protected and unprotected groups are are female and male, respectively. For the remainder of this paper we will let $g$ represent the set of female users, and $\neg g$ the set of male users, $\textbf{R}$ is the set of ratings in the dataset, $m$ is the number of predictions made by the model, $n$ is the number of unique items in the dataset, and $v_{i,j}$ and $r_{i,j}$ are the predicted and true rating user $i$ gives item $j$, respectively. For the fairness metric definitions we use $E_{g}[v]$ and $E_{\neg g}[v]$ to represent the average predicted ratings for $g$ and $\neg g$, respectively, $E_{g}[v]_{j}$ and $E_{\neg g}[v]_{j}$ represent the average predicted ratings for movie $j$ for $g$ and $\neg g$, respectively, and $E_{g}[r]_{j}$ and $E_{\neg g}[r]_{j}$ represent the average true ratings for movie $j$ for $g$ and $\neg g$, respectively \begin{table*}[h] \caption{Fairness Metrics} \centering \begin{tabular}{l l} \hline Metric & Definition \\ \hline \textit{Non-Parity} \cite{DBLP:journals/corr/YaoH17, FairnessAwareRegularizer}& $U_{par}(v) = |(E_{g}[v] - E_{\neg g}[v])|$\\ \textit{Value} \cite{DBLP:journals/corr/YaoH17} & $U_{val}(y) = \frac{1}{n} \sum_{j=1}^{n} |(E_{g}[v]_{j}] - E_{g}[r]_{j}]) - (E_{\neg g}[v]_{j} - E_{\neg g}[r]_{j}])|$\\ \hline \end{tabular} \label{tab:fairness_metrics} \end{table*} } \subsection{In-Process Fairness Intervention} The baseline hybrid recommender system (\secref{sec:Hyper}) uses cosine similarity for the similarity predicates and three local predictors, non-negative matrix factorization (NMF) \cite{lee2001algorithms}, biased singular value decomposition (SVD) \cite{koren2009matrix}, and a content-based multinomial Naive Bayes multi-class classifier with Laplace smoothing that is trained using the demographic and content information of the user and item, respectively. Five versions of the \PSL \, recommender system, extending the baseline model, are implemented: \commentout{ The baseline hybrid recommender system discussed in \secref{sec:Hyper} is built with the following implementation details. The similarity predicates all represent calculated cosine similarities. Furthermore, three local predictors are employed. The first two are the matrix factorization based approaches, non-negative matrix factorization (NMF) \cite{lee2001algorithms} and biased singular value decomposition (SVD) \cite{koren2009matrix}. The third local predictor is a content-based multinomial Naive Bayes multi-class classifier with Laplace smoothing that is trained using the demographic and content information of the user and item, respectively. Five versions of the \PSL \, recommender system, extending the baseline model, are implemented: } \begin{itemize} \item \textbf{\PSL \, Base:} demographic and content similarity, collaborative filtering, local predictor, and mean-centering rules \item \textbf{\HyperFair (NP):} The \textbf{\PSL \, Base} model with the non-parity fairness rules. \item \textbf{\HyperFair (Val):} The \textbf{\PSL \, Base} model with the value fairness rules. \item \textbf{\HyperFair (NP + Val):} The \textbf{\PSL \, Base} model with both the non-parity and value fairness rules. \item \textbf{Fair \PSL:} The \textbf{\PSL \, Base} model with rules introduced by Farnadi et al. \cite{fairHyper:RecSys}. \end{itemize} We also implemented three of the fair matrix factorization methods introduced by Yao and Huang \cite{DBLP:journals/corr/YaoH17} using the hyperparameters and training methods chosen by the authors, i.e., we use a L2 regularization term $\lambda = 10^{-3}$ and learning rate of $0.1$ for $500$ iterations of Adam optimization using the full gradient. The first is the baseline matrix factorization based approach which we refer to as \textbf{MF}. The second and third methods are where the matrix factorization objective function is augmented with the smoothed non-parity and value unfairness metrics, which we refer to as \textbf{MF NP} and \textbf{MF Val}, respectively. For both the \HyperFair \, models we introduced in this work and the matrix factorization methods, we set the fairness regularization parameter to $1.0$. We measure the prediction performance of each of the models using the RMSE of the rating predictions. The unfairness of the predictions are measured using the metrics defined in \secref{sec:models}. The prediction performance and fairness metrics are measured across 5 folds of the \MovieLens \, dataset and we report the mean and standard deviation for each model. We bold the best value, and values not statistically different from the best with $p < 0.05$ for a paired sample t-test. \begin{table*}[t] \caption{Prediction performance(RMSE) and unfairness(Non-Parity and Value) of recommender systems on \MovieLens 1m} \centering \begin{tabular}{|l|c|c|c|c|} \hline \textbf{Model} & \textbf{RMSE (SD)} & \textbf{Non-Parity (SD)} & \textbf{Value (SD)}\\ \hline \hline MF & $0.945 (1.0e\hbox{-}3)$ & $0.0371(1.6e\hbox{-}3)$ & $0.349 (6.0e\hbox{-}3)$ \\ \hline MF NP & $0.945(1.0e\hbox{-}3)$ & $\mathbf{0.0106(2.0e\hbox{-}3)}$ & $0.351(6.3e\hbox{-}3)$ \\ \hline MF Val & $0.950(6.4e\hbox{-}4)$ & $0.0446(3.0e\hbox{-}3)$ & $0.343(3.4e\hbox{-}3)$ \\ \hline \hline Fair \PSL & $\mathbf{0.932(9.7e\hbox{-}4)}$ & $0.0274(9.6e\hbox{-}4)$ & $\mathbf{0.332(5.5e\hbox{-}3)}$ \\ \hline \hline PSL Base & $\mathbf{0.931 (1.2e\hbox{-}3)}$ & $0.0270 (1.4e\hbox{-}3)$ & $\mathbf{0.330 (4.4e\hbox{-}3)}$ \\ \hline \HyperFair (NP) & $0.945 (1.1e\hbox{-}2)$ & $0.0215 (5.0e\hbox{-}3)$ & $\mathbf{0.338(9.9e\hbox{-}3)}$ \\ \hline \HyperFair (Val) & $\mathbf{0.932(1.1e\hbox{-}3)}$ & $0.0267(8.6e\hbox{-}4)$ & $\mathbf{0.333(6.9e\hbox{-}3)}$ \\ \hline \HyperFair (NP + Val) & $\mathbf{0.932 (1.1e\hbox{-}3)}$ & $0.0274(1.4e\hbox{-}3)$ & $\mathbf{0.331(4.5e\hbox{-}3)}$ \\ \hline \end{tabular} \label{tab:fairness_results} \end{table*} We can see from \tabref{tab:fairness_results} that the \HyperFair \, models either improved on the targeted fairness metric over \textbf{\PSL \, Base} or achieved results that were not significantly different from the best \PSL \, model. Notably, \textbf{\HyperFair(NP)} achieved significantly better non-parity unfairness over \textbf{\PSL \, Base} and the anticipated performance decrease in the RMSE of the rating predictions was minimal. In fact, the \textbf{\HyperFair(NP)} still achieved the same level of prediction accuracy as the highest performing matrix factorization method. Another interesting takeaway from \tabref{tab:fairness_results} is that when attempting to optimize for both non-parity and value unfairness simultaneously in \textbf{\HyperFair(NP + Val)}, the effectiveness of the non-parity rule decreases. This effect can also be observed in the \textbf{ Fair \PSL} of \cite{farnadi2018fairness}, where both fairness notions are attempting to be addressed with a single set of rules. A potential explanation of this could be that the value unfairness and non-parity unfairness metrics are opposing one another, that is to say that a set of ratings that performs well on value unfairness in this dataset may actually perform poorly on non-parity unfairness, and vice-versa. Fully understanding this behavior and controlling the tradeoff between the metrics is a direction for future work. When comparing the \PSL \, models to the matrix factorization models from \cite{DBLP:journals/corr/YaoH17}, we see that \PSL \, consistently achieves better RMSE and value unfairness, while matrix factorization achieves better non-parity unfairness values. It is important to note that \tabref{tab:fairness_results} only reflects metrics values for the regularization parameter $w_f = 1.0$. In the next set of experiments, we show how tuning the non-parity unfairness regularization parameter can effectively yield predictions that fall within a desired non-parity unfairness threshold. \subsection{Post-Process Fairness Intervention} \label{post_process_exp_section} Another way we employ our proposed methods is as an interpretable fair retrofitting procedure for predictions from an arbitrary black-box model. To show the effectiveness of our methods for this task, we create a simple \PSL \, model that contains only the NMF local predictor rule and the fairness rule. We refer to these models as \textbf{NMF + NP \PSL} and \textbf{NMF + Val \PSL} for the models with non-parity and value unfairness rules, respectively. The weights of the fairness rules in the templates are varied to show the tradeoff between prediction performance and the fairness metric. For both models, we run experiments for all $w_f \in \{0.0, 0.01, 0.1, \cdots, 10000.0 \}$. \begin{figure}[t] \centering \subfloat[]{\includegraphics[width=0.4\textwidth]{Figures/NPvsFairnessRegularizer.png}}\hfill \subfloat[]{\includegraphics[width=0.4\textwidth]{Figures/ValuevsFairnessRegularizer.png}} \caption{(a) Non-Parity unfairness and RMSE performance of \textbf{NMF + NP \PSL} vs the value of the fairness regularization parameter.\\ (b) Value unfairness and RMSE performance of \textbf{NMF + Val \PSL} vs the value of the fairness regularization parameter.} \label{fig:FairnessvsRegularizer} \end{figure} \figref{fig:FairnessvsRegularizer} shows both the RMSE and the fairness of the ratings predicted by the NMF model. We see that \textbf{NMF + NP \PSL} begins to improve the predictions' fairness without significantly decreasing the performance when the regularization parameter is set to $100.0$. When the parameter exceeds $10.0$, there is a significant decrease in the non-parity unfairness, reaching nearly $0.0$, while the increase in RMSE is still not drastic. The \textbf{Val + NP \PSL} model initially does not improve the value unfairness of the NMF rating predictions. We suspect this behavior suggests that the quality of the estimator for the group average item rating needs improvement and initially biases the predictions in a detrimental way and is a direction for future investigation. There is a region where the value unfairness begins a downward trend with respect to the fairness regularizer, as is desired. This is an encouraging result, showing that the weight of the fair rule generally has the desired relationship with value unfairness. \section{Introduction} \label{sec:intro} As the ubiquity of recommender systems continues to grow, concerns of bias and fairness are becoming increasingly urgent to address. An algorithm oblivious to any form of fairness has the potential to propagate, or even amplify, discrimination \cite{MenAlsoLikeShopping:Zhao, DiscriminationAds}. In doing so, certain groups can be severely impacted by the recommendations provided. For instance, one study showed that an algorithm for targeted advertising of jobs in the STEM fields was delivering more advertisements to men than women with similar professional backgrounds \cite{Lambrecht:biasedAdvertising}. The need to integrate fairness and ensure that different groups of users are experiencing the same level of utility from recommender systems has been acknowledged by the artificial intelligence community \cite{mehrabi2019survey, pmlr-v81-ekstrand18b}. We introduce techniques for integrating fairness metrics as regularizations of a joint inference objective function of a probabilistic graphical model. Our approach naturally leads to novel collections of rules that can be added to a probabilistic soft logic (\PSL) \cite{bach:jmlr17} model. Furthermore, the weights of the rules can be translated as regularization parameters which can be tuned by the modeler or via weight learning \cite{bach:jmlr17}. This motivates a general framework for introducing multiple soft fairness constraints in a hybrid recommender system which we refer to as \HyperFair. \commentout{ Farnadi et al. \cite{fairHyper:RecSys} introduced collections of rules that can be added to a \PSL \, recommender system to address disthe same fairness metrics we are considering in this research. Our work is different in that we give the modeler a finer level of control. Rather than attempting to capture multiple definitions of fairness at once, we propose interventions that integrate specific fairness metrics into the \PSL\, inference objective. In this way, the modeler is able to tune the degree of the specific fairness constraint to the domain they are working in by simply adjusting a single parameter. } \HyperFair \, builds upon the \Hyper \, recommender system introduced by Kouki et al. \cite{kouki:recsys15} by adding the ability to enforce multiple soft fairness constraints to the model predictions. This framework is general enough to capture previous work by Farnadi et al. \cite{fairHyper:RecSys} who proposed \PSL \, modelling techniques for addressing disparities stemming from imbalanced training data and observation bias. We develop a generic technique, provide principled derivations of the soft constraints, and show how a set of fairness metrics can be precisely targeted. Our key contributions are as follows: 1) we introduce the \HyperFair \, framework for enforcing soft fairness constraints in a hybrid recommender system; 2) we show that non-parity and value unfairness can be written as linear combinations of hinge-loss potentials and can thus be integrated into the \PSL \, inference objective via template rules; 3) we perform an empirical analysis using the \MovieLens\, dataset and show both how our fairness rules can be used internally or as a method for retrofitting the output of a black-box algorithm to increase the fairness of predictions; and 4) we show our method improves fairness over baseline models and outperforms a state-of-the-art fair recommender \cite{DBLP:journals/corr/YaoH17} in terms of RMSE and value unfairness. \commentout{ The contributions we make in this paper are the following: 1) we theoretically motivate two collections of \PSL\, rules that can be added to model templates to integrate variations of fairness metrics into the MAP inference objective; 2) we perform an empirical analysis of the methods we propose using the \MovieLens\, dataset and show how our fairness rules can be used as extensions of a \PSL \, model or as a method for retrofitting the output of a black-box algorithm to increase the fairness of predictions. } \commentout{ The remainder of this paper is structured as follows: In \secref{sec:background}, we provide the reader with the necessary background for understanding the motivations and approaches proposed in this paper. We introduce the modeling framework we utilize in this work, \PSL, and then give the fairness definitions we will be working with. Next, in \secref{sec:models}, we introduce the \PSL \, recommender system we will be working with for the empirical evaluation and then motivate the approaches we take to integrate the fairness metrics into the \PSL \, inference objective. Then, in \secref{sec:experiments}, we empirically validate our approach with experiments comparing our model to two state-of-the-art fair recommender sytems. Finally, in \secref{sec:conclusion}, we close with concluding remarks and propose possible directions for future research. } \newpage \section{\HyperFair} \label{sec:models} In this section, we introduce \HyperFair, a framework for enforcing multiple soft fairness constraints in a hybrid recommender system. \HyperFair \, is a natural development to \Hyper \cite{kouki:recsys15} that incorporates fairness metrics, $U$, via regularization of the HL-MRF MAP inference objective \eqref{eq:Rec_Obj}: \begin{equation} \min_{\mathbf{y} \in [0, 1]^n} \quad w_f U + \sum_{i}^{k} w_{i} \phi_{i}(\mathbf{y}, \mathbf{x}) \label{eq:regularized_rec_obj} \end{equation} where $w_f \in \mathcal{R}^+$ is the scalar regularization parameter. A fairness metric, $U$, in a \HyperFair \, model is expressed as a linear combination of hinge loss potential functions and can then be written as a \PSL \, rule. A particularly active and productive area of research is defining fairness metrics, and there are many metrics that could be targeted by the proposed HyperFair framework. Following the line of work in \cite{DBLP:journals/corr/YaoH17} and \cite{fairHyper:RecSys}, we focus on the unfairness metrics of non-parity and value unfairness defined in the following sections. These metrics were introduced in \cite{DBLP:journals/corr/YaoH17} specifically for addressing disparity stemming from biased training data in collaborative-filtering based recommender systems. For the remainder of this paper, we will let $g$ represent the protected group of users, i.e., $g$ is a subset of all the users present in the data that have been identified as possessing a protected attribute. Then, $\neg g$ represents the remaining subset of users that do not possess the protected attribute. We let $\textbf{R}$ be the set of ratings in the dataset, $m$ the number of predictions made by the model, $n$ the number of unique items in the dataset, and $v_{i,j}$ and $r_{i,j}$ the predicted and true rating user $i$ gives item $j$, respectively. For the fairness metric definitions, we use $E_{g}[v]$ and $E_{\neg g}[v]$ to represent the average predicted ratings for $g$ and $\neg g$, respectively, $E_{g}[v]_{j}$ and $E_{\neg g}[v]_{j}$ represent the average predicted ratings for item $j$ for $g$ and $\neg g$, respectively, and $E_{g}[r]_{j}$ and $E_{\neg g}[r]_{j}$ represent the average true ratings for item $j$ for $g$ and $\neg g$, respectively. \subsection{Non-parity Unfairness} Non-parity unfairness, $U_{par}$, aims to minimize the disparity in the overall average predicted ratings of the protected and unprotected groups. $$U_{par}(v) = |(E_{g}[v] - E_{\neg g}[v])|$$ In this section, we motivate a collection of rules that can be added to the \PSL \, recommender system as an approach to minimize this metric. We start by introducing two new free variables to the inference problem \eqref{eq:Rec_Obj}, $y_{n + 1}$ and $y_{n + 2}$, and the following hard constraints without breaking the convexity of \PSL \, inference: \begin{gather*} c_{1}(\mathbf{y}, \mathbf{x}) := y_{n + 1} - \frac{1}{\lvert \{(i,j) : ((i, j) \in \mathbf{R}) \land g_{i} \}\rvert} \sum_{(i,j) : ((i, j ) \in \mathbf{R}) \land g_{i}} v_{i,j} = 0 \\ c_{2}(\mathbf{y}, \mathbf{x}) := y_{n + 2} - \frac{1}{\lvert \{(i,j) : ((i, j ) \in \mathbf{R}) \land \neg g_{i} \}\rvert} \sum_{(i,j) : ((i, j ) \in \mathbf{R}) \land \neg g_{i}} v_{i,j} = 0 \end{gather*} With the two additional hard constraints, the solution of the new optimization problem is a state such that $y^{*}_{n + 1} = E_{g}[v]$ and $y^{*}_{n + 2} = E_{\neg g}[v]$. The two hard constraints can be added to the \PSL \, model by introducing the following pair of rules: \begin{gather*} \pslpred{Rating}(+ \pslarg{U}, + \pslarg{I}) / m_{g} = \pslpred{ProtectedAvgRating}(\pslarg{c}) \, . \, \{\pslarg{U}: \pslpred{Protected}(\pslarg{U})\} \, \{\pslarg{I}: \pslpred{ProtectedItem}(\pslarg{I})\} \\ \pslpred{Rating}(+ \pslarg{U}, + \pslarg{I}) / m_{\neg g} = \pslpred{UnProtectedAvgRating}(\pslarg{c}) \, . \, \{\pslarg{U}: \pslpred{UnProtected}(\pslarg{U})\} \, \{\pslarg{I}: \pslpred{UnProtectedItem}(\pslarg{I})\} \end{gather*} where $m_{g}$ and $m_{\neg g}$ are the total number of ratings for the protected and unprotected group, respectively, and are added as a preprocessing step. The predicates $\pslpred{ProtectedAvgRating}(\pslarg{c})$ and $\pslpred{UnProtectedAvgRating}(\pslarg{c})$ hold the values of $y_{n+1}$ and $y_{n+2}$ , respectively. We can now define the two following hinge-loss potentials: \begin{align*} \phi_{k+1} (\mathbf{y}, \mathbf{x}) = \max \Big \{1 - y_{n+1} - (1 - y_{n + 2}), 0 \Big\} && \phi_{k+2}(\mathbf{y}, \mathbf{x}) = \max \Big \{1 - y_{n+2} - (1 - y_{n + 1}), 0 \Big\} \end{align*} \noindent Observe that $U_{par} = \phi_{k+1} (y_{n+1}^{*}, \mathbf{x}) + \phi_{k+2} (y_{n+2}^{*}, \mathbf{x})$. This transformation allows us to push the regularizer in \eqref{eq:regularized_rec_obj} into the summation to create a valid \PSL \, objective function. Formally, if we let $w_{k + 1} = w_{k + 2} = w_f$, then: \begin{align} \argmin_{\mathbf{y} \in [0, 1]^n} \quad w_f U_{par} + \sum_{i}^{k} w_{i} \phi_{i}(\mathbf{y}, \mathbf{x}) \quad \equiv \quad \argmin_{\mathbf{y} \in [0, 1]^{n + 2}} \quad & \sum_{i}^{k + 2} w_{i} \phi_{i}(\mathbf{y'}, \mathbf{x}) \label{eq:NP_Rec_Intervention_Obj} \\ \textrm{s.t.} \quad & c_{1}(\mathbf{y}, \mathbf{x}) = 0, \ c_{2}(\mathbf{y}, \mathbf{x}) = 0 \nonumber \end{align} \noindent Furthermore, we now have that the right hand side of \eqref{eq:NP_Rec_Intervention_Obj} is a valid HL-MRF that can be instantiated using \PSL. The following rule can be added to a \PSL \, model to obtain the two desired ground potentials $\phi_{k+1}$ and $\phi_{k+2}$. \begin{gather*} \pslpred{ProtectedAvgRating}(\pslarg{c}) = \pslpred{UnProtectedAvgRating}(\pslarg{c}) \end{gather*} Altogether, this method for addressing non-parity unfairness results in a total of $4$ additional ground potentials and $3$ additional rules in the \PSL \, template and achieves precisely the desired semantics. Furthermore, the regularization term $w_f$ is directly translated as a weight in \PSL \, that can be tuned by the modeler or via weight learning. \subsection{Value Unfairness} Next, we motivate our approach in addressing value unfairness. Value unfairness aims to minimize the expected inconsistency in the signed estimation error between the protected and unprotected user groups. $$U_{val}(y) = \frac{1}{n} \sum_{j=1}^{n} |(E_{g}[v]_{j} - E_{g}[r]_{j}) - (E_{\neg g}[v]_{j} - E_{\neg g}[r]_{j})|$$ A key difference between this metric and non-parity is that the truth values of the predictions are included in the definition of the metric and thus cannot be directly targeted during inference. In \PSL \, the truth values of the target predicates are withheld until evaluation. Therefore, the approach we take is to estimate properties of the rating distribution prior to running the model to approximate the desired inference objective function \eqref{eq:regularized_rec_obj}. We start the derivation of the fairness rules we will be adding to the \PSL \, model by augmenting the inference optimization problem of \eqref{eq:Rec_Obj} with two hard constraints for every item in the dataset, that is for all $j \in I = \{j : (i,j) \in \mathbf{R}\}$. Note that these constraints do not break the convexity properties of the original optimization problem. \begin{gather*} c_{1,j}(y_{n + j}, \mathbf{x}) := y_{n + j} - \frac{1}{\lvert \{i : ((i, j) \in \mathbf{R}) \land g_{i} \}\rvert} \sum_{i : ((i, j ) \in \mathbf{R}) \land g_{i}} v_{i,j} = 0 \\ c_{2,j}(y_{n + j + \lvert I \rvert}, \mathbf{x}) := y_{n + j + \lvert I \rvert} - \frac{1}{\lvert \{i : ((i, j) \in \mathbf{R}) \land \neg g_{i} \}\rvert} \sum_{i : ((i, j) \in \mathbf{R}) \land \neg g_{i}} v_{i,j} = 0 \end{gather*} With these hard constraints, the setting of the free variables $y_{n + 1}, \cdots , y_{n + \lvert I \rvert}, y_{n + \lvert I \rvert} \cdots y_{n + 2 \lvert I \rvert}$ in the optimal solution will be such that $(y^{*}_{n + 1} = E_g[v]_1), \cdots , (y^{*}_{n + \lvert I \rvert} = E_g[v]_{\lvert I \rvert}), (y^{*}_{n + 1 + \lvert I \rvert} = E_{\neg g}[v]_{1}) \cdots (y^{*}_{n + 2 \lvert I \rvert} = E_{\neg g}[v]_{ \lvert I \rvert})$. These hard constraints are added to the \PSL \, inference objective with the following rule: \begin{gather*} \pslpred{Rating}(+ \pslarg{U}, \pslarg{I}) / @Max[1, \lvert \pslarg{U} \rvert] = \pslpred{PredGroupAvgItemRating}(\pslarg{G}, \pslarg{I}) \, . \, \{\pslarg{U}: \pslpred{target}(\pslarg{U}, \pslarg{I}) \land \pslpred{Group}(\pslarg{G}, \pslarg{U})\} \end{gather*} $\pslpred{PredGroupAvgItemRating}(\pslarg{G}, \pslarg{I})$ represents the average of the predicted ratings that users in group $G$ gave item $I$. The term $G$ in this rule represents either the unprotected or protected group. At the time of inference, we cannot calculate the average true values of the ratings for either the protected or unprotected group, $E_{g}[r]_{j}$ or $E_{\neg g}[r]_{j}$, since the true rating value information is withheld until evaluation. Instead, the group average item rating is estimated using the observed ratings, $\hat{E}_{g}[r]_{j} = \frac{1}{\lvert \{i : ((i, j) \in \mathbf{R}_{obs}) \land g_{i} \}\rvert} \sum_{i : ((i, j) \in \mathbf{R}_{obs}) \land g_{i}} v_{i,j}$ and similarly, $\hat{E}_{\neg g}[r]_{j} = \frac{1}{\lvert \{i : ((i, j) \in \mathbf{R}_{obs}) \land \neg g_{i} \}\rvert} \sum_{i : ((i, j) \in \mathbf{R}_{obs}) \land \neg g_{i}} v_{i,j}$, where $\mathbf{R}_{obs}$ is the set of observed ratings. The observed group average item rating is calculated in a preprocessing step and is added to the model as an observed predicate, $\pslpred{ObsGroupAvgItemRating}(\pslarg{G}, \pslarg{I})$. We can now define the following set of hinge-loss potentials: \begin{align*} \phi_{k + j}(\mathbf{y}, \mathbf{x}) & = \max\Big \{(y_{n + j} - \hat{E}_{g}[r]_{j}) - (y_{n + j + \lvert I \rvert} - \hat{E}_{\neg g}[r]_{j}), 0 \Big \} \\ \phi_{k + j + \lvert I \rvert}(\mathbf{y}, \mathbf{x}) & = \max\Big \{(y_{n + j + \lvert I \rvert} - \hat{E}_{\neg g}[r]_{j}) - (y_{n + j} + \hat{E}_{g}[r]_{j}), 0 \Big \} \end{align*} Then, in the optimal state: $U_{val} \approx n \sum_{j = 1}^{2 \lvert I \rvert} \phi_{k + j} (\mathbf{y}^{*}, \mathbf{x}) =: \hat{U}_{val}$. This transformation allows us to push an approximation of the regularizer in \eqref{eq:regularized_rec_obj} into the summation of the HL-MRF MAP inference objective function. Formally, if we let $w_{k+j} = w' = \frac{1}{n} w_{Val}$ for all $j \geq 0$, then: \begin{align} \argmin_{\mathbf{y} \in [0, 1]^n} \quad w_f \hat{U}_{val} + \sum_{i}^{k} w_{i} \phi_{i}(\mathbf{y}, \mathbf{x}) \quad \equiv \argmin_{\mathbf{y'} \in [0, 1]^{n + 2|I|}} \quad & \sum_{i}^{k + 2|I|} w_{i} \phi_{i}(\mathbf{y'}, \mathbf{x}) \label{eq:val_Rec_Intervention}\\ \textrm{s.t.} \quad & c_{1, j}(\mathbf{y'}, \mathbf{x}) = 0, \ c_{2, j}(\mathbf{y'}, \mathbf{x}) = 0, \ \forall j \in I \nonumber \end{align} Further, we have \eqref{eq:val_Rec_Intervention} is a valid HL-MRF that can be instantiated using \PSL. Specifically, the following rule in \PSL \, results in the desired potentials $\phi_{k + 1}, \cdots, \phi_{k + 2 \lvert I \rvert}$: \begin{align*} \pslpred{PredGroupAvgItemRating} (\pslarg{G1}, \pslarg{I}) & - \pslpred{ObsGroupAvgItemRating} (\pslarg{G1}, \pslarg{I}) \\ = \pslpred{PredGroupAvgItemRating} (\pslarg{G2}, \pslarg{I}) & - \pslpred{ObsGroupAvgItemRating} (\pslarg{G2}, \pslarg{I}) \end{align*} This approach approximates the targeted fairness metric using statistics from the set of observations. The approximation is then transformed into a summation of hinge-loss potential functions that could be pushed into a \PSL \, inference objective function. Furthermore, the weight of the arithmetic rule in this intervention can be interpreted as a scaled version of the regularization parameter of the fairness metric in \eqref{eq:regularized_rec_obj}. \section{Related Works} \label{sec:Related Works} Generally methods for addressing unfairness can fall into three stages of a pipeline: pre-process, in-process, and post-process \cite{mehrabi2019survey}. Pre-processing techniques transform the data so that discrimination characteristics are removed prior to model training \cite{lahoti2019ifair, NIPS2017_6988}. Our work does not fit into this category of techniques but instead can be viewed as either an in-processing or post-processing method. Post-processing techniques treat the learned model as a black box and modify the output to remove discrimination \cite{FairnessExposureInRankings:Singh, equalityOfOpportunity:Hardt, LinkedInReRanking:Geyik, MatchmakingFairness:Paraschakis}. This class of approach is a simple way to integrate fairness constraints into an existing pipeline, which is a common practical requirement for industry applications \cite{AdressingAlgorithmicBias:Gathright, LinkedInReRanking:Geyik} In-processing techniques attempt to remove discrimination during the model training process, either by incorporating changes into the objective function or by imposing a constraint. Recent work has shown the effectiveness of both adversarial learning \cite{AdversariallyLearningFairRepresentations:Beutel, Louizos:CoRR2016, Madras:CoRR2018} and regularization \cite{FairnessAwareRegularizer, DBLP:journals/corr/YaoH17, PairwiseFairness} as in-processing methods for addressing fairness. Our work specifically builds upon the line of research that addresses fairness via regularization.
{'timestamp': '2020-09-21T02:18:10', 'yymm': '2009', 'arxiv_id': '2009.08952', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08952'}
arxiv
\section{Introduction} \label{sec:introduction} Genome-wide association studies (GWASs) explore the associations between genetic variants, called single-nucleotide polymorphisms (SNPs), and traits \citep{visscher2012five}. They have been successfully applied to identify numerous genetic variants associated with complex human diseases \citep{buniello2019nhgri}. In GWASs, it is common to measure multiple traits underlying complex diseases, because due to pleiotropy one genetic variant can influence multiple phenotypic traits \citep{solovieff2013pleiotropy}. For example, a number of genetic variants are associated with both fasting glucose and fasting insulin of type 2 diabetes \citep{Billings2010}; GWASs found a variant in gene SLC39A8 that has an influence on the risk of schizophrenia and Parkinson disease.\citep{pickrell2016detection}. In the last decade, single-trait methods has been widely adopted \citep{visscher201710} in which the association between the genetic variant and each single trait is tested one at a time. However, this type of methods suffers from several disadvantages. First, sometimes the association between a single SNP and a trait is too weak to be detected by itself. Second, it ignores the correlation structure among the traits, which leads to the loss of statistical power when the traits are truly correlated. Third, post-hoc combination of multiple tests without proper adjustment may lead to inflated type I error or compromised statistical power. As a result, there is an increasing need to develop powerful statistical methods that are capable of testing multiple traits simultaneously and properly. Various statistical methods have been developed and applied to multiple-trait studies. Following an overview of multiple-trait methods by \citet{Yang2012}, we classify the existing methods into three categories. The first category is to combine test statistics or p-values from univariate tests. The O'Brien method \citep{o1984procedures, wei1985combining} combines the test statistics from the individual test on each trait weighted by inverse variance. The sum of powered score tests (SPU) \citep{Pan2014} and adaptive SPU (aSPU) \citep{Zhang2014} combines the score test statistics derived from generalized estimation equations (GEE). The Trait-based Association Test that uses Extended Simes procedure (TATES) \citep{Sluis2013} exploits the correlation among p-values from each univariate test and generate a new test statistic. Fisher's method \citep{fisher1925statistical, yang2016efficient} and Cauchy's method \citep{liu2020cauchy} combines p-values of single-trait analyses and get the final p-values from known probability distributions. The second category is to reduce the dimensions of multiple traits. Principal components of heritability (PCH) \citep{Klei2008} collapses the multiple traits to a linear combination of traits which maximizes the heritability and then tests the associations based on transformed traits. Canonical correlation analysis \citep{Ferreira2009} finds the linear combination of traits maximizing the covariance between a SNP and all traits. It is equivalent to multivariate analysis of variance (MANOVA) when there is only one SNP \citep{Sluis2013}. The third category relies on regression models. MultiPhen \citep{OReilly2012} regresses genotypes on phenotypes via proportional odds logistic model. As mentioned, GEE has been utilized to generate score test statistics in aSPU \citep{Zhang2014}. Besides linear models, kernel regression models (KMRs) also play a role in multiple-trait analysis, including multivariate kernel machine regression \citep{maity2012multivariate}, multi-trait sequence kernel association test (MSKAT) \citep{Wu2016} and Multi‐SKAT \citep{dutta2019multi}. \citet{davenport2018powerful} extended KMRs to multiple binary outcomes. Currently, several limitations still exist in multiple-trait methods restricting their wide applications. First, many existing methods are unable to simultaneously analyze binary and continuous traits. For KMRs, multiple non-continuous traits can be both theoretically and computationally challenging and it is unclear how to integrate multiple different datatypes (e.g., multi-omics) \citep{larson2019review}. MANOVA is not applicable to non-Normal traits. Numerous studies in GWASs are case-control studies and incapability of processing binary traits greatly limits their application. Second, the methods may have inconsistent performance under various scenarios depending on the number of traits, the strength of correlation and the number of true associations, which are largely unknown in practice. Hence, there is a demand for methods with robust performance regardless of scenarios. Third, although many methods claimed the capability of handling covariates and confounders, few of them conducted the relevant simulations or real-data applications to demonstrate the type I error control and performance. As a matter of fact, our simulation study indicates the claims of some methods are inaccurate (see section \ref{sec:results}). In this paper, We propose a multiple-trait adaptive Fisher's (MTAF) method for multiple traits based on adaptive Fisher's (AF) method \citep{Song2016}. The remainder of this paper is organized as follows. In section \ref{sec:methods}, we elaborate the proposed method and introduce variations to tackle highly correlated traits. In section \ref{sec:results}, we evaluate the performance of MTAF using simulation and apply it to a real GWAS of substance addiction traits. In section \ref{sec:discussion}, we review the advantages and the limitations of the MTAF method and discuss our future work. \section{Methods} \label{sec:methods} Suppose there are $n$ independent subjects. For each subject $i=1,\ldots,n$, there are $K$ traits $\bm{Y_i}=(y_{i1},\ldots,y_{iK})'$ and $\bm{Y_k}=(y_{1k},\ldots,y_{nk})'$, and $x_i \in {0,1,2}$ is the genotype of a SNP coded as the number of minor alleles in the subject $i$. $\bm{x} = (x_1,\ldots,x_n)$ is the vector of all subjects' genotypes for this SNP. In terms of real applications, we suppose each subject $i$ has $M$ covariates $z_{i1},\dots,z_{iM}$ and $\bm{Z}=\{z_{im}\}_{n \times M}$. After adjusting for covariates, We aim to test the associations between the SNP and $K$ traits under the null hypothesis $H_0$ that none of the $K$ traits associates with the SNP. To construct the test statistics, the MTAF method combines the marginal p-values from the single-trait score tests in an adaptive way. At last, because our test statistic has no closed form, we conduct permutations to get the empirical p-values. \subsection{Score Test} Score test is one of the most popular test in GWASs of single traits, because it only requires fitting the null model thus is computationally inexpensive. Suppose for each SNP and subject $i$, a generalized linear model of the following form is assumed for the $k^{th}$ trait and the SNP with $M$ covariates: \begin{equation*} g_{k}(E(Y_{ik})) = x_{i} \cdot \beta_{k} + \sum_{m=1}^{M} z_{im} \cdot \alpha_{mk}, \label{eq:glm} \end{equation*} where $\beta_k$ is the effect of the SNP and $\alpha$'s are the effects of the M covariates on the $k^{th}$ trait. $g_k(\cdot)$ is the link function, which is identity function for continuous traits and logit function for binary traits. Different link functions make it possible to allow for both continuous traits and binary traits. Under $H_0: \beta_{k} = 0$, the test statistic of score test for the SNP is: \begin{equation*} U_k = \sum_{i=1}^n (x_i-\hat{x}_i)(Y_{ik}-\hat{Y}_{ik}), \label{eq:score} \end{equation*} where $\hat{x}_i$ is an estimate of $x_i$ and $\hat{Y}_{ik}$ is an estimate of $Y_{ik}$. Denote $\bm{V}$ as Fisher information matrix which is the covariance matrix of $\bm{U}=(U_1,\ldots,U_k)$ and $\mbox{Var}(U_k|H_0)=V_{kk}$ where $V_{kk}$ is the $k^{th}$ diagonal element of $\bm{V}$. Asymptotically, we have $U_k/\sqrt{V_{kk}} \sim \mathcal{N}(0,1)$ and then the p-values (either one-sided or two-sided) can be generated. We get the p-values of the single-trait score tests computationally by R package \textbf{statmod} \citep{RJ-2016-024}. \subsection{MTAF Method} Denote $p_1,...,p_K$ as the p-values of score tests between the K traits and the SNP. Let $S_k = - \sum_{i=1}^k{\log{p_{(i)}}}$ where $p_{(i)}$ is the $i^{th}$ smallest p-value and it is the sum of first $k$ smallest p-values. Then the p-value of $s_k$ is $p_{s_k} = P( S_k \ge s_k )$ where $s_k$ is the observed value of $S_k$. In practice, this p-value can be obtained by permutation. The proposed test statistic of the MTAF method is \begin{equation*} T_{MTAF} = \min_{1 \le k \le K} p_{s_k}. \end{equation*} \subsection{Permutation test} Since it is intractable to get the p-value of the test statistic analytically, we turn to apply the permutation procedure to get the empirical p-values. We intend to test the conditional independence between the SNP and the traits given the covariates, i.e.,$\bm{Y} \perp \bm{x} \mid \bm{Z}$. The permutation procedure should break the associations between $\bm{Y}$ and $\bm{x}$ while preserving the associations between $\bm{Y}$ and $\bm{Z}$ and between $\bm{x}$ and $\bm{Z}$. Simply permuting the genotype $\bm{x}$ leads to inflated type I error rate, because the correlation between the genotype and covariates are destroyed. Following \citet{potter2005permutation} and \citet{werft2010glmperm}, we permute residuals of regressions of $\bm{x}$ on $\bm{Z}$ for generalized regression models. In our method, we first regress the genotype on the covariates, then we permute the residuals derived from the regression. We replace the original genotype with the permuted residuals to perform score tests for the permuted data. It should be noted that even when no covariate is explicitly included in the mode, we still have a constant as our covariate. Specifically, we denote the vector of residuals of regressing $\bm{x}$ on $\bm{Z}$ as $\bm{e_{x}}$ and permute it for B times. In the $b^{th}$ permutation, we regress $\bm{Y_{k}}$ on $\bm{e_{x}^{(b)}}$ and get the score tests p-values $p_{k}^{(b)}$ for the coefficient of $\bm{e_{x}^{(b)}}$. After B permutations, we get a $(B+1) \times K$ matrix $\mathbbm{P}=\{p_{k}^{(b)} \}$. Each element $p_{k}^{(b)}$ is the p-value measuring the $k^{th}$ trait in the $b^{th}$ permutation for $1 \leq b \leq B$ and $p_{k}^{(0)}$ is the observed p-value. Based on $\mathbbm{P}$, we can construct the MTAF method's test statistics for both the observed data and permuted data. For the matrix $\mathbbm{P}$, we can calculate the empirical p-values of the MTAF method for the observed data and permuted data with the following steps: Suppose we have a $(B+1) \times K$ matrix of p-values $\mathbbm{P}$. \begin{enumerate} \item For each row $b \in \{ 0,1,...,B \}$, we calculate $s_k^{(b)}$ and \begin{equation*} p_{s_k}^{(b)} = \frac{1}{B+1} \sum_{j=0}^B \mathbbm{1}{\{s_k^{(j)} \geq s_k^{(b)}\}}, \end{equation*} where $\mathbbm{1}$ is the indicator function. \item Then we can get a vector $\bm{t}=(t_{MTAF}^{(0)},t_{MTAF}^{(1)},\dots,t_{MTAF}^{(B)})$ where $t_{MTAF}^{(b)} = \min_{1 \le k \le K} p_{s_k}^{(b)}$. \item The p-values of MTAF test statistics are approximated by \begin{equation*} p_{MTAF}^{(b)} = \frac{1}{B+1} \sum_{j=0}^B \mathbbm{1}{\{ t_{MTAF}^{(j)} \leq t_{MTAF}^{(b)} \}}, \label{eq:approx_pval} \end{equation*} where $p_{MTAF}^{(b)}$ is the empirical p-value of the MTAF method for the permuted data for $1 \leq b \leq B$ and $p_{MTAF}^{(0)}$ is the empirical p-value for the observed data. \end{enumerate} To simplify the following discussion of the variation of MTAF method, we define the steps above as an AF operator $AF\{\cdot\}$ mapping $\mathbbm{P}$ to $\bm{p} = (p_{MTAF}^{(0)},p_{MTAF}^{(1)},\dots,p_{MTAF}^{(B)})$. \subsection{Combination of One Sided P-values} In practice, traits of a complex disease tend to be positively correlated intrinsically. Or, according to the prior knowledge, we can manually change the direction of effects to make them in the same direction. In the situation that effects are in the same direction, combining one-sided p-values aggregates evidence for the effects which tend to have the same signal and enjoys higher statistical power than combining two-sided p-values. Therefore, we recommend always combine one-sided p-values when it is appropriate. We separately combine the lower-tail p-values and the upper-tail p-values, and then unify these two results using another round of MTAF permutation. Specifically, we get $\bm{p}_{lower} = AF\{\mathbbm{P}_{lower}\}$ and $\bm{p}_{upper} = AF\{\mathbbm{P}_{upper}\}$ and then the empirical p-value of the observed data is the first element of $\bm{p}_{combo} = AF\{[\bm{p}_{lower} \ \bm{p}_{upper}] \}$. \subsection{PCA of continuous traits} Alternatively, a SNP may not have strong associations with observed traits but hidden components, which can be difficult to detect those associations. PCA is widely used to reduce dimensions and it generates orthogonal linear combinations of variables maximizing the variability. We introduce PCA into the MTAF method with the purpose of uncovering the hidden components. In the MTAF method, PCA generates $K$ independent principal components and we detect the associations between the SNP and the principal components. Specifically, for continuous traits, we first regress $\bm{Y_k}$ on the covariates $\bm{Z}$ and denote the residuals $\bm{e_{k}}$ for $1 \leq k \leq K$. PCA conducted on $\bm{e_{1}},\ldots,\bm{e_{K}}$ leads to $K$ principal components which substitute for $\bm{y_{1}},\ldots,\bm{y_{K}}$. In the simulation study, the power of the MTAF method increases dramatically given correlated traits after applying PCA. Unlike its common use in practice that selects only several top principal components, it claims that using all principal components can have greater power \citep{aschard2014maximizing}. Therefore, the MTAF method keeps all principal components and it proves to be powerful. The MTAF method itself is powerful when signals are sparse, but usually the number of traits truly associated with the SNP and underlying correlation structure are unknown. Hence, when analyze continuous traits, initially we apply the original MTAF method and the MTAF method with PCA respectively, then combine the results from the two to get the final p-value. Specifically, we have $\bm{p}_{original}=AF(\mathbbm{P}_{original})$ and $\bm{p}_{pca}=AF(\mathbbm{P}_{pca})$. Then combine two vectors $\bm{p}_{original}$ and $\bm{p}_{pca}$ into a matrix $\mathbbm{P}_{continuous}$. At last, we have $\bm{p}_{continuous}=AF(\mathbbm{P}_{continuous})$ and the p-value is the first element of $\bm{p}_{continuous}$. To process a mixture of binary traits and continuous traits, we first apply the MTAF method to binary traits to get $\bm{p}_{binary}$ and then get $\bm{p}_{continuous}$ by the procedure above. Then we combine two p-value vectors to get $\mathbbm{P}_{mix} = [\bm{p}_{binary} \ \bm{p}_{continuous}]$ and the empirical p-value is the first element of $\bm{p}_{mix}=AF(\mathbbm{P}_{mix})$. In the MTAF method, PCA is used to handle continuous traits rather than binary traits. Although some literature refers to generalized PCA \citep{landgraf2019generalized}, our method only applies PCA to continuous traits at this moment. \subsection{Simulation Setup} To evaluate the performance of the MTAF method, we conduct a simulation study. In each dataset, we simulate $1000$ subjects based on various parameters such as the number and types of traits, as well as the proportion of traits associated with the genotype and the strength of the association. We consider $10$, $50$, and $100$ traits and we simulate three scenarios: continuous traits only, binary traits only, and mixture of the two. We assume a compound symmetry (CS) structure underlying traits with either weak correlation ($\rho=0.3$) or strong correlation ($\rho=0.6$). For the proportion of associated traits, we define the sparse scenarios as when $2\%$ of the traits are truly associated with the SNP, and the dense scenarios as when $20\%$ are associated. However when there are only $10$ traits, we set the number of associated traits being 1 and 4 for the sparse and dense scenarios respectively. The detailed simulation steps are listed below. First, we simulate the genotypes of the SNP. Since we focus on the association between single common SNPs and multiple traits, we only simulate one SNP genotype $x_i \in \{0,1,2\}$ for each subject $i$, such that $x_i \sim \textrm{Bin} (2, 0.3)$, where $0.3$ is the minor allele frequency (MAF) of the simulated SNP. Next, the traits for each subject $\bm{Y_i}=(Y_{i1},\ldots,Y_{iK})'$ are simulated via a linear model: \begin{equation} Y_i = x_i\bm{\beta} + \bm{\epsilon}_i, \label{eq:sim_1} \end{equation} where $\bm{\beta} = (\beta_1,\ldots,\beta_K )$ are the coefficients. The non-zero $\beta_k$'s are drawn from independent uniform distributions and we select the parameters of the uniform distributions to make the differences among methods obvious. $\bm{\epsilon}_i$'s are independently drawn from a multivariate Gaussian distribution $N(\mathbf{0},\bm{\Sigma})$. To simulate correlated traits, $\bm{\Sigma}$ is simulated such that the variances are sampled independently from an inverse gamma distributions $\textrm{Inv-Gamma}(4, 4)$ and the corresponding correlation matrix is CS with correlation $\rho$. In addition, we consider simulation scenarios with two binary covariates $Z_{i1}$ and $Z_{i2}$ to investigate the performance of the MTAF method in the presence of confounders, such as gender and race in the real datasets. These covariates are simulated by dichotomizing underlying covariates that are linearly associated with the genotype. Specifically, $Z_{i1}$ is simulated by dichotomizing $x_i \eta_1 + \omega_{i1}$, and $Z_{i2}$ are simulated by dichotomizing $x_i \eta_2 + \omega_{i2}$, where $\eta_1$ and $\eta_2$ are randomly drawn from uniform distributions $U(0.5,1)$, and $\omega_{i1}$ and $\omega_{i2}$ follow $\mathcal{N}(0,1)$. Then, we label the values greater than medians ``1", otherwise ``0". $\bm{Y_i}$ is simulated based on a linear model conditional on both the genotype and the covariates: \begin{equation} \bm{Y_i} = x_i \bm{\beta} + \bm{Z_i} \bm{\Gamma} + \bm{\epsilon}_i, \label{eq:sim_2} \end{equation} where $\bm{Z_i} = (Z_{i1},Z_{i2})$ and $\bm{\Gamma}_{K \times 2}$ has coefficients drawn from iid uniform distribution $U(0.5,1)$. To simulate binary traits, we first simulate the log-odds of $Y_{ik}=1$ by replacing the corresponding $Y_{ik}$ with $\textrm{logit}(E(Y_{ik}))$ in \ref{eq:sim_1} and \ref{eq:sim_2} and then we draw the binary traits based on the simulated odds. To evaluate the performance of the MTAF method, competitor methods including MSKAT, aSPU, TATES, MANOVA, MultiPhen, and minP are also applied on the simulated datasets for comparison. \subsection*{Data availability} The authors state that all data necessary for confirming the conclusions are represented fully within the article. The SAGE data was downloaded from the dbGAP using accession number phs000092.v1.p1. The R software package for the MTAF method and our simulation code are available at \url{https://github.com/songbiostat/MTAF}. \section{Results} \label{sec:results} \subsection{Simulation Results} \subsubsection{Type I Error Rate} First, to assess whether the MTAF method and other methods can appropriately control type I error at the nominal level, we perform simulations under the null hypothesis where $\beta_1=\dots=\beta_K=0$. The empirical p-values were calculated based on $1,000$ permutations and the type I error rate is evaluated at the $0.05$ nominal level. In addition to aSPU with default independent structure, we evaluated aSPU equipped with exchangeable correlation structure (aSPU-ex). Table \ref{tab:typeI_cont} shows that, when all traits were continuous, the empirical Type I error of most methods were well controlled allowing for different number of traits and strength of correlation. We found that MultiPhen had inflated Type I error, especially after adding covariates into the models. Thus, we decided not to include MultiPhen in the corresponding simulation studies. The similar phenomenon was reported by Konigorski et al.\citep{konigorski2020powerful} that MultiPhen led to inflated or highly inflated type I errors and they did not include the method in the power study. Table \ref{tab:typeI_bin} and \ref{tab:typeI_mix} show that type I error were well controlled for the compared methods when all traits are binary, or when the traits are half binary and half continuous. Please be noted that only methods that can be applied on binary or mixed trait scenarios are included in tables \ref{tab:typeI_bin} and \ref{tab:typeI_mix}. \begin{table}[htbp] \caption{\bf Type I error: continuous traits} \centering \scalebox{0.8}{ \begin{tabular}{c c c c cccccccc} \hline \# Covariates & Correlation & \# Traits & MTAF & MSKAT & aSPU &aSPU-ex &MultiPhen & TATES & MANOVA & minP \\ [0.5ex] \hline 0 & 0.3 & 10 &0.042 &0.048 &0.041 &0.049 &0.049 &0.045 &0.050 &0.049 \\[-0.5ex] & & 50 &0.044 &0.038 &0.047 &0.039 &0.038 &0.042 &0.045 &0.049 \\[-0.5ex] & & 100 &0.049 &0.040 &0.054 &0.051 &0.041 &0.050 &0.049 &0.052 \\[0.5ex] & 0.6 & 10 &0.045 &0.048 &0.041 &0.049 &0.049 &0.035 &0.050 &0.039 \\[-0.5ex] & & 50 &0.041 &0.038 &0.050 &0.039 &0.038 &0.026 &0.045 &0.043 \\[-0.5ex] & & 100 &0.051 &0.040 &0.061 &0.047 &0.041 &0.044 &0.049 &0.054 \\[1ex] 2 & 0.3 & 10 &0.051 &0.049 &0.039 &0.042 &0.066 &0.046 &- &0.046 \\[-0.5ex] & & 50 &0.049 &0.064 &0.040 &0.041 &0.097 &0.045 &- &0.046 \\[-0.5ex] & & 100 &0.047 &0.042 &0.056 &0.058 &0.146 &0.043 &- &0.046 \\[0.5ex] & 0.6 & 10 &0.048 &0.048 &0.043 &0.050 &0.059 &0.044 &- &0.045 \\[-0.5ex] & & 50 &0.039 &0.064 &0.034 &0.038 &0.097 &0.027 &- &0.038 \\[-0.5ex] & & 100 &0.043 &0.040 &0.033 &0.042 &0.138 &0.029 &- &0.049 \\[0ex] \hline \hline \end{tabular} } \label{tab:typeI_cont} \end{table} \begin{table}[htbp] \caption{\bf Type I error: binary traits} \centering \scalebox{1}{ \begin{tabular}{c c c c cccccc} \hline \# Covariates & Correlation & \# Traits & MTAF &aSPU &aSPU-ex & MultiPhen &TATES & minP \\ [0.5ex] \hline 0 & 0.3 & 10 &0.050 &0.055 &0.056 &0.066 &0.054 &0.055 \\[-0.5ex] & & 50 &0.050 &0.051 &0.040 &0.072 &0.055 &0.052 \\[0.5ex] & 0.6 & 10 &0.044 &0.048 &0.055 &0.059 &0.048 &0.046 \\[-0.5ex] & & 50 &0.051 &0.046 &0.049 &0.077 &0.055 &0.054 \\[1ex] 2 & 0.3 & 10 &0.039 &0.042 &0.043 &0.526 &0.047 &0.049 \\[-0.5ex] & & 50 &0.035 &0.034 &0.037 &0.710 &0.044 &0.043 \\[0.5ex] & 0.6 & 10 &0.043 &0.042 &0.039 &0.429 &0.044 &0.040 \\[-0.5ex] & & 50 &0.038 &0.038 &0.044 &0.606 &0.049 &0.052 \\[0ex] \hline \end{tabular} } \label{tab:typeI_bin} \end{table} \begin{table}[htbp] \caption{\bf Type I error: mixed traits with covariates} \centering \scalebox{1}{ \begin{tabular}{c c c ccc} \hline Correlation & \# Traits & MTAF &MultiPhen & TATES & minP \\ [0.5ex] \hline 0.3 & 10 &0.054 &0.886 &0.059 &0.058 \\[-0.5ex] & 50 &0.043 &0.982 &0.056 &0.055 \\[0.5ex] 0.6 & 10 &0.049 &0.878 &0.053 &0.051 \\[-0.5ex] & 50 &0.040 &0.996 &0.041 &0.045\\[0ex] \hline \end{tabular} } \label{tab:typeI_mix} \end{table} \subsubsection{Statistical Power} The power of these compared methods were evaluated under different scenarios at significance level of $0.05$. The effect sizes for the associated traits were randomly drawn from uniform distributions. We include the original MTAF method ($\textrm{MTAF}_{\textrm{original}}$) and its PCA expansion ($\textrm{MTAF}_{\textrm{PCA}}$). The results show that the statistical power under dense scenarios was greatly improved by introducing PCA. Table \ref{tab:power_cont_noz} summarizes the power of the compared methods for continuous traits without covariates. We observe that when signals were sparse, the MTAF method was the most powerful method or performed similar to the most powerful method. On the other hand, when the signals were dense, MSKAT, MANOVA, and MultiPhen were the powerful methods. Although the MTAF method had a slightly lower power, the performance of the MTAF method was close to these methods. Table \ref{tab:power_cont_z} shows the results for continuous traits with two covariates. It shows that when confounders were included, only the MTAF method and MSKAT managed to preserve their power in both sparse and dense scenarios, while the performance of other methods deteriorated for the dense signal scenarios, especially when the number of traits got large. Table \ref{tab:power_bin_noz} shows the results for binary traits without covariates. Under this scenario, aSPU and aSPU-ex outperformed other methods. The MTAF method was slightly less powerful than aSPU methods, while TATES and minP performed well with sparse signal, but significantly underperforms with dense signals. In Table \ref{tab:power_bin_z}, we find that with two covariates, performance difference between the MTAF method and the aSPU methods diminished, and their powers were close in most simulations settings. Table \ref{tab:power_mix} shows the results for mixed traits with two covariates. It should be noted that only four methods allow for mixture of binary and continuous traits, including MultiPhen, the MTAF method, TATES, and minP. Whereas we did not include MultiPhen in our comparison because it fails to control type I error as shown previously. According to the results, the MTAF method outperformed TATES and minP regardless of the number of traits, the strength of correlation, or the proportional of signals. In summary, MTAF was robustly one of the most powerful methods in all the simulation settings with various number of traits, strength of correlation, and proportion of signals, for both continuous traits and binary traits (or their mixture), with or without confounding covariates. \begin{table*}[!htbp] \caption{\bf Power: continuous traits without covariates} \centering \scalebox{0.6}{ \begin{tabular}{c c c c cccccccccc} \hline Sparsity & Correlation & \# Traits & Effect Size &$\textrm{MTAF}_{\textrm{PCA}}$ &$\textrm{MTAF}_{\textrm{original}}$ &MTAF &MSKAT &aSPU &aSPU-ex &MultiPhen &TATES &MANOVA &minP \\ [0.5ex] \hline sparse & 0.3 & 10 &U(0.15,0.25) &0.762 &0.791 &0.793 &0.796 &0.563 &0.702 &0.796 &0.785 &0.798 &0.788 \\[-0.5ex] & & 50 & U(0.2,0.4) &0.797 &0.922 &0.916 &0.825 &0.688 &0.807 &0.827 &0.904 &0.836 &0.906 \\[-0.5ex] & & 100 & U(0.15,0.3) &0.770 &0.924 &0.919 &0.843 &0.400 &0.665 &0.845 &0.895 &0.852 &0.894 \\[0.5ex] & 0.6 & 10 &U(0.15,0.25) &0.907 &0.858 &0.905 &0.918 &0.590 &0.859 &0.918 &0.799 &0.918 &0.907 \\[-0.5ex] & & 50 & U(0.2,0.4) &0.916 &0.957 &0.949 &0.944 &0.730 &0.926 &0.944 &0.908 &0.950 &0.924 \\[-0.5ex] & & 100 & U(0.15,0.3) &0.935 &0.948 &0.968 &0.960 &0.413 &0.833 &0.960 &0.886 &0.966 &0.914 \\[1ex] dense & 0.3 & 10 &U(0.05,0.15) &0.769 &0.690 &0.765 &0.784 &0.390 &0.507 &0.784 &0.651 &0.786 &0.639 \\[-0.5ex] & & 50 & U(0.05,0.12) &0.808 &0.629 &0.812 &0.865 &0.134 &0.422 &0.866 &0.534 &0.873 &0.551\\[-0.5ex] & & 100 & U(0.02,0.1) &0.615 &0.418 &0.637 &0.716 &0.082 &0.266 &0.716 &0.334 &0.742 &0.343 \\[0.5ex] & 0.6 & 10 &U(0.05,0.15) &0.92 &0.729 &0.907 &0.933 &0.301 &0.701 &0.933 &0.627 &0.933 &0.641 \\[-0.5ex] & & 50 & U(0.05,0.12) &0.969 &0.654 &0.964 &0.987 &0.119 &0.640 &0.987 &0.457 &0.988 &0.526 \\[-0.5ex] & & 100 & U(0.02,0.1) &0.929 &0.437 &0.916 &0.970 &0.074 &0.338 &0.970 &0.273 &0.974 &0.346 \\[0ex] \hline \end{tabular} } \label{tab:power_cont_noz} \end{table*} \begin{table}[htbp] \caption{\bf Power: continuous traits with covariates} \centering \scalebox{0.7}{ \begin{tabular}{c c c c cccccccc} \hline Sparsity & Correlation & \# Traits & Effect Size &$\textrm{MTAF}_{\textrm{PCA}}$ &$\textrm{MTAF}_{\textrm{original}}$ &MTAF &MSKAT &aSPU &aSPU-ex &TATES &minP \\ [0.5ex] \hline sparse & 0.3 & 10 &U(0.15,0.3) &0.763 &0.787 &0.803 &0.795 &0.602 &0.715 &0.773 &0.779 \\[-0.5ex] & & 50 & U(0.2,0.4) &0.684 &0.889 &0.871 &0.757 &0.578 &0.722 &0.871 &0.876 \\[-0.5ex] & & 100 & U(0.15,0.3) &0.646 &0.872 &0.862 &0.754 &0.273 &0.543 &0.835 &0.840 \\[0.5ex] & 0.6 & 10 &U(0.15,0.3) &0.908 &0.862 &0.900 &0.920 &0.620 &0.865 &0.778 &0.794 \\[-0.5ex] & & 50 & U(0.2,0.4) &0.877 &0.935 &0.939 &0.917 &0.619 &0.878 &0.880 &0.891 \\[-0.5ex] & & 100 & U(0.15,0.3) &0.889 &0.922 &0.948 &0.934 &0.307 &0.739 &0.828 &0.859 \\[1ex] dense & 0.3 & 10 &U(0.05,0.2) &0.833 &0.792 &0.842 &0.875 &0.506 &0.649 &0.759 &0.748 \\[-0.5ex] & & 50 &U(0.05,0.13) &0.685 &0.517 &0.695 &0.775 &0.123 &0.387 &0.468 &0.470\\[-0.5ex] & & 100 &U(0.03,0.12) &0.460 &0.301 &0.478 &0.560 &0.064 &0.211 &0.258 &0.268 \\[0.5ex] & 0.6 & 10 &U(0.05,0.2) &0.957 &0.833 &0.947 &0.963 &0.422 &0.821 &0.732 &0.737 \\[-0.5ex] & & 50 &U(0.05,0.13) &0.934 &0.544 &0.928 &0.963 &0.105 &0.567 &0.400 &0.457\\[-0.5ex] & & 100 &U(0.03,0.12) &0.779 &0.292 &0.756 &0.862 &0.057 &0.247 &0.192 &0.269 \\[0ex] \hline \end{tabular} } \label{tab:power_cont_z} \end{table} \begin{table}[htbp] \caption{\bf Power: binary traits without covariates} \centering \scalebox{0.7}{ \begin{tabular}{c c c c ccccc} \hline Sparsity & Correlation & \# Traits & Effect Size &MTAF &aSPU &aSPU-ex &TATES &minP \\ [0.5ex] \hline sparse & 0.3 & 10 &U(0.4,0.6) &0.747 &0.837 &0.839 &0.805 &0.805 \\[-0.5ex] & & 50 &U(0.6,0.8) &0.891 &0.957 &0.959 &0.930 &0.934 \\[0.5ex] & 0.6 & 10 &U(0.4,0.6) &0.773 &0.84 &0.859 &0.804 &0.801\\[-0.5ex] & & 50 &U(0.6,0.8) &0.912 &0.960 &0.974 &0.934 &0.931 \\[1ex] dense & 0.3 & 10 &U(0.2,0.3) &0.712 &0.738 &0.723 &0.547 &0.554 \\[-0.5ex] & & 50 &U(0.15,0.3) &0.667 &0.734 &0.749 &0.473 &0.46 \\[0.5ex] & 0.6 & 10 &U(0.2,0.3) &0.684 &0.701 &0.691 &0.569 &0.573 \\[-0.5ex] & & 50 &U(0.15,0.3) &0.580 &0.619 &0.754 &0.459 &0.454 \\[0ex] \hline \end{tabular} } \label{tab:power_bin_noz} \end{table} \begin{table}[htbp] \caption{\bf Power: binary traits with covariates} \centering \scalebox{0.7}{ \begin{tabular}{c c c c ccccc} \hline Sparsity & Correlation & \# Traits & Effect Size &MTAF &aSPU &aSPU-ex &TATES &minP \\ [0.5ex] \hline sparse & 0.3 & 10 &U(0.4,0.6) &0.702 &0.704 &0.714 &0.745 &0.739 \\[-0.5ex] & & 50 &U(0.5,0.7) &0.745 &0.725 &0.753 &0.800 &0.805 \\[0.5ex] & 0.6 & 10 &U(0.4,0.6) &0.718 &0.712 &0.747 &0.737 &0.740 \\[-0.5ex] & & 50 &U(0.5,0.7) &0.766 &0.738 &0.792 &0.791 &0.787 \\[1ex] dense & 0.3 & 10 &U(0.2,0.3) &0.610 &0.589 &0.570 &0.509 &0.491 \\[-0.5ex] & & 50 &U(0.2,0.35) &0.782 &0.783 &0.797 &0.637 &0.608 \\[0.5ex] & 0.6 & 10 &U(0.2,0.3) &0.548 &0.534 &0.525 &0.490 &0.467 \\[-0.5ex] & & 50 &U(0.2,0.35) &0.725 &0.683 &0.806 &0.608 &0.589 \\[0ex] \hline \end{tabular} } \label{tab:power_bin_z} \end{table} \begin{table}[htbp] \caption{\bf Power: mixed traits with covariates and dense signals} \centering \scalebox{0.8}{ \begin{tabular}{c c c c ccc} \hline Correlation & \# Traits & Effect Size &MTAF &TATES &minP \\ [0.5ex] \hline 0.3 & 10 &U(0.05,0.3) &0.844 &0.805 &0.804 \\[-0.5ex] & 50 &U(0.05,0.25) &0.929 &0.846 &0.852 \\[0.5ex] 0.6 & 10 &U(0.05,0.3) &0.897 &0.798 &0.795 \\[-0.5ex] & 50 &U(0.05,0.25) &0.986 &0.827 &0.835 \\[0ex] \hline \end{tabular} } \label{tab:power_mix} \end{table} \subsection{The Study of Addiction: Genetics and Environment (SAGE)} To further demonstrate the usage of the proposed method in real studies, we applied MTAF to The Study of Addiction: Genetics and Environment (SAGE) \citep{bierut2010genome} data from the database of Genotypes and Phenotypes (dbGaP) \citep{mailman2007ncbi}, \url{http://www.ncbi.nlm.nih.gov/projects/gap/cgi-bin/study.cgi?study_id=phs000092.v1.p1}. SAGE is a case-control GWAS of addiction with unrelated individuals where cases are defined as individuals with Diagnostic and Statistical Manual of Mental Disorders 4th Edition (DSM-IV) alcohol dependence (lifetime) and potentially other illicit drug dependence. The individuals were selected from three large studies including the Collaborative Study on the Genetics of Alcoholism (COGA), the Family Study of Cocaine Dependence (FSCD), and the Collaborative Genetic Study of Nicotine Dependence (COGEND). From dbGaP, We downloaded the data of $3,847$ individuals who consented to provide their data for health research. Quality control was performed using PLINK 1.9 \citep{purcell2007plink}. We filtered data based on the genotyping rate (0.01), missingness (0.01), minor allele frequency (0.01), and Hardy-Weinberg equilibrium (p-value $\le$ 0.01). After the filtering, we ended up with $3,557$ individuals and $560,218$ SNPs. In order to detect SNPs associated with addiction, we selected 18 traits (summarized in Table \ref{tab:sage_variables}) that account for the addiction to alcohol, nicotine, marijuana, cocaine, opiates, and any other drug. Among these traits, 12 are binary and 6 are continuous. In addition, gender and race (black or white) are included in our analysis as confounding covariates. \begin{table}[htbp] \caption{\bf SAGE data variables summary} \centering \scalebox{0.75}{ \begin{tabular}{c c c} \hline & variable name & description \\ [0.5ex] \hline & nic\_sx\_tot & number of nicotine symptoms endorsed \\ [0.5ex] & nic\_sx1 & tolerance to nicotine \\ [0.5ex] & nic\_sx2 & withdrawal from nicotine \\ [0.5ex] & cig\_daily & Has participant ever smoked cigarettes daily for a month or more? \\ [0.5ex] & mj\_sx\_tot & number of marijuana dependence symptoms endorsed \\ [0.5ex] & mj\_sx1 & tolerance to marijuana \\ [0.5ex] & mj\_sx2 & withdrawal to marijuana \\ [0.5ex] & coc\_sx\_tot & number of cocaine dependence symptoms endorsed \\ [0.5ex] & coc\_sx1 & tolerance to cocaine \\ [0.5ex] & coc\_sx2 & withdrawal to cocaine \\ [0.5ex] & op\_sx\_tot & number of opiates dependence symptoms endorsed \\ [0.5ex] & op\_sx1 & tolerance to opiates \\ [0.5ex] & op\_sx2 & withdrawal to opiates \\ [0.5ex] & alc\_sx\_tot & number of alcohol dependence symptoms endorsed \\ [0.5ex] & alc\_sx1 & tolerance to opiates \\ [0.5ex] & alc\_sx2 & withdrawal to opiates \\ [0.5ex] & max\_drinks & largest number of alcoholic drinks consumed in 24 hours \\ [0.5ex] & ever\_oth & Has participant ever used drugs other than marijuana, cocaine or opiates? \\ [0.5ex] \hline \end{tabular} } \label{tab:sage_variables} \end{table} \begin{table}[htbp] \caption{\bf Correlation of continuous traits in SAGE data} \centering \scalebox{0.75}{ \begin{tabular}{c c c c c c c} \hline & nicotine & marijuana & cocaine & alcohol & opiate & max drinks \\ [0.5ex] \hline nicotine &1 &0.390 &0.392 &0.534 &0.218 &0.345 \\ [0.5ex] marijuana &0.390 &1 &0.534 &0.472 &0.331 &0.287 \\ [0.5ex] cocaine &0.392 &0.534 &1 &0.519 &0.377 &0.346 \\ [0.5ex] alcohol &0.537 &0.472 &0.519 &1 &0.298 &0.574 \\ [0.5ex] opiate &0.218 &0.331 &0.377 &0.298 &1 &0.175 \\ [0.5ex] max drinks &0.350 &0.287 &0.346 &0.574 &0.175 &1 \\ [0.5ex] \hline \end{tabular} } \label{tab:sage_corr} \end{table} We inspected the Pearson's correlation among six continuous traits and Table \ref{tab:sage_corr} shows that all six traits are positively correlated. Then we applied the MTAF method to detect the associations between the SNPs and the 18 traits. To get accurate p-values at extremely small significance level (usually lower than $10^{-6}$) given limited computational resource, we performed the tests by adaptively increasing the number of permutations. We first set the number of permutation to be $B$ and filtered out insignificant SNPs with p-values greater than $5/B$ and updated the number of permutation to $10 \times B$. We started with $B = 100$ and repeat the above process until $B=10^7$. By doing this, we managed to avoided permuting $10^7$ times for most of the SNPs, and saved computation resource only for the most significant SNPs. Figure \ref{fig:qq} shows the QQ-plot of the $-\log_{10}(\textrm{p-values})$ of all the SNPs based on the MTAF method. As expected, the majority of the SNPs have p-values that are uniformly distributed, while only a small proportion of the SNPs has strong association with the phenotypes. Please be noted that the inflections observed in the QQ-plot are completely normal due to the adaptive permutation procedure. Figure \ref{fig:man} shows the p-values for all SNPs across 22 chromosomes in a Manhattan plot. \begin{figure}[htbp!] \centering \includegraphics[width=\linewidth]{qq2.pdf} \caption{QQ-plot of p-values of the MTAF method testing the association between SNPs and multiple traits of substance dependence. }% \label{fig:qq} \end{figure} At the significance level $5 \times 10^{-6}$, we identified 11 significant SNPs belonging to six genes as shown in Table \ref{tab:sage_SNP}. Most of these genes are related to the biological functions of nerve and brain, which is plausible considering the fact that addictions are considered to be related to mental health. Among these genes, EVI5 is a risk gene of multiple sclerosis, a disease which causes damage to the nervous system \citep{hoppenbrouwers2008evi5}. Gouveia et al. \citep{gouveia2019genetics} finds that ZNF385D is associated with cognitive function, and it is also reported to be associated with language impairment in previous literature. TPK1 produces thiamine pyrophosphate and its mutation can cause neurological disorder \citep{banka2014expanding}. According to GWAS catlog \citep{buniello2019nhgri}, LINC02008, MIR4495 and CNTN1 are all linked to Alzheimer's disease, and CNTN1 is reported to be associated with Parkinson's disease and schizophrenia. \begin{table}[htbp] \caption{\bf significant SNPs at $5 \times 10^{-6}$ level } \centering \scalebox{0.8}{ \begin{tabular}{c c c c c} \hline rsid & chromosone & position & p-value & gene \\ [0.5ex] \hline rs1556562 &1 & 92568466 &$4.0 \times 10^{-6}$ &EVI5 \\ [0.5ex] rs1408916 &1 & 92527070 &$3.1 \times 10^{-6}$ &EVI5 \\ [0.5ex] rs4847377 &1 & 92557593 &$2.8 \times 10^{-6}$ &EVI5 \\ [0.5ex] rs4970712 &1 & 92527990 &$3.8 \times 10^{-6}$ & EVI5 \\ [0.5ex] rs9310661 &3 & 21855648 &$1.3 \times 10^{-6}$ & ZNF385D \\ [0.5ex] rs7614064 &3 & 82239346 &$1.4 \times 10^{-6}$ &LINC02008 \\ [0.5ex] rs7645576 &3 & 82274160 &$3.0 \times 10^{-6}$ &LINC02008 \\ [0.5ex] rs9852219 &3 & 82327624 &$5.0 \times 10^{-6}$ &LINC02008 \\ [0.5ex] rs10224675 &7 & 144595669 &$3.4 \times 10^{-6}$ &TPK1 \\ [0.5ex] rs11178982 &12 &40907530 &$2.0 \times 10^{-6}$ &CNTN1 \\ [0.5ex] rs2020139 &12 &97953656 &$3.1 \times 10^{-6}$ &MIR4495 \\ [0.5ex] \hline \end{tabular} } \label{tab:sage_SNP} \end{table} \begin{figure}[htbp!] \centering \includegraphics[width=\linewidth]{man2.pdf} \caption{Manhattan plot of the MTAF method testing the association between SNPs and multiple traits of substance dependence at a significance level of $5 \times 10^{-6}$ }% \label{fig:man} \end{figure} \section{Discussion} \label{sec:discussion} Although single-trait analysis methods have been widely used in multiple-trait studies, these methods may be insufficient when traits are truly correlated with each other. Hence, the multiple-trait association tests can increase statistical power by incorporating the information among traits. In this paper, we propose the MTAF method for multiple traits, by adaptively combining p-values from the single-trait analyses. The MTAF method is very versatile for the multiple-trait association testing. First, because the MTAF method only requires the p-values as inputs, it can process both continuous traits and binary traits simultaneous whenever p-values are provided. Second, we apply PCA on continuous traits to uncover hidden components underlying traits, which greatly improves the performance of MTAF when signals are weak and dense. Third, the MTAF method combines the one sided p-values instead of two sided p-values, which increases power given the effects of traits are in the same direction. When some of the traits are in the opposite direction of other traits, we can flip these traits such that all or most of the traits are positively correlated. At last, we paid special attention to the permutation test with covariates. By permuting the residuals of genotypes regressed on the covariates, we managed to control type I error while adjusting for confounders. Relying on the permutation procedure to get the empirical p-values can be time-consuming when the validity of tiny p-values is required. Since in GWASs most SNPs have no significant effect on the traits, permuting the same number of times on each SNP is unnecessary and can be a waste of computing time and resources. A more efficient way is to permute the data iteratively on each SNP with the expectation that insignificant SNPs will be excluded in less permutation time. As a result, most SNPs get removed after the first few rounds and only significant SNPs require a large number of permutation time. We show the reduction in time complexity by the following example. Starting with $B=100$, the chance that a SNP gets removed in the first round is $0.05$. If the SNP remains, we would start the second round $B=1000$ and the chance that the SNP gets removed in the second round would be $0.045$ which is the difference between the chance of remaining in the first round $0.05$ and the chance of advancing to the third round $0.005$. Following the procedure, if we stop at $B=10^7$, the expected permutation times for a SNP would be $0.95 \cdot 100 + 0.045 \cdot 1000 + \ldots + 4.5 \cdot 10^{-6} \cdot 10^7 \approx 45 \cdot \log_{10}(10^7)$, which is logarithmic time $\log_{10}(B)$. On the contrary, if we fix the permutation times at $10^7$, the expected permutation times would be linear time $B$. Therefore, we reduce the time complexity from linear time to logarithmic time. A SNP may not always influence the traits directly. Instead, it may indirectly affect correlated traits through an unobserved component, in which case, uncovering the hidden component can enhance the statistical power given correlated traits. In the MTAF method, we use PCA to uncover this potentially hidden component. By detecting the associations between the SNP and hidden components, we may increase the statistical power. This idea was supported by our simulation study in which PCA largely improved the statistical power under dense scenarios. Thus, depending on the correlation structure, PCA may increase the power of testing when traits are correlated. Despite the advantages of the MTAF method, several limitations can be addressed in the future work. First, the MTAF method can only analyze the single variant at this moment, the set-based analysis is common in GWASs though. \citet{cai2020adaptive} proposed a set-based AF method and the MTAF method might be extended to the set-based analysis or pathway analysis in the future. Second, the p-values are adaptively combined in the MTAF method and we do not aim at selecting the most related traits for the identified SNPs. Thus, in our future work, we can develop a method to provide a list of traits that are most related for each identified SNP. At last, because we need to permute the residuals of genotypes to control for type I error while adjusting for confounders or covariates, the MTAF method requires the individual level genotype data to perform the test. However, the individual level data are not alway available or often require special permissions since they are considered as identifiable data. In the future work, we would explore whether the MTAF method can be extended to use the GWAS summary statistics without requiring the individual level data. The R software package for the MTAF method and our simulation code are available at \url{https://github.com/songbiostat/MTAF}. \section*{Acknowledgments} Funding support for the Study of Addiction: Genetics and Environment (SAGE) was provided through the NIH Genes, Environment and Health Initiative [GEI] (U01 HG004422). SAGE is one of the genome-wide association studies funded as part of the Gene Environment Association Studies (GENEVA) under GEI. Assistance with phenotype harmonization and genotype cleaning, as well as with general study coordination, was provided by the GENEVA Coordinating Center (U01 HG004446). Assistance with data cleaning was provided by the National Center for Biotechnology Information. Support for collection of datasets and samples was provided by the Collaborative Study on the Genetics of Alcoholism (COGA; U10 AA008401), the Collaborative Genetic Study of Nicotine Dependence (COGEND; P01 CA089392), and the Family Study of Cocaine Dependence (FSCD; R01 DA013423). Funding support for genotyping, which was performed at the Johns Hopkins University Center for Inherited Disease Research, was provided by the NIH GEI (U01HG004438), the National Institute on Alcohol Abuse and Alcoholism, the National Institute on Drug Abuse, and the NIH contract "High throughput genotyping for studying the genetic contributions to human disease" (HHSN268200782096C). The datasets used for the analyses described in this manuscript were obtained from dbGaP at \url{http://www.ncbi.nlm.nih.gov/projects/gap/cgi-bin/study.cgi?study_id=phs000092.v1.p1} through dbGaP accession number phs000092.v1.p. \bibliographystyle{plainnat}
{'timestamp': '2020-09-22T02:00:49', 'yymm': '2009', 'arxiv_id': '2009.09002', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09002'}
arxiv
\section{Introduction} Deep learning has shown outstanding performance in a wide range of computer vision tasks in the past years, especially image tasks. Meanwhile, in many practical applications, such as autonomous vehicles (Figure \ref{fig:1} shows a point cloud collected by an autonomous vehicle), we need more information than only images to obtain a better sense of the environment. 3D data from lidar or RGB-D cameras are considered to be a good supplement here. These devices generate 3D geometric data in the form of point clouds. With the growing demand from industry, utilization of point clouds with deep learning models is becoming a research hotspot recently. \par \begin{figure}[t] \begin{center} \includegraphics[width=1.5in]{pc1.png} \includegraphics[width=1.5in]{pc2.png} \end{center} \caption{Point cloud data collected from outdoor scene, shown from two distinct angles.} \label{fig:1} \end{figure} In constrast to image data, point clouds do not directly contain spatial structure, and deep models on point clouds must therefore solve three main problems: (1) how to find a representation of high information density from a sparse point cloud, (2) how to build a network satisfying necessary restrictions like size-variance and permutation-invariance, (3) how to process large volumes of data with lower time and computing resource consumption. PointNet \cite{qi2017pointnet} is one of the representative early attempts to design a novel deep network for comsumption of unordered 3D point sets by taking advantage of MLP and T-Net. PointNet, together with its improved version PointNet++ \cite{qi2017pointnet++}, inspired a lot of follow-up works. \par Fundamental tasks in images, such as classification, segmentation and object detection also exist in point clouds. Most solutions to these problems benefit from research findings on the image side, while adequate adaptions are inevitable to suit the characteristics of 3D data. In this paper, recent works on point clouds are divided into the following categories: classification, segmentation, detection, matching and registration, augmentation, completion and reconstruction. Detailed descriptions of each category will be provided in the following sections. \par A growing number of datasets are available for different tasks on point clouds. ShapeNet \cite{shapenet2015} and ModelNet \cite{wu20153d} are two early datasets consisting of clean 3D models. These early datasets suffer from the lack of generalization. However, it is necessary to consider disturbance including noise and missing points to develop robust models. With that in mind, datasets such as ScanNet \cite{dai2017scannet} and KITTI \cite{Geiger2013IJRR} are then created from scans of the actual environment. Datasets designed for autonomous vehicle tasks, like nuScenes \cite{caesar2019nuscenes} and Lyft \cite{lyft2019}, are further generalized by involving various environments at different times. Currently, ever more datasets are being proposed in order to meet the increasing demands of distinct niches. \par The structure of this paper is as follows. Section 2 introduces existing 3D datasets and corresponding metrics for different tasks. Section 3 includes a survey of 3D shape classification methods. Section 4 reviews methods for 3D semantic segmentation and instance segmentation. Section 5 presents a survey of methods for 3D object detection and its derivative task. Section 6 introduces recent progress in 3D point cloud matching and registration. Section 7 provides a review of methods to improve data quality. Finally, section 8 concludes the paper. \par \section{Datasets and metrics} Datasets are of great importance in deep learning methods for 3D point cloud data. First, well-designed datasets provide convictive evaluation and comparison among different algorithms. Second, datasets with richer content and metadata help define more complicated tasks and raise new research topics. In this section, we will briefly introduce some most commonly used datasets and evaluation metrics. \begin{table*}[h] \centering \caption{Commonly used 3D point cloud datasets in recent works} \begin{tabular}{|p{2.2cm}|p{2cm}|p{1cm}|p{2.8cm}|p{5.5cm}|p{0.7cm}|} \hline Dataset & Task & Classes & Scale & Feature & Year \\ \hline ShapeNet \cite{shapenet2015} & Classification & 55 & 51300 models & The categories are selected according to WordNet \cite{miller1995wordnet} synset. & 2015\\ \hline ModelNet40 \cite{wu20153d} & Classification & 40 & 12311 models & The models are collected with online search engines by querying for each established object category. & 2015 \\ \hline S3DIS \cite{armeni20163d} & Segmentation & 12 & 215 million points & Points are collected in 5 large-scale indoor scenes from 3 different buildings. & 2016 \\ \hline Semantic3D \cite{hackel2017isprs} & Segmentation & 8 & 4 billion points & Hand-labelled from a range of diverse urban scenes. & 2017 \\ \hline ScanNet \cite{dai2017scannet} & Segmentation & 20 & 2.5 million frames & Collected with a scalable RGB-D capture system with automated surface reconstruction and crowdsourced semantic annotation. & 2017 \\ \hline KITTI \cite{Geiger2013IJRR,Geiger2012CVPR,Fritsch2013ITSC,Menze2015CVPR} & Detection Tracking & 3 & 80256 objects & Captured by a standard station wagon equipped with two cameras, a Velodyne laser scanner and a GPS localization system driving in different outdoor scenes. & 2012\\ \hline nuScenes \cite{caesar2019nuscenes} & Detection Tracking & 23 & 1.4M objects & Captured with full sensor suite (1x LIDAR, 5x RADAR, 6x camera, IMU, GPS); 1000 scenes of 20s each. & 2019\\ \hline Waymo Open Dataset \cite{sun2020scalability} & Detection Tracking & 4 & 12.6M objects with tracking ID & Captured with 1 mid-range lidar, 4 short-range lidars and 5 cameras (front and sides); 1,950 segments of 20s each, collected at 10Hz. & 2019 \\ \hline \end{tabular} \label{table:0} \end{table*} \subsection{Datasets} Table \ref{table:0} shows the most commonly used 3D point cloud datasets for three matured tasks (classification, segmentation and detection), which will be mentioned often in the following sections. We will also introduce each of them with more details. \par \textbf{ShapeNet} ShapeNet \cite{shapenet2015} is a rich-annotated dataset with 51300 3D models in 55 categories. It consists of several subsets. ShapeNetSem, which is one of the subsets, contains 12000 models spread over a broader set of 270 categories. This dataset, together with ModelNet40 \cite{wu20153d}, are relatively clean and small, so they are usually used to evaluate the capacity of backbones before applied to more complicated tasks.\par \textbf{ModelNet40} The ModelNet \cite{wu20153d} project provides three benchmarks: ModelNet10, ModelNet40 and Aligned40. The ModelNet40 benchmark, where ``40" indicates the number of classes, is the most widely used. To find the most common object categories, the statistics obtained from the SUN database \cite{xiao2010sun} are utilized. After establishing the vocabulary, 3D CAD models are collected with online search engines and verified by human workers. \par \textbf{S3DIS} The Stanford Large-Scale 3D Indoor Spaces (S3DIS) dataset is composed of 5 large-scale indoor scenes from three buildings to hold diverse in architectural style and appearance. The point clouds are automatically generated without manual intervention. 12 semantic elements including structural elements (floor, wall, etc.) and common furniture are detected. \par \textbf{Semantic3D} Semantic3D \cite{hackel2017isprs} is the largest 3D point cloud dataset for outdoor scene segmentation so far. It contains over 4 billion points collected from around 110000$m^2$ area with a static lidar. The natural of outdoor scene, such as the unevenly distribution of points and massive occlusions, makes the dataset challenging. \par \textbf{ScanNet} ScanNet \cite{dai2017scannet} is a video dataset consists of 2.5 million frames from more than 1000 scans, annotated with camera poses, surface reconstructions and instance-level semantic segmentation. The dataset provides benchmarks for mutiple 3D scene understanding tasks, such as classification, semantic voxel labeling and CAD model retrieval. \par \textbf{KITTI} The KITTI \cite{Geiger2013IJRR,Geiger2012CVPR,Fritsch2013ITSC,Menze2015CVPR} vision benchmark suite is among the most famous benchmarks with 3D data. It covers benchmarks for 3D object detection, tracking and scene flow estimation. The multi-view data are captured with an autonomous driving platform with two high-resolution color and gray cameras, a Velodyne laser scanner and a GPS localization system. Only three kinds of objects which are important to autonomous driving are labelled: cars, pedestrians and cyclists.\par \textbf{Other datasets} There are some other datasets of high quality but not widely used, such as Oakland \cite{munoz2009contextual}, iQmulus \cite{vallet2015terramobilita} and Paris-Lille-3D \cite{roynard2017parisIJRR}. 3DMatch \cite{zeng20183dcontextnet} pushed the research in 3D matching and registration, which is a less popular direction in the past period. Recently, the rising demand from industry of autonomous driving has spawned several large-scale road-based datasets, represented by nuScenes \cite{caesar2019nuscenes}, Lyft Level 5 \cite{lyft2019} and Waymo Open Dataset \cite{sun2020scalability}. They proposed complicated challenges requiring to leverage multi-view data and related metadata. The development of datasets is helping reduce the gap between research and practical applications. \subsection{Metrics} The comparison between different algorithms requires certain metrics. It is important to design and select appropriate metrics. Well-designed metrics can provide valid evaluation of different models, while unreasonable metrics might lead to incorrect conclusions. \par Table \ref{table:metrics} lists widely used metrics in different tasks. For classification methods, overall accuracy and mean accuracy are most frequently used. Segmentation models can be analyzed by accuracy or (m)IoU. In detection tasks, the result are usually evaluated region-wise, so (m)IoU, accuracy, precision and recall could apply. MOTA and MOTP are specially designed for object tracking modelts, while EPE is for scene for estimation. ROC curves, which is the derivative of precision and recall, help evaluate the performance of 3D match and registration models. Besides, visualization is always an effective supplement of numbers. \begin{table*}[htbp] \centering \caption{Commonly used metrics for different tasks. In this table, $N$ denotes the number of samples, $C$ denotes the number of categories, $IDS$ denotes the number of identity switches, $I_{i,j}$ denotes the number of points that are from ground truth class/instance $i$ and labelled as $j$, $TP/TN/FP/FN$ stands for the number of true positives, true negatives, false positives and false negatives respectively. Higher metrics indicate better results if not specified otherwise.} \begin{tabular}{|c|c|c|c|} \hline Metric & Formula & Explanation \\ \hline Accuracy & $Accuracy=\frac{TP+TN}{TP+TN+FP+FN}$ & \multicolumn{1}{|m{9cm}|}{Accuracy indicates how many predictions are correct over all predictions. ``Overall accuracy (OA)" indicates the accuracy on the entire dataset.} \\ \hline mACC & $mACC=\frac{1}{C}\sum_{c=1}^C Accuracy_c$ & \multicolumn{1}{|m{9cm}|}{The mean of accuracy on different categories, useful when the categories are imbalanced.} \\ \hline Precision & $Precision=\frac{TP}{TP+FP}$ & \multicolumn{1}{|m{9cm}|}{The ratio of correct predictions over all predictions.} \\ \hline Recall & $Recall=\frac{TP}{TP+FN}$ & \multicolumn{1}{|m{9cm}|}{The ratio of correct predictions over positive samples in the ground truth.} \\ \hline F1-Score & $F_1=2\times \frac{Precision\cdot Recall}{Precision + Recall}$ & \multicolumn{1}{|m{9cm}|}{The harmonic mean of precision and recall.} \\ \hline IoU & $IoU_i=\frac{I_{i,i}}{\sum_{c=1}^C (I_{i,c}+I_{c,i}) - I_{i,i}}$ & \multicolumn{1}{|m{9cm}|}{Intersection over Union (of class/instance $i$). The intersection and union are calculated between the prediction and the ground truth.}\\ \hline mIoU & $mIoU = \frac{1}{C}\sum_{c=1}^{C}IoU_i$ & \multicolumn{1}{|m{9cm}|}{The mean of IoU on all classes/instances.} \\ \hline MOTA & $MOTA=1-\frac{FN+FP+IDS}{TP+FN}$ & \multicolumn{1}{|m{9cm}|}{Multi-object tracking accuracy (MOTA) synthesizes 3 error sources: false positives, missed targets and identity switches, and the number of ground truth (as $TP+FN$) is used for normalization.} \\ \hline MOTP & $MOTP=\frac{\sum_{i,t} e_{i,t}}{\sum_t d_t}$ & \multicolumn{1}{|m{9cm}|}{Multi-object tracking precision (MOTP) indicates the precision of localization. $d_t$ denotes the number of matches at time $t$, and $e_{i,t}$ denotes the error of the $i$-th pair at time $t$.} \\ \hline EPE & $EPE=||\Hat{sf}-sf||_2$ & \multicolumn{1}{|m{9cm}|}{End point error (EPE) is used in scene flow estimation, also referred as EPE2D/EPE3D for 2D/3D data respectively. $\Hat{sf}$ denotes the predicted scene flow vector while $sf$ denotes the ground truth.} \\ \hline \end{tabular} \label{table:metrics} \end{table*} \section{Classification} \subsection{Overview} Classification on point clouds is commonly known as 3D shape classification. Similar to image classification models, models on 3D shape classification usually first generate a global embedding with an aggregation encoder, then pass the embedding through several fully connected layers to obtain the final result. Most 3D shape classification methods are tested with clean 3D models (as in Figure \ref{fig:2}). Based on the point cloud aggregation method, classification models can be generally divided into two categories: projection-based methods and point-based methods. \begin{figure*}[h] \begin{center} \includegraphics[width=5in]{shapenet.png} \end{center} \caption{3D models from ShapeNet \cite{shapenet2015}. ShapeNet contains large-scale 3D models with manually verified annotation.} \label{fig:2} \end{figure*} \subsection{Projection-based Methods} Projection-based methods project the unstructured 3D point clouds into specific presupposed modality (e.g. voxels, pillars), and extract features from the target format, which allows them to benefit from the previous research findings in the corresponding direction. \par \subsubsection{Multi-view representation} MvCNN \cite{su15mvcnn} is a method based on a multi-view representation of point clouds. A 3D point cloud is represented by a group of 2D images by rendering snapshots from different angles. Each image in the group will be passed through a CNN to extract view-based features, pooled across views and passed through another CNN to build a compact descriptor. While MVCNN does not distinguish different views, it is helpful to consider the relationship among views. GVCNN \cite{feng2018gvcnn} is a method that takes advantage of this relationship. By quantifying the discrimination of views, we are able to divided the set of views into groups based on their discrimination scores. The view descriptors will be passed through intra-group pooling and cross-group fusion for prediction. Aside from the models mentioned above, \cite{yu2018multi} and \cite{yang2019learning} also improve the recognition accuracy with multi-view representation. \subsubsection{Volumetric representation} VoxNet \cite{maturana2015voxnet} is an early method using the volumetric representation. In this method, each point $(x, y, z)$ is projected into a corresponding discrete voxel point $(i, j, k)$. Each point cloud will be mapped into an occupancy grid of $32\times 32\times 32$ voxels, and the grid will then be passed through two 3D convolutional layers to obtain the final representation. \par VoxNet simply uses adaption of CNN layers for the prediction head, which leads to potential loss of detailed spatial information. 3D ShapeNet \cite{shapenet2015} proposed a belief-based deep convolutional network to learn the distribution of point clouds in different 3D shapes. In this method, 3D shapes are represented by the probability distributions of binary variables on grids. \par While volumetric methods already achieve satisfactory performance, most suffer from the cubic growth of computation complexity and memory footprint, hence the resolution of the grid is strictly limited. OctNet \cite{riegler2017octnet} improved the efficiency by introducing a hybrid grid-octree structure to hierarchically partition point clouds. A point cloud is represented by several octrees along a regular grid, each octree is encoded as a bit string, and features are generated through naive arithmetic. Inspired by OctNet, OCNN \cite{wang2017cnn} then proposed a method that introduces 3D-CNNs to extract features from octrees. \par Methods based on volumetric representations as mentioned above are naturally coarse as only a small fraction of voxels are non-empty and the detailed context inside each voxel is hardly collected. The balance between resolution and computation is difficult to achieve in practice. \par \subsubsection{Basis point set} BPS \cite{prokudin2019efficient} proposed a new approach that breaks the convention that point clouds, even with various sizes, are usually projected onto a grid of same size. In BPS, input points are first normalized into a unit ball, then a group of points is randomly sampled to make up a basis point set (BPS). The sampled BPS is constant for all point clouds in a dataset. For a given point cloud $X$, each point $x_i$ is represented by the Euclidean distance between itself and its nearest neighbor in BPS. By passing such representation through the last two fully connected layers of PointNet, the model achieves performance similar to that of the original PointNet design. \subsection{Point-based Methods} Compared with projection-based methods that aggregate points from a spatial neighborhood, point-based methods attempt to learn features from individual points. Most of recent work focuses on this direction. \subsubsection{MLP networks} PointNet \cite{qi2017pointnet} is a famous architecture that takes advantage of multi-layer perceptrons (MLPs). The input (an $n \times 3$ 2D tensor) is first multiplied by an affine transformation matrix predicted by a mini-network (T-Net) to hold invariance under geometric transformations. The point set is then passed through a group of MLPs followed by another joint alignment network, and a max-pooling layer to obtain the final global feature. This backbone can be used for both classification and segmentation prediction. For classification, the global feature is passed through an MLP for output scores. For segmentation, the concatenations of the global feature and different levels of intermediate features from each point are passed through an MLP for the classification result of each point. Conventional CNNs take features at different scales by a stack of convolutional layers; inspired by that, PointNet++ \cite{qi2017pointnet++} is proposed. In this work, the local region of a point $x$ is defined as the points within a sphere centered at $x$. One set abstraction level here contains a sampling layer, a grouping layer to identify local regions and a PointNet layer. Stacking such set abstraction levels allows us to extract features hierarchically as CNNs for image tasks do. \par The simple implementation and promising performance of PointNet \cite{qi2017pointnet} and PointNet++ \cite{qi2017pointnet++} inspired a lot of follow-up work. PointWeb \cite{zhao2019pointweb} is adapted from PointNet++ and improves quality of features by introducing Adaptive Feature Adjustment (AFA) to make use of context information of local neighborhoods. In addition, SRN \cite{duan2019structural} proposed Structural Relation Network (SRN) to equip PointNet++, and obtained better performance. \subsubsection{Convolutional networks} Convolution kernels on 2D data can be extended to work on 3D point cloud data. As mentioned before, VoxNet \cite{maturana2015voxnet} is an early work that directly takes advantage of 3D convolution. \par A-CNN \cite{komarichev2019cnn} proposed another way to apply convolution on point clouds. In order to prevent redundant information from overlapped local regions (the same group of neighboring points might be repeatedly included in regions at different scales), A-CNN proposed a ring-based scheme instead of spheres. To convolve points within a ring, points are projected on a tangent plane at a query point $q_i$, then ordered in clockwise or counter-clockwise direction by making use of cross product and dot product, and eventually a 1-D convolution kernel will be applied to the ordered sequence. The output feature can be used for both classification and segmentation as in PointNet.\par RS-CNN \cite{liu2019relation} is another convolutional network based on relation-shape convolution. An RS-Conv kernel takes a neighborhood around a certain point as its input, and learns the mapping from naive relations (e.g. Euclidean distance, relative position) to high-level relations among points, and encodes the spatial structure within the neighborhood with the learned mapping.\par In PointConv \cite{wu2019pointconv}, the convolution operation is defined as finding a Monte Carlo estimation of the hidden continuous 3D convolution w.r.t. an importance sampling. The process is composed with a weighting function and a density function, implemented by MLP layers and a kernelized density estimation. Furthermore, the 3D convolution is reduced into matrix multiplication and 2D convolution for memory and computational efficiency and easy deployment. A similar idea is used in MCCNN \cite{hermosilla2018monte}, where convolution is replaced by a Monte Carlo estimation based on the density function of the sample. \par Geo-CNN \cite{lan2019modeling} proposed another way to model the geometric relationship among neighborhood points. By taking six orthogonal bases, the space will be separated into eight quadrants, and all vectors in a specific quadrant can be composed by three of the bases. Features are extracted independently along each direction with corresponding direction-associated weight matrices, and are aggregated based on the angle between the geometric vector and the bases. The feature of some specific point at the current layer is the sum of features of the given point and its neighboring edge features from the previous layer. \par In SFCNN \cite{rao2019spherical}, the input point cloud is projected onto regular icosahedral lattices with discrete sphere coordinates, hence convolution can be implemented by maxpooling and convolution on the concatenated features from vertices of spherical lattices and their neighbors. SFCNN holds rotation invariance and is robust to perturbations. \subsubsection{Graph networks} Graph networks consider a point cloud as a graph and the vertices of the graph as the points, and edges are generated based on the neighbors of each point. Features will be learned in spatial or spectral domains. \par ECC \cite{simonovsky2017dynamic} first proposed the idea of considering each point as a vertex of the graph and connected edges between pairs of points that are ``neighbors". Then, edge conditioned convolution (ECC) is applied with a filter generating network such as MLP. Neighborhood information is aggregated by maxpooling and coarsened graph will be generated with VoxelGrid \cite{rusu20113d} algorithm. After that, DGCNN \cite{wang2019dynamic} uses a MLP to implement EdgeConv, followed by channel-wise symmetric aggregation on edge features from the neighborhood of each point, which allows the graph to be dynamically updated after each layer of the network. \par Inspired by DGCNN, Hassani and Haley \cite{hassani2019unsupervised} proposed an unsupervised multi-task approach to learn shape features. The approach consists of an encoder and an decoder, where the encoder is constructed from multi-scale graphs, and the decoder is constructed for three unsupervised tasks (clustering, self-supervised classification and reconstruction) trained by a joint loss. \par ClusterNet \cite{chen2019clusternet} uses rigorously rotation-invariant (RRI) module to generate rotation-invariant features from each point, and an unsupervised agglomerative hierarchical clustering method to construct hierarchical structures of a point cloud. Features of sub-clusters at each level are first learned with an EdgeConv block, then aggregated by maxpooling. \par \subsubsection{Other networks} Aside from OctNet \cite{riegler2017octnet}, which uses octrees on voxel grids to hierarchically extract features from point clouds, Kd-Net \cite{klokov2017escape} makes use of K-d trees to build a bottom-up encoder. Leaf node representations are normalized 3D coordinates (by setting the center of mass as origin and rescaled to $[-1,1]^3$), and non-leaf node representations are calculated from its children nodes with MLP. The parameters of MLPs are shared within each level of the tree. Moreover, 3DContextNet \cite{zeng20183dcontextnet} proposed another method based on K-d trees. While non-leaf representations are still computed with MLP from its children, the aggregation at each level is more complicated for considering both local cues and global cues. The local cues concern points in the corresponding local region, and the global cues concern the relationship between current position and all positions in the input feature map. The representation at the root will be used for prediction. \par RCNet \cite{wu2019point} introduced RNN to point cloud embedding. The ambient space is first partitioned into parallel beams, each beam is then fed into a shared RNN, and the output subregional features are considered as a 2D feature map and processed by a 2D CNN. \par SO-Net \cite{li2018so} is a method based on the self-organized map (SOM). A SOM is a low-dimensional (two-dimensional in the paper) representation of the input point cloud, initialized by a proper guess (dispersing nodes uniformly in a unit ball), and trained with unsupervised competitive learning. A k-nearest-neighbor set is searched over the SOM for each point, and the normalized KNN set is then passed through a series of fully connected layers to generate individual point features. The point features are used to generate node features by maxpooling according to the association in KNN search, and the node features are passed through another series of fully connected layers and aggregated into a global representation of the input point cloud. \subsection{Experiments} Different methods choose to test their models on various datasets. In order to obtain a better comparison among methods, we select datasets that most methods are tested on, and list the experiment results for them in Table \ref{table:1}. \begin{table*}[htbp] \centering \caption{Experiment results on ModelNet40 classification benchmark. ``OA" stands for overall accuracy and ``mACC" stands for mean accuracy.} \begin{tabular}{|c|c|c|} \hline Methods & ModelNet40(OA) & ModelNet40(mAcc) \\ \hline PointNet \cite{qi2017pointnet} & 89.2\% & 86.2\% \\ \hline PointNet++ \cite{qi2017pointnet++} & 90.7\% & 90.7\% \\ \hline PointWeb \cite{zhao2019pointweb} & 92.3\% & 89.4\% \\ \hline SRN \cite{duan2019structural} & 91.5\% & - \\ \hline Pointwise-CNN \cite{hua2018pointwise} & 86.1\% & 81.4\% \\ \hline PointConv \cite{wu2019pointconv} & 92.5\% & - \\ \hline RS-CNN \cite{liu2019relation} & 92.6\% & - \\ \hline GeoCNN \cite{lan2019modeling} & 93.4\% & 91.1\% \\ \hline A-CNN \cite{komarichev2019cnn} & 92.6\% & 90.3\% \\ \hline Hassani and Haley \cite{hassani2019unsupervised} & 89.1\% & - \\ \hline ECC \cite{simonovsky2017dynamic} & 87.4\% & 83.2\% \\ \hline SFCNN \cite{rao2019spherical} & 91.4\% & - \\ \hline DGCNN \cite{wang2019dynamic} & 92.2\% & 90.2\% \\ \hline ClusterNet \cite{chen2019clusternet} & 87.1\% & - \\ \hline BPS \cite{prokudin2019efficient} & 91.6\% & - \\ \hline KD-Net \cite{klokov2017escape} & 91.8\% & 88.5\% \\ \hline 3DContextNet\cite{zeng20183dcontextnet} & 91.1\% & - \\ \hline RCNet \cite{wu2019point} & 91.6\% & - \\ \hline SO-Net \cite{li2018so} & 90.9\% & 87.3\% \\ \hline \end{tabular} \label{table:1} \end{table*} \section{Segmentation} \subsection{Overview} 3D segmentation intends to label each individual point, which requires the model to collect both global context and detailed local information at each point. Figure \ref{fig:3} shows some examples from S3DIS \cite{armeni20163d} dataset. There are two main tasks in 3D segmentation: semantic segmentation and instance segmentation.\par Since a large number of classification models are able to achieve very high performance on popular benchmarks, they tend to test their backbone on segmentation datasets to prove the novel contribution and generalization ability. We will not reintroduce these models if they have been mentioned above. There are also some models that benefit from the jointly training on multiple tasks, and we will discuss these methods later in section 3.4. \begin{figure}[htbp] \begin{center} \includegraphics[width=3.2in]{s3dis.png} \end{center} \caption{Stanford Large-Scale 3D Indoor Spaces Dataset \cite{armeni20163d} (S3DIS).} \label{fig:3} \end{figure} \subsection{Semantic Segmentation} Similar to 3D shape classification models, based on how the raw point cloud is organized, semantic segmentation methods can be generally divided into projection-based methods and point-based methods. \subsubsection{Projection-based methods} Huang and You \cite{huang2016point} project the input point cloud into occupancy voxels, which are then fed into a 3D convolutional network to generate voxel-level labels. All points within a voxel are assigned with the same semantic label as the voxel. ScanComplete \cite{dai2018scancomplete} utilizes fully convolutional networks to adapt to different input data sizes, and deploys a coarse-to-fine strategy to improve the resolution of predictions hierarchically. VV-Net \cite{meng2019vv} also transfers unordered points into regular voxel grids as the first step. After that, the local geometry information of each voxel will be encoded with a kernel-based interpolated variational auto-encoder (VAE). In each voxel, a radial basis function (RBF) is computed to generate a local continuous representation to deal with sparse distributions of points. \par F. Jaremo-Lawin et al. \cite{lawin2017deep} proposed a multi-view method that first projects a 3D cloud to 2D planes from multiple camera views, then pixel-wise scores on synthetic images are predicted with a multi-stream FCN, and the final labels are obtained by fusing scores over different views. PolarNet \cite{Zhang_polar_2020_CVPR}, however, proposed a polar BEV representation. By implicitly aligning attention with the long-tailed distribution, this representation reduces the imbalance of points across grid cells along the radial axis.\par Some other methods leverage scans in multiple modalities. 3DMV \cite{dai20183dmv} proposed a joint 3D-multi-view network that combines features from RGB images and point cloud. Features are extracted with a 3D CNN stream and a group of 2D streams respectively. MVPNet \cite{jaritz2019multi} proposed another aggregation to fuse features (from images and point cloud) in 3D canonical space with a point-based network. \par \par \subsubsection{Point-based methods} First of all, PointNet \cite{qi2017pointnet} and PointNet++ \cite{qi2017pointnet++} can predict semantic labels with corresponding prediction branches attached. Engelmann et al. \cite{engelmann2018know} proposed a method to define neighborhoods in both world space and feature space with k-means clustering and KNN. A pairwise distance loss and centroid loss are introduced to feature learning based on the assumption that points with the same semantic label are supposed to be closer. PointWeb \cite{zhao2019pointweb}, as mentioned in classification, can also be adapted to predict segmentation labels. PVCNN \cite{liu2019point} proposed a comprehensive method that leverages both point and voxel representation to obtain memory and computation efficiency simultaneously.\par Some extensions of the convolution operator are introduced for feature extraction on point cloud. PCCN \cite{wang2018deep} introduces parametric continuous convolutional layers. These layers are parameterized by MLPs and span full continuous vector spaces. The generalization allows models to learn over any data structure where the support relationship is computable. Pointwise-CNN \cite{hua2018pointwise} introduced a point-wise convolution where the neighbor points are projected into kernel cells and convolved with corresponding kernel weights. Engelmann et al. \cite{engelmann2019dilated} proposed Dilated Point Convolution (DPC) to aggregate dilated neighbor features, instead of the conventional k-nearest neighbors. \par Graph networks are also used in some segmentation models to obtain the underlying geometric structures of the input point clouds. SPG \cite{landrieu2018large} introduced a structure called superpoint graph (SPG) to capture the organization of point clouds. The idea is further extended in \cite{landrieu2019point}, which introduces a oversegmentation (into pure superpoints) of the input point cloud. Aside from that, Graph Attention Convolution \cite{wang2019graph} (GAC) is proposed to learn relevant features from local neighborhoods selectively. By dynamically assigning attention weights to different neighbor points and different feature channels based on their spatial positions and feature differences, the model is able to learn discriminative features from the most relevant part of the neighbor point sets.\par Compared with projection-based methods, point-based methods usually require more computation and therefore have more trouble dealing with large-scale data. Tatarchenko et al. \cite{tatarchenko2018tangent} introduced tangent convolutions to solve this. A fully-convolutional network is designed based on the tangent convolution and successfully improved the performance on large-scale point clouds. RandLA-Net \cite{Hu_rand_2020_CVPR} attempted to reduce computation by replace conventional complex point sampling approaches with random sampling. And to avoid random sampling from discarding crucial information, a novel feature aggregation module is introduced to enlarge receptive fields of each point. \par Based on the fact that the production of point-level labels is labor-intensive and time-consuming, some methods explored weakly supervised segmentation. Xu and Lee \cite{xulee2020weakly} proposed a weakly supervised approach which only requires a small fraction of points to be labelled at training stage. By learning gradient approximation and smoothness constraints in geometry and color, competitive results can be obtained with as few as 10\% points labelled. On the other hand, Wei et al. \cite{Wei_multi_2020_CVPR} introduced a multi-path region mining module, which can provide pseudo point-level labels by a classification network over weak labels. The segmentation network is then trained with these pseudo labels in a fully supervised manner. \subsection{Instance Segmentation} Instance segmentation, compared with semantic segmentation, requires distinguishing points with same semantic meaning, which makes the task more challenging. In this section, instance segmentation methods are further divided into two categories: proposal-based methods and proposal-free methods. \subsubsection{Proposal-based methods} Proposal-based instance segmentation methods can be considered as the combination of object detection and mask prediction. 3D-SIS \cite{hou20193d} is a fully convolutional network for 3D semantic instance segmentation where geometry and color signals are fused. For each image, 2D features for each pixel are extracted by a series of 2D convolutional layers, and then backprojected to the associated 3D voxel grids. The geometry and color features are passed through a series of 3D convolutional layers respectively and concatenated into a global semantic feature map. Then a 3D-RPN and a 3D-RoI layer are applied to generate bounding boxes, instance masks and object labels. Generative Shape Proposal Network (GSPN) \cite{yi2019gspn} generates proposals by reconstructing shapes from the scene instead of directly regresses bounding boxes. The generated proposals are refined with a region-based PointNet (R-PointNet), and the labels are determined with a point-wise binary mask prediction over all class labels. 3D-BoNet \cite{yang2019learning} is a single-stage method that adapts PointNet++ \cite{qi2017pointnet++} as backbone network to global features and local features at each point. Two prediction branches follow to generate instance-level bounding box and point-level mask respectively. Zhang el al. \cite{zhang2020instance} proposed a method for large-scale outdoor point clouds. The point cloud is first encoded into a high-resolution BEV representation augmented by KNN, and features are then extracted by voxel feature encoding (VFE) layers and self-attention blocks. For each grid, a horizontal object center and its height limit are predicted, objects that are closed enough will be merged, and eventually these constraints will be leveraged to generate instance prediction. \subsubsection{Proposal-free methods} Proposal-free methods tend to generate instance-level label based on semantic segmentation by algorithms like clustering. Similarity Group Proposal Network (SGPN) \cite{wang2018sgpn} is a representative work that learns a feature and semantic map for each point, and a similarity matrix to estimate the similarity between pairs of features. A heuristic non-maximal suppression method follows to merge points into instances. Lahoud et al. \cite{lahoud20193d} adopted multi-task metric learning to (1) learn a feature embedding such that voxels with the same instance label are close and those with different labels are separated in the feature space and (2) predict the shape of instance at each voxel. Instance boundaries are estimated with mean-shift clustering and NMS. \par Zhang et al. \cite{zhang2019point} introduced a probabilistic embedding to encode point clouds. The embedding is implemented with multivariate Gaussian distribution, and the Bhattacharyya kernel is adopted to esimate the similarity between points. Proposal-free methods do not suffer from the computational complexity of region-proposal layers; however, it is usually difficult for them to produce discriminative object boundaries from clustering. \par There are also several instance segmentation methods based on projection. SqueezeSeg \cite{wu2018squeezeseg} is one of the pioneer works in this direction. In this method, points are first projected onto a sphere for a grid-based representation. The transformed representation is of size $H\times W\times C$, where in practice $H$=64 is the number of vertical channels of lidar, $W$ is manually picked to be 512, and $C$ equals to 5 (3 dimensional coordinates + intensity measurement + range). The representation is then fed through a conventional 2D CNN and a conditional random field (CRF) for refined segmentation results. This method is afterwards improved by SqueezeSegv2 \cite{wu2019squeezesegv2} with a context aggregation module and a domain adaptation pipeline. \par The idea of projection-based methods is further explored by Lyu et al. \cite{Lyu_Seg2D_2020_CVPR}. Inspired by graph drawing algorithms, they proposed a hierarchical approximate algorithm to project point clouds into image representations with abundant local geometric information preserved. The segmentation will then be generated by a multi-scale U-Net from the image representation. With this innovative projection algorithm, the method obtained significant improvement. \par PointGroup \cite{Jiang_pointgroup_2020_CVPR} proposed a bottom-up framework with two prediction branches. For each point, its semantic label and relative offset to its respective instance centroid are predicted. The offset branch helps better grouping of points into objects as well as separation of objects with the same semantic label. During the clustering stage, both original positions and shifted positions are considered, the association of these two results turns out to have a better performance. Along with NMS based on the newly designed ScoreNet, this method outperforms other works of the day by a great margin. \par \subsection{Joint Training} As mentioned above, some recent works jointly address more than one problems to better realized the power of models. The unsupervised multi-task approach proposed by Hassani and Haley \cite{hassani2019unsupervised} is an example in which clustering, self-supervised classification and reconstruction are jointly trained. The two tasks under segmentation, semantic segmentation and instance segmentation, are also proven to likely benefit from simultaneous training. \par There are two naive ways to solve semantic segmentation and instance segmentation at the same time: (1) solve semantic segmentation first, run instance segmentation on points of certain labels based on the result of semantic segmentation, (2) solve instance segmentation first, and directly assign semantic labels with instance labels. These two step-wise paradigms highly depend on the output quality of the first step, and are not able to make full use of the shared information between two tasks. \par JSIS3D \cite{pham2019jsis3d} develops a pointwise network that predicts the semantic label of each point and high-dimensional embeddings at the same time. After these steps, instances of the same class will have similar embeddings, then a multi-value conditional random field model is applied to synthesize semantic and instance labels, formulating the problem as jointly optimizing labels in the field model. ASIS \cite{wang2019associatively} is another method that makes the two tasks benefit from each other. Specifically, instance segmentation benefits from semantic segmentation by learning semantic-aware instance embedding at point level, while semantic features of the point set from the same instance will be fused together to generate accurate semantic predictions for every point. \subsection{Experiments} We select the benchmarks on which most methods are tested, S3DIS\cite{armeni20163d}, to compare the performance of different methods. The performances are summarized in Table \ref{table:2}. \begin{table*}[!htbp] \centering \caption{Experiment results on on semantic segmentation in S3DIS benchmark. Only results that are reported in the original papers are listed, those reported as a reference by other papers are excluded because they are sometimes conflicting.} \begin{tabular}{|c|c|c|c|c|} \hline Methods & Area5(mACC) & Area5(mIoU) & 6-fold(mACC) & 6-fold(mIoU) \\ \hline PointCNN \cite{li2018pointcnn} & 63.9 & 57.3 & 75.6 & 65.4 \\ \hline PointWeb \cite{zhao2019pointweb} & 66.6 & 60.3 & 76.2 & 66.7 \\ \hline A-CNN \cite{wu2019pointconv} & - & - & - & 62.9 \\ \hline DGCNN \cite{wang2019dynamic} & - & - & - & 56.1 \\ \hline VV-Net \cite{meng2019vv} & - & - & 82.2 & 78.2 \\ \hline PCCN \cite{wang2018deep} & - & 58.3 & - & - \\ \hline GAC \cite{wang2019graph} & - & 62.9 & - & - \\ \hline DPC \cite{engelmann2019dilated} & 68.4 & 61.3 & - & - \\ \hline SSP+SPG \cite{landrieu2019point} & - & - & 78.3 & 68.4\\ \hline JSIS3D \cite{pham2019jsis3d} & - & - & 78.6 & - \\ \hline ASIS \cite{wang2019associatively} & 60.9 & 53.4 & 70.1 & 59.3 \\ \hline Xu and Lee \cite{xulee2020weakly} & - & 48.0 & - & - \\ \hline RandLA-Net \cite{Hu_rand_2020_CVPR} & - & - & 82.0 & 70.0 \\ \hline Tatarchenko et al. \cite{tatarchenko2018tangent} & 62.2 & 52.8 & - & - \\ \hline \hline \end{tabular} \label{table:2} \end{table*} \section{Detection, Tracking and Flow Estimation} \subsection{Overview} Object detection is a recent research hotspot as the basis of many practical applications. It aims to locate all the objects in the given scene. 3D object detection methods can be generally divided into three categories: multi-view methods, projection-based methods and point-based methods. Figure 4.1 shows an example of 3D object detection on multiple (lidar and camera) views. Aside from image object detection models, the exclusive characteristics of point cloud data provide more potential of optimization. Also, since 3D object tracking and scene flow estimation are two derivative tasks that highly depend on object detection, they will be discussed together in this section. \begin{figure}[htbp] \begin{center} \includegraphics[width=3.2in]{nuscene.png} \end{center} \caption{An outdoor scene from nuScenes \cite{caesar2019nuscenes}, annotations in multi-view (lidar/camera) are provided.} \label{fig:4} \end{figure} \subsection{Object Detection} \subsubsection{Projection-based methods} The success of convolutional neural networks in image object detection inspired attempts to apply 3D CNN on projected point cloud data. VoxelNet \cite{zhou2018voxelnet} proposed an approach that applies random sampling to the point set within each voxel, and passes them through a novel voxel feature encoding (VFE) layer based on PointNet \cite{qi2017pointnet} and PointNet++ \cite{qi2017pointnet++} to extract point-wise features. A region proposal network is used to produce detection results. Similar to classification models with volumetric representation, VoxelNet runs at a relatively low speed due to the sparsity of voxels and 3D convolutions. SECOND \cite{yan2018second} then proposed an improvement in inference efficiency by taking advantage of sparse convolution network. \par PointPillars \cite{lang2019pointpillars} utilizes point cloud data in another way. Points are organized in vertical columns (called Pillars), and the features of pillars are extracted with PointNet to generate a pseudo image. The pseudo image is then considered as the input of a 2D object detection pipeline to predict 3D bounding boxes. PointPillars is more accurate than previous fusion approaches, and it is capable of real-time applications with a running speed of 62 FPS. Wang et al. \cite{wang2020} further proposed another anchor-free bounding box prediction based on a cylindrical projection into multi-view features. \par Projection-based methods suffer from spatial information loss inevitably. Aside from using point-based networks instead, He et al. \cite{He_SAS_2020_CVPR} proposed a structure-aware method to mitigate the problem. The convolutional layers are explicitly supervised to contain structural information by an auxiliary network. The auxiliary network converts the convolutional features from the backbone network to point-level representations and is jointly optimized. After the training process is finished, the auxiliary network can be detached to speed up the inference. \par \subsubsection{Point-based methods} Most point-based methods attempt to minimize information loss during feature extraction, and they are the group with the best performance so far. STD \cite{yang2019std} introduced the idea of using sphere anchors for proposal generation, which achieves a high recall with significantly less computation than previous methods. Each proposal is passed through a PointsPool layer that converts proposal features from sparse expression to compact representation, and is robust under transformation. In addition to the regular regression branch, STD has another IoU branch to replace the role of classification score in NMS.\par Some methods use foreground-background classification to improve the quality of proposals. PointRCNN \cite{shi2019pointrcnn} is such a framework, in which points are directly segmented to screen out foreground points, while semantic features and spatial features are then fused to produce high-quality 3D boxes. Compared with multi-view methods above, segmentation-based methods perform better for complicated scenes and occluded objects.\par Furthermore, Qi et al. proposed VoteNet \cite{qi2019vote}. A group of points are sampled as seeds, and each seed independently generates a vote for potential center points of objects in the point cloud with the help of PointNet++ \cite{qi2017pointnet++}. By taking advantage of voting, VoteNet outperforms previous approaches on two large indoor benchmarks. However, as the center point prediction of virtual center points is not as stable, the method performs less satisfactorily in wild scenes. As a follow-up work, ImVoteNet \cite{Qi_ImVoteNet_2020_CVPR} inherited the idea of VoteNet and achieved prominent improvement by fusing 3D votes with 2D votes from images.\par There are also attempts that consider domain knowledge as an auxiliary to enhance features. Associate-3Ddet \cite{Du_A3D_2020_CVPR} introduced the idea of perceptual-to-conceptual association. To enrich perception features that might be incomplete due to occlusion or sparsity, a perceptual-to-conceptual module is proposed to generate class-wise conceptual models from the dataset. The perception and conceptual features will be associated for feature enhancement. \par Yang et al. \cite{Yang_3DSSD_2020_CVPR} proposed a point-based anchor-free method 3DSSD. This method attempts to reduce computation by abandoning the upsampling layers (e.g. feature propagation layers in \cite{yang2019std}) and refinement stages that are widely used in previous point-based methods. Previous set abstraction layers for downsampling only leverage furthest-point-sampling based on Euclidean distance (D-FPS), instances with a small number of interior points are easily lost under this strategy. In this case, removing upsampling layers could lead to huge performance drop. 3DSSD proposed F-FPS, a new sampling strategy based on feature distances, to preserve more foreground points for instances. The fusion of F-FPS and D-FPS, together with the candidate generation layer and 3D center-ness assignment in the prediction head, help this method outperform previous single-stage methods with a considerable margin. \par Graph neural networks have also been introduced to 3D object detection for its ability to accommodate intrinsic characteristics of point clouds like sparsity. PointRGCN \cite{zarzar2019pointrgcn} is an early work that introduce graph-based representation for 3D vehicle detection refinement. After that, HGNet \cite{Chen_HGNet_2020_CVPR} introduces a hierarchical graph network based on shape-attentive graph convolution (SA-GConv). By capturing object shapes with relative geometric information and reasoning on proposals, the method obtained a significant improvement on previous results. Besides, Point-GNN \cite{Shi_PointGNN_2020_CVPR} proposed a single-shot method based on graph neural networks. It first builds a fixed radius near-neighbors graph over the input point cloud. Then, the category and the bounding box of affiliation are predicted with the point graph. Finally, a box merging and scoring operation is used to obtain accurate combination of detection results from multiple vertices. \par \subsubsection{Multi-view methods} MV3D \cite{chen2017multi} is a pioneering method in multi-view object detection methods on point clouds. In this approach, candidate boxes are generated from BEV map and projected into feature maps of multiple views (RGB images, lidar data, etc.), then the region-wise features extracted from different views are combined to produce the final oriented 3D bounding boxes. While this approach achieves satisfactory performance, much like many other early multi-view methods, its running speed is too slow for practical use. \par Attempts to improve multi-view methods generally take one of two directions. First, we could find a more efficient way to fuse information from different views. Liang et al. \cite{liang2018deep} use continuous convolutions to effectively fuse feature maps from images and lidar at different resolutions. Image features for each point in BEV space are utilized to generate a dense BEV feature map by bi-linear interpolation with projections of image features within the BEV plane. Experiments show that dense BEV feature maps perform better than discrete image feature maps and sparse point cloud feature maps. Second, many methods propose innovative feature extraction approaches to obtain representations of input data with higher robustness. SCANet \cite{lu2019scanet} introduced a Spatial Channel Attention (SCA) module to make use of multi-scale contextual information. The SCA module captures useful features from the global and multi-scale context of given scene, while an Extension Spatial Unsample (ESU) module helps combine multi-scale low-level features to generate high-level features with rich spatial information, which then leads to accurate 3D object proposals. In RT3D \cite{zeng2018rt3d}, the majority of convolution operations prior to the RoI pooling module are removed. With such optimization, RoI convolutions only need to be performed once for all proposals, accelerating the method to run at 11.1 FPS, which is five times faster than MV3D \cite{chen2017multi}. \par Another approach to detect 3D objects is to generate candidate regions on 2D plane with 2D object detectors, then extract a 3D frustum proposal for each 2D candidate region. In F-PointNets \cite{qi2018frustum}, each 2D region generates a frustum proposal, and the features of each 3D frustum are learned with PointNet \cite{qi2017pointnet} or PointNet++ \cite{qi2017pointnet++} and used for 3D bounding box estimation. PointFusion \cite{xu2018pointfusion} uses both 2D image region and corresponding frustum points for more accurate 3D box regression. A fusion network is proposed to directly predict corner locations of boxes by fusing image features and global features from point clouds. \par \subsection{Object Tracking} Object tracking targets estimating the location of a certain object in subsequent frames given its state in the first frame. The success of Siamese networks \cite{bertinetto2016fully} in 2D image object tracking inspired 3D object tracking, and Giancola et al. \cite{giancola2019leveraging} extend Siamese networks to 3D. In this method, candidates are first generated by a Kalman filter, then passed through an encoding model to generate compact representations with shape regularization, and match the detected objects by cosine similarity. Zarzar et al. \cite{zarzar2019pointrgcn} proposed another method that captures target objects more efficiently by leveraging a 2D Siamese network to detect coarse object candidates on BEV representation. The coarse candidates are then refined by cosine similarity in the 3D Siamese network.\par Chiu et al. \cite{chiu2020probabilistic} introduced the Kalman filter to encode the hidden states of objects. The state of an object is represented by a tuple of 11 variables, including position, orientation, size and speed. A Kalman filter is adopted to predict the object in next frame based on previous information, and a greedy algorithm is used for data association with Mahalanobis distance.\par Besides, Qi et al. \cite{Qi_P2B_2020_CVPR} proposed P2B, a point-to-box method for 3D object tracking. It divides the task into two parts. The first part is target-specific feature augmentation, seeds from the template and the search area are generated with a PointNet++ backbone, and the search area seeds will be enriched with target clues from the template. The second is target proposal and verification, candidate target centers are regressed and seed-wise targetness is evaluated for joint target proposal and verification. \par \subsection{Scene Flow Estimation} Similar to optical flow estimation on images, 3D scene flow estimation works on a sequence of point clouds. FlowNet3D \cite{liu2019flownet3d} is a representative work that directly estimates scene flows from pairs of consecutive point clouds. The flow embedding layer is used to learn point-level features and motion features. The experiment results of FlowNet3D shows that it performs less than satisfactorily in non-static scenes, and the angles of predicted motion vectors sometimes significantly differ from the ground truth. FlowNet3D++ \cite{wang2020flownet3d++} is proposed to fix these issues by introducing a cosine distance loss in angles, and a point-to-plane distance loss to improve accuracy in dynamic scenes. HPLFlowNet \cite{gu2019hplflownet}, on the other hand, proposed a series of bilateral convolutional layers to fuse information from two consecutive frames and restore structural information from unconstructed point clouds. \par In addition, MeteorNet \cite{liu2019meteornet} introduced direct grouping and chained-flow grouping to group temporal neighbors, and adopted information aggregation over neighbor points to generate representation for dynamic scenes. Derived from recurrent models in images, Fan and Yang \cite{fan2019pointrnn} proposed PointRNN, PointGRU and PointLSTM to encode dynamic point clouds by capturing both spatial and temporary information. \subsection{Experiments} KITTI \cite{Geiger2013IJRR,Geiger2012CVPR,Fritsch2013ITSC,Menze2015CVPR} is one of the most popular benchmarks for many computer vision tasks, including those in images, point clouds, and multi-views. By taking advantage of autonomous driving platforms, KITTI provides raw data of real-world scenes, and allows evaluation on multiple tasks. Table \ref{table:3} shows experimental results of different methods on KITTI. Some methods, such as VoteNet \cite{ding2019votenet}, which does not provide detailed test results on KITTI, are not listed. \begin{table*}[htbp] \centering \caption{Experiment results on KITTI 3D detection benchmark, E/M/H stands for easy/medium/hard samples.} \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|} \hline \multirow{2}*{Method} & \multirow{2}*{Category} & \multirow{2}*{Speed} & \multicolumn{3}{|c|}{Car} & \multicolumn{3}{|c|}{Pedestrians} & \multicolumn{3}{|c|}{Cyclists} \\ \cline{4-12} ~ & ~ & ~ & E & M & H & E & M & H & E & M & H\\ \hline MV3D \cite{chen2017multi} & multi-view & 2.8 & 74.8 & 63.6 & 54.0 & - & - & - & - & - & - \\ \hline AVOD \cite{ku2018joint} & multi-view & 12.5 & 89.8 & 85.0 & 78.3 & 42.6 & 33.6 & 30.1 & 64.1 & 48.1 & 42.4 \\ \hline SCANet \cite{lu2019scanet} & multi-view & 12.5 & 76.4 & 66.5 & 60.2 & - & - & - & - & - & - \\ \hline PIXOR \cite{yang2018pixor} & projection & 28.6 & 84.0 & 80.0 & 74.3 & - & - & - & - & - & - \\ \hline VoxelNet \cite{zhou2018voxelnet} & projection & 2.0 & 77.5 & 65.1 & 57.7 & 39.5 & 33.7 & 31.5 & 61.2 & 48.4 & 44.4 \\ \hline SECOND \cite{yan2018second} & projection & 26.3 & 83.3 & 72.6 & 65.8 & 49.0 & 38.8 & 34.9 & 71.3 & 52.1 & 45.8 \\ \hline PointPillars \cite{lang2019pointpillars} & projection & 62.0 & 82.6 & 74.3 & 69.0 & 54.5 & 41.2 & 38.9 & 77.1 & 85.7 & 52.0 \\ \hline PointRCNN \cite{shi2019pointrcnn} & point & 10.0 & 87.0 & 75.6 & 70.7 & 48.0 & 39.4 & 36.0 & 75.0 & 58.8 & 52.5 \\ \hline PointRGCN \cite{zarzar2019pointrgcn} & point & 3.8 & 86.0 & 95.6 & 70.7 & - & - & - & - & - & - \\ \hline STD \cite{yang2019std} & point & 12.5 & 88.0 & 79.7 & 75.1 & 53.3 & 42.5 & 38.3 & 78.7 & 61.6 & 55.3 \\ \hline Point-GNN \cite{Shi_PointGNN_2020_CVPR} & point & - & 88.3 & 79.5 & 72.3 & 52.0 & 43.8 & 40.1 & 78.6 & 63.5 & 57.0 \\ \hline PV-RCNN \cite{Shi_PVRCNN_2020_CVPR} & point & - & 90.2 & 81.4 & 76.8 & 52.1 & 43.3 & 40.3 & 78.6 & 63.7 & 57.7 \\ \hline 3DSSD \cite{Yang_3DSSD_2020_CVPR} & point & 26.3 & 88.4 & 79.6 & 74.6 & 54.6 & 44.3 & 40.2 & 82.5 & 64.1 & 56.9 \\ \hline \end{tabular} \label{table:3} \end{table*} \section{Registration} \subsection{Overview} In some scenarios like autopilot, it is of great value to find the relationship between point cloud data of the same scene collected in different ways. These data might be collected from different angles, or at different times. 3D point cloud registration (sometimes also called matching) attempts to align two or more different point clouds by estimating the transformation between them. It is a challenging problem affected by a lot of factors including noise, outliers and nonrigid spatial transformation. \subsection{Traditional Methods} The Iterative Closest Point (ICP) algorithm \cite{besl1992method} is a pioneering work that solves 3D point set registration. The basic pipeline of ICP and its variants is as follows: (1) Sample a point set $P$ from the source point cloud. (2) Compute the closest point set $Q$ from the target point cloud. (3) Calculate the registration (transformation) with $P$ and $Q$. (4) Apply the registration, and if the error is above some threshold, go back to step (2), otherwise terminate. A global refinement step is usually required for better performance. The performance of ICP highly depends on the quality of initialization and whether the input point clouds are clean. Generalized-ICP \cite{segal2009generalized} and Go-ICP \cite{yang2015go} are two representative follow-up works that mitigate the problems of ICP in different ways. \par Coherent Point Drift (CPD) algorithm \cite{myronenko2010point} considers the alignment as a problem of probability density estimation. Concretely, the algorithm consider the first point set as the Gaussian mixture model centroids, and the transformation is estimated by maximizing the likelihood in fitting them to the second point set. The movement of these centroids are forced to be coherent to preserve the topological structure. \par Robust Point Matching (RPM) \cite{gold1998new} is another influential point matching algorithm. The algorithm starts with soft assignments of the point correspondences, and these soft assignments will get hardened through deterministic annealing. RPM is generally more robust than ICP, but still sensitive to initialization and noise.\par Iglesias et al. \cite{Iglesias_2020_CVPR} focused on the registration of several point clouds to a global coordinate system. In other words, with the original set of $n$ points, we want to find the correspondences between (subsets of) the original set and $m$ local coordinate systems respectively. Iglesias et al. consider the problem as a Semidefinite Program (SDP), and attempt to analyze it with the application of Lagrangian duality. \par \subsection{Learning-based Methods} DeepVCP \cite{lu2019deepvcp} is the first end-to-end learning-based framework in point cloud registration. Given the source and target point cloud, PointNet++ \cite{qi2017pointnet++} is applied to extract local features. A point weighting layer then helps select a set of $N$ keypoints, after which $N\times C$ candidates from the target point cloud are selected and passed through a deep feature embedding operation together with keypoints from the source. Finally, a corresponding point generation layer takes the embeddings and generates the final result. Two losses are incurred: (1) the Euclidean distance between the estimated corresponding points and ground truth under the ground truth transformation, and (2) the distance between the target under the estimated transformation and ground truth. These losses are combined to consider both global geometric information and local similarity. \par 3DSmoothNet \cite{gojcic2019perfect} is proposed to perform 3D point cloud matching with a compact learned local feature descriptor. Given two raw point clouds as input, the model first computes the local reference frame (LRF) of the neighborhood around the randomly sampled interest points. Then the neighborhoods are transformed into canonical representations and voxelized by Gaussian smoothing, and the local feature of each point is then generated by 3DSmoothNet. The features will then be utilized by a RANSAC approach to produce registration results. The proposed smooth density value (SDV) voxelization outperforms traditional binary-occupancy grids by reducing the impact of boundary effects and noise, and provides greater compactness. Following 3DSmoothNet, Gojcic et al. \cite{gojcic2020learning} proposed another method that formulates conventional two-stage approaches in an end-to-end structure. Earlier methods solve the problem in two steps, the pairwise alignment and the globally consistent refinement, by jointly learning both parts. Gojcic et al.'s method outperforms previous ones with higher accuracy and less computational complexity. \par RPM-Net \cite{yew2020rpm} inherits the idea of RPM \cite{gold1998new} algorithm, and takes advantage of deep learning to enhance robustness against noise, outliers and bad initialization. In this method, the initialization assignments are generated based on hybrid features from a network instead of spatial distances between points. The parameters of annealing is predicted by a secondary network, and a modified Chamfer distance is introduced to evaluate the quality of registration. This method outperforms previous methods no matter the input is clean, noisy, or even partially visible. \section{Augmentation and Completion} \subsection{Overview} Point clouds collected by lidar, especially those from outdoor scenes, suffer from different kinds of quality issues like noise, outliers, and missing points. Many attempts have been made to improve the quality of raw point clouds by completing missing points, removing outliers and so on. The motivation and implementation vary a lot among different approaches; in this paper, we divide them into two categories: discriminative models and generative models. \subsection{Discriminative Methods} Noise in point clouds collected from outdoor scenes is naturally inevitable. To prevent noise from influencing the encoding of point clouds, some denoising methods shall be applied in pre-processing. Conventional methods include local surface fitting, neighborhood averaging and guessing the underlying noise model. PointCleanNet \cite{rakotosaona2020pointcleannet} proposed a data-driven method to remove outliers and reduce noise. With a deep neural network adapted from PCPNet\cite{guerrero2018pcpnet}, the model first classifies outliers and discards them, then estimates a correction projection that projects noise to original surfaces.\par Hermosilla et al. \cite{hermosilla2019total} proposed Total Denoising that achieved unsupervised denoising of 3D point clouds without additional data. The unsupervised image denoisers are usually built based on the assumption that the value of a noisy pixel follows a distribution around a clean pixel value. Under this assumption, the original clean value can be recovered by learning the parameters of the random distribution. However, such an idea cannot be directly extended to point clouds because there are multiple formats of noise in point clouds, such as a global position deviation where no reliable reference point exists. Total Denoising introduces a spatial prior term that finds the closest of all possible modes on a manifold. The model achieves competitive performance against supervised models.\par While a lot of models benefit from rich information in dense point clouds, some others are suffering from the low efficiency with large amounts of points. Conventional downsampling approaches usually have to risk dropping critical points. Nezhadarya et al. \cite{Nezhadarya_2020_CVPR} proposed the critical points layer (CPL) that learns to reduce the number of points while preserving the important ones. The layer is deterministic, order-agnostic and also efficient by avoiding neighbor search. Aside from that, SampleNet \cite{Lang_sample_2020_CVPR} proposed a differentiable relaxation of point sampling by approximating points after sampling as a mixture of original points. The method has been tested as a front to networks on various tasks, and obtains decent performance with only a small fraction of the raw input point cloud. \par \subsection{Generative Methods} Generative adversarial networks are widely studied for 2D images and CNNs, as they help locate the potential defects of networks by generating false samples. While typical applications of point cloud models, such as autonomous driving, consider safety as a critical concern, it is helpful to study how current deep neural networks on point clouds are affected by false samples.\par Xiang et al. \cite{xiang2019generating} proposed several algorithms to generate adversarial point clouds against PointNet. The adversarial algorithms work in two ways: point perturbation and point generation. Perturbation is implemented by shifting existing points negligibly, and generation is implemented by either adding some independent and scattered points or a small number of point clusters with predefined shapes. Shu et al. \cite{shu20193d} proposed tree-GAN, a tree-structured graph convolution network. By performing graph convolution within a tree, the model takes advantage of ancestor information to enrich the capacity of features. Along with the development of adversarial networks, DUP-Net \cite{zhou2019dup} is proposed to defend 3D adversarial models. The model contains a statistical outlier removal (SOR) module as denoiser and a data-driven upsampling network as upsampler. \par Aside from adversarial generation, generative models are also used for point cloud upsampling. There are generally two motivations to upsample a point cloud. The first is to reduce the sparseness and irregularity of data, and the second is to restore missing points due to occlusion. \par For the first aim, PU-Net \cite{yu2018pu} proposed upsampling in the feature space. For each point, multi-level features are extracted and expanded via a multi-branch convolution unit; after that, the expanded feature is split into multiple features and reconstructed to upsample the input set. Inspired by image super-resolution models, Wang et al. \cite{yifan2019patch} proposed a cascade of patch-based upsampling networks, learning different levels of details at different steps, where at each step the network focuses only on a local patch from the output of the previous step. The architecture is able to upsample a sparse input point set to a dense set with rich details. Hui et al. \cite{hui2020progressive} also proposed a learning-based deconvolution network that generates multi-resolution point clouds based on low-resolution input with bilateral interpolation performed in both the spatial and feature spaces.\par Meanwhile, early methods in completion, such as \cite{dai2017shape}, tend to voxelize the input point cloud at the very beginning. PCN \cite{yuan2018pcn} was the first framework to work on raw point clouds and in a coarse-to-fine fashion. Wang et al. \cite{Wang_Comp_2020_CVPR} improved the results with a two-step reconstruction design. Besides, Huang et al. \cite{Huang_PF_2020_CVPR} proposed PF-Net that preserves the spatial structure of the original incomplete point cloud, and predicts the missing points hierarchically a multi-scale generating network. GRNet\cite{xie2020grnet}, on the other hand, proposed a gridding-based which retrieve structural context by performing cubic feature sampling per grid, and complete the output with "Gridding Reverse" layers and MLPs. \par Lan et al. \cite{lan2019robust} proposed a probabilistic approach to optimize outliers by applying EM algorithm with Cauchy-Uniform mixture model to suppress potential outliers. More generally, PU-GAN \cite{li2019pu} proposed a data-driven generative adversarial network to learn point distributions from the data and upsample points over patches on the surfaces of objects. Furthermore, RL-GAN-Net \cite{sarmad2019rl} uses a reinforcement learning (RL) agent to provide fast and reliable control of a generative adversarial network. By first training the GAN on the dimension-reduced latent space representation, and then finding the correct input to generate the representation that fits the current input form the uncompleted point cloud with a RL agent, the framework is able to convert noisy, partial point cloud into a completed shape in real time.\par \section{Conclusion} In this paper, we reviewed milestones and recent progress on various problems in 3D point clouds. With the expectation of practical applications like autonomous driving, point cloud understanding has received increasing attention lately. In 3D shape classification, point-based models have achieved satisfactory performance on recognized benchmarks. Methods developed from image tasks, such as two-stage detector and the Siamese architecture, are widely introduced in 3D segmentation, object detection and other derivative tasks. Specific deep learning frameworks are proposed to match point clouds of the same scene from multiple scans, and generative networks are adapted to improve the quality of point cloud data with noise and missing points. Deep learning methods with proper adaption have been proven to efficiently help overcome the unique challenges in point cloud data. \par {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-09-21T02:17:08', 'yymm': '2009', 'arxiv_id': '2009.08920', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08920'}
arxiv
\section{Introduction} \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{img.pdf} \caption{\label{figure:simexample} Examples of two generated similes GenSimile1 and GenSimile2 from their literal inputs.} \vspace{-1em} \end{figure} Comparisons are inherent linguistic devices that express the likeness of two entities, concepts or ideas. When used in a figurative sense, these comparisons are called similes. They are a figure of speech that compare two different kind of things, usually with the intent to make the description more emphatic or vivid, being often used in literature and poetry to spark the reader's imagination ~\cite{definition}. Take the following two examples: ``The city was \textit{like a painting}", and ``If it falls into the wrong hands it would be as catastrophic \textit{as a nuclear bomb}." In the first example, the comparison draws on the implicit ``beauty" property being shared by the two very different entities, \textit{city} and \textit{painting}, while in the second the ``catastrophic" property is shared by \textit{falling into the wrong hands} and \textit{nuclear bomb}. While most computational work has focused on simile detection \cite{simile1,simile2,simile3,simile4,simile5,simile6}, research on simile generation is under-explored. Generating similes could impact many downstream applications such as creative writing assistance, and literary or poetic content creation. To tackle the generation problem, we take advantage of the relatively simple structure of similes that consists of five elements \cite{hanks2013lexical,simile1}: the {\tt TOPIC} (usually a noun phrase that acts as logical subject), the {\tt VEHICLE} (the logical object of the comparison, usually a noun phrase), the {\tt PROPERTY} (what the two things being compared have in common, usually an adjective), the {\tt EVENT} (eventuality or state, usually a verb), and the {\tt COMPARATOR} (the trigger word or phrase that marks the presence of a comparison, usually the preposition ``like" or ``as...as"). All elements of a simile are explicit, with the exception of {\tt PROPERTY}, which can be both implicit and explicit. If we take the first example above, its structure is: ``[The city/{\tt TOPIC}] [was/{\tt EVENT}] [like/{\tt COMPARATOR}] [a painting/{\tt VEHICLE}]" ({\tt PROPERTY} is implicit). Unlike metaphors, the semantic context of similes tends to be very shallow, transferring a single \textit{property} \cite{hanks2013lexical}. Moreover, the explicit syntactic structure of similes allows, in exchange, for more lexical creativity~\cite{simile1}. We focus on the task of generating a simile starting from a literal utterance that contains the {\tt TOPIC}, {\tt EVENT} and {\tt PROPERTY}. We frame this task as a style-transfer problem \cite{shen2017style,fu2017style,li2018delete}, where the author's intent is to make the description of the {\tt TOPIC} more emphatic by introducing a comparison with the {\tt VEHICLE} via a shared {\tt PROPERTY} (See Figure~\ref{figure:simexample} for example of literal descriptive sentences and the generated similes). We call our approach \textbf{SCOPE} (\textbf{S}tyle transfer through \textbf{CO}mmonsense \textbf{P}rop\textbf{E}rty). There are two main challenges we need to address: 1) the lack of training data that consists of pairs of literal utterances and their equivalent simile in order to train a supervised model; 2) ensuring that the generated simile makes a meaningful comparison between the {\tt TOPIC} and the {\tt VEHICLE} via the shared {\tt PROPERTY} explicitly or implicitly expressed (e.g., Figure \ref{figure:simexample} GenSimile1 and GenSimile2, respectively). To the best of our knowledge, this is the first work in attempting to generate similes. By framing the task as a style-transfer problem we make three contributions: \footnote{ Code \& Data at \url{https://github.com/tuhinjubcse/SimileGeneration-EMNLP2020}} \textbf{Automatic creation of a parallel corpus of \textit{[literal sentence, simile]} pairs}. Our constructed corpus contains 87,843 such pairs. As a first step, we use distant supervision to automatically collect a set of \emph{self-labeled similes} using the phrase \textit{like a}. We then convert these similes to their literal versions by removing the {\tt COMPARATOR} and replacing the {\tt VEHICLE} with the associated {\tt PROPERTY} by leveraging the structured common sense knowledge achieved from COMET \cite{comet}, a language model fine-tuned on ConceptNet \cite{conceptnet}. For example, for the simile ``Love is like a unicorn" our method will generate ``Love is rare" (Section \ref{section:data1}). \textbf{Transfer learning from a pre-trained model for generating high quality similes.} Our system \textbf{SCOPE}, \emph{fine-tunes} BART \cite{lewis2019bart} --- a state of the art pre-trained denoising autoencoder built with a sequence to sequence model, on our \emph{automatically collected parallel corpus} of \textit{[literal sentence, simile]} pairs (Section \ref{section:model}) to generate similes. Human evaluations show that this approach generates similes that are better 37\% of the time on average compared to 2 literary experts, 82\% and 63\% of times compared to two well crafted baselines, and 68\% of the times compared to a state of the art system for metaphor generation \cite{metagen2} (Section \ref{section:results}). \textbf{A task-based evaluation.} We show the effectiveness of the generated similes as a tool for enhancing creativity and evocativeness in machine generated stories. Evaluation via Amazon Mechanical Turk shows that stories containing similes generated by \textbf{SCOPE} is preferred by Turkers 42\% of the times compared to stories without similes, which is preferred 25\% of the times (Section \ref{section:story}). \section{Related Work} Simile generation is a relatively new task. Most prior work has focused on detection of similes. The closest task in NLP to simile generation is generating metaphors. However it should be noted the overlap between the expressive range of similes and metaphors is known to be only partial: there are similes that cannot be rephrased as metaphors, similarly the other way around~\cite{israel2004simile}. \subsection{Simile Detection and Analysis} \citet{simile1} proposed frameworks for annotating similes from product reviews by considering their semantic and syntactic characteristics as well as the challenges inherent to the automatic detection of similes. \citet{simile3,simile4} built computational models to recognize affective polarity and implicit properties in similes. Unlike these works, we focus on generating similes by transforming a literal sentence while still being faithful to the property in context. \subsection{Metaphor Generation} Earlier works in metaphor generation \cite{abe2006computational,terai2010computational} were conducted on a lexical or phrase level, using template and heuristic-based methods. \cite{metaphoria} presented an interactive system for collaboratively writing metaphors with a computer. They use an open source knowledge graph and a modified Word Mover’s Distance algorithm to find a large, ranked list of suggested metaphorical connections. Word embedding approaches \cite{gagliano2016intersecting} have also been used for metaphor generation. However, the metaphors generated through these methods do not take semantic context into consideration and lack the flexibility and creativity necessary to instantiate similes through a natural language sentence. \citet{metagen1} use neural models to generate metaphoric expressions given a literal input in an unsupervised manner. \citet{metagen2} develop a new framework dubbed `metaphor masking' where they train a supervised seq2seq model with input as the masked text, where they mask or hide the metaphorical verb while preserving the original text as the output. However, both these works hinge on metaphoric verbs unlike similes where we not only need to replace the literal property with a vehicle but it also needs to be relevant to the context and the tenor. Additionally we also use \cite{metagen2} as a baseline and show that their approach may not be the best way for generating similes. \section{Conclusion} We establish a new task for NLG: simile generation from literal sentences. We propose a novel way of creating parallel corpora and a transfer-learning approach for generating similes. Human and automatic evaluations show that our best model is successful at generating similes. Our experimental results further show that to truly be able to generate similes based on actual metaphoric or conceptual mappings, it is important to incorporate some common sense knowledge about the topics and their properties. Future directions include exploration of other knowledge bases to help the inference and applying our simile generation approach to different creative NLG tasks. \section{Problem Statement} \section{SCOPE: {S}tyle Transfer through \textbf{CO}mmonsense \textbf{P}rop\textbf{E}rty} \begin{figure*}[ht] \centering \includegraphics[width=\textwidth]{schematic.pdf} \vspace{-1.5em} \caption{\label{figure:sim} A schematic illustration of our system, where the top block shows our \textbf{training} process where we use COMET to transform similes to literal sentences and use them to fine-tune BART. The block below shows the \textbf{inference} step where we use fine-tuned BART to generate novel similes conditioned on a literal sentence.} \vspace{-.5em} \end{figure*} Our style transfer approach for simile generation from literal descriptive sentences has two steps: 1) first convert self-labeled similes into literal sentences using structured common sense knowledge (Section \ref{section:data1}); and 2) given the \textit{[literal sentence, simile]} pairs, fine-tune a seq2seq model on these pairs to generate a simile given a literal sentence (Section \ref{section:model}). This two-step approach is shown in the upper half of Figure \ref{figure:sim}. \subsection{Automatic Parallel Corpus Creation} \label{section:data1} One of the requirements to train a supervised generative model for text style transfer is the presence of a large-scale parallel corpus. We use distant supervision to collect self-labeled similes using the phrase \textit{like a} \footnote{While there can be noisy sentences where the TOPIC is a PNP and typically short $<=6$ tokens such as \textit{I feel like a .., I would like a .., I don't like a..}, they are very less in number(1.1 \%) so we do not remove them. More details in Appendix A.2} from Reddit (e.g., the rows labeled as Simile in Table \ref{table:example2}). For fine-tuning, the similes form the ``target" side of our parallel data. For the ``source" side of our parallel data, we use commonsense knowledge to transform the similes to their literal version (e.g., the rows labeled as Best Literal in Table \ref{table:example2}). One of the possible ways to collect similes would be to train a supervised model using existing data and methods for simile detection but most data sets are very small in size (in order of a few hundred). The only large-scale dataset is that of \cite{simile1} however their data is from a rather restricted domain of product reviews on Amazon which might often lack variety, diversity and creativity needed for this task. \paragraph{Simile Dataset Collection.} We hypothesize that similes are used frequently in creative writing or humorous content on social media \cite{veale2013humorous}. Hence, we obtain training data by scraping the subreddits WRITINGPROMPTS \footnote{\url{https://www.reddit.com/r/WritingPrompts/}} and FUNNY \footnote{\url{https://www.reddit.com/r/funny/}} from social media site Reddit for comments containing the phrase \textit{like a}. We use the API provided by pushshift.io \footnote{\url{https://pushshift.io/}} to mine comments. Through this process we collect 87,843 self-labeled human written similes, from which we use 82,697 samples for training and 5,146 for validation. \paragraph{Simile to Literal Transformation via Commonsense Property.} From a theoretical perspective, similes are created by making a comparison between the {\tt TOPIC} and the {\tt VEHICLE} through a shared {\tt PROPERTY}. While this property is naturally known to humans through common sense and connotative knowledge, computers still struggle to perform well on such tasks when the {\tt PROPERTY} is not expressed. Hence we use structured common sense knowledge to derive properties to transform similes to their literal versions. \begin{table}[t] \centering \small \begin{tabular}{|@{ }l@{ }|@{ }p{5.5cm}@{ }|} \hline Simile & Love is like a \textit{unicorn.} \\ \hline Has property & very rare, rare, beautiful, beautiful and smart, color \\ \hline Best Literal & Love is \textit{\color{blue}rare.} \\ \hline\hline Simile & It was cool and quiet, and I stormed through like a \textit{charging bull.} \\ \hline Has property & big and strong, dangerous, big, fast, large \\ \hline Best Literal & It was cool and quiet, and I stormed through \textit{\color{blue}fast.} \\ \hline\hline Simile & Sir Francis's voice was calm and quiet, like a \textit{breeze through a forest.} \\ \hline Has property & very relax, soothe, cool, beautiful, relax \\ \hline Best Literal & Sir Francis's voice was calm and quiet, \textit{\color{blue}very relaxed.} \\ \hline \end{tabular} \caption{Examples of self-labeled similes collected from Reddit. For each example, we show the top five commonsense properties associated with the \textit{vehicle} obtained from COMET, and the best literal sentence constructed from these properties. The blue italic texts in the literal sentences represent the \textit{property} inferred from the \textit{vehicle} in the simile (denoted in black italic). } \vspace{-1em} \label{table:example2} \end{table} To generate the common sense {\tt PROPERTY} that is implied by the {\tt VEHICLE} in the simile, we take advantage of the simple syntactic structure of a simile. We extract the {\tt VEHICLE} by extracting the phrase after \textit{like a} and feed it as input to COMET \cite{comet}. COMET is an adaptation framework for constructing commonsense knowledge based on pre-trained language models. Our work only leverages the \textbf{HasProperty} relation from COMET \footnote{\url{https://mosaickg.apps.allenai.org/comet\_conceptnet}}. For a given simile \textit{`Love is like a unicorn.'}, the {\tt TOPIC} \textit{Love} is compared to the {\tt VEHICLE} \textit{unicorn}. As shown in Table \ref{table:example2}, COMET tells us the top 5 properties associated with the {\tt VEHICLE} are \textit{very rare, rare, beautiful, beautiful and smart, color}. COMET gives us the properties sorted by probability in isolation by just relying on the {\tt VEHICLE}. While in most situations all of the properties are apt, we need to make the literal sentence as meaningful as possible. To do this, we append the common sense property to the portion of the simile before \textit{`like a'}. This typically consists of the {\tt TOPIC}, the {\tt EVENT}, and a {\tt PROPERTY} if stated explicitly. We take the top 5 properties from COMET to form 5 possible literal versions for a particular simile. To rank these literal versions and select the best one, we rely on perplexity scores obtained from a pre-trained language model GPT \cite{gpt}. Table \ref{table:example2} shows human written similes collected from Reddit, the top 5 common sense properties associated with the {\tt VEHICLE}, and the literal version created by taking the best {\tt PROPERTY}. To correct any grammatical error introduced by this manipulation, we rely on a grammatical error correction model \cite{zhao2019improving}. \paragraph{Test Data Collection.} \label{section:evaldata} Our task is to generate a simile given a literal input. The automatically-generated parallel data might contain stylistic biases. To truly measure the effectiveness of our approach, we need to evaluate on a dataset independent of our training and validation data. Towards this end, we again scrape WRITINGPROMPTS subreddits for sentences which are this time \emph{literal} in nature (without any comparators \textit{like, as}). Since literal utterances contains the description of {\tt TOPIC} via a {\tt PROPERTY} and usually the {\tt PROPERTY} is an adjective or adverb, we restrict the last word of our literal sentences to adverbs or adjectives. We crawl 500 such sentences and randomly sample 150 literal utterance. We used two literary experts, a student in creative writing, and a student in comparative literature who is the author of a novel, to write corresponding similes for each of these 150 inputs for evaluation and comparison. \subsection{Seq2Seq Model for Simile Generation} \label{section:model} Our goal of generating similes can be broken down into two primary tasks: 1) identifying the words in the literal sentence that should be removed or replaced and 2) generating the appropriate substitutions while being pertinent to the context. Sequence to sequence (seq2seq) neural network models \cite{sutskever2014sequence} have demonstrated great success in many text generation tasks, such as machine translation, dialog system and image caption, with the requirement of a considerable amount of parallel data. Hence we use seq2seq models for simile generation. \begin{figure}[t] \centering \includegraphics[scale=0.75]{bart.pdf} \caption{\label{figure:bart} The backbone of SCOPE: fine-tuning BART on literal to simile pairs.} \vspace{-1em} \end{figure} BART \cite{lewis2019bart} is a pre-trained model combining bidirectional and auto-regressive transformers. It is implemented as a sequence-to-sequence model with a bidirectional encoder over corrupted text and a left-to-right autoregressive decoder. In principle, the pre-training procedure has two stages: (1) text is corrupted with an arbitrary noising function, and (2) a transformer-to-transformer model is learned to reconstruct the original text. Because BART has an autoregressive decoder, it can be directly fine-tuned for most sequence generation tasks. Here, the encoder input is the a sequence of words, and the decoder generates outputs autoregressively, as shown in Figure \ref{figure:bart}. BART achieves new state-of-the art results on a number of text generation tasks, making it an ideal choice for generating similes. We refer the reader to \cite{lewis2019bart} for further details. For our task, we fine-tune BART by treating the literal input as encoder source and the simile as the the decoder target. Post fine-tuning at the inference step, we use top-k sampling strategy \cite{fan2018hierarchical} to generate similes conditioned on a test literal input. \paragraph{Implementation details.} Hyper-parameters, and essential details needed for satisfiability of reproducibility checklists are given in Appendix A.1. \section{Model} \section{Experimental Setup} To compare the quality of the generated similes, we benchmark SCOPE model and human generations (HUMAN1 \& HUMAN2) described in Section \ref{section:evaldata} with three baseline systems described below \subsection{Baseline Systems} Simile generation is a new task. The baselines outlined below have been used for other generation tasks. We adapt them to generate similes. \begin{enumerate} \item \textbf{BART}: This is the pre-trained BART model. Since BART is a pre-trained sequence to sequence model, it can still be used for conditional text generation. To this end we use the same literal sentence (For example \textit{The city was beautiful}) as an input to the encoder and force the decoder to begin with same prefix by removing the adjective/adverb at the end and appending the comparator and the article (\textit{The city was like a}) and generate a simile. \item \textbf{Retrieval (RTRVL)}: We also experiment with a retrieval approach where we retrieve a {\tt VEHICLE} from ConceptNet \cite{conceptnet} having the highest \textit{HasProperty} relation w.r.t our input (i.e., an adjective or adverb at the end of literal sentence) \footnote{ConceptNet is a weighted graph with multiple relations as can be viewed here http://conceptnet.io/ . We use `has property" for our work.There are multiple edges for objects with their properties. We choose edge with highest weight}. For the input \textit{The city was beautiful} we query ConceptNet with \textit{beautiful} and it returns \textit{sunset} as the {\tt VEHICLE} having highest weight for \textit{HasProperty beautiful}. We take this retrieved {\tt VEHICLE} and append it to the prefix ending in \textit{like a}. If the word is not in ConceptNet, we fall back to its synonyms obtained from Wordnet \cite{miller1995wordnet}. \item \textbf{Metaphor Masking (META\_M)}: The third baseline is the metaphor generation model given a literal sentence described by \newcite{metagen2}. Following their approach, we fine-tune BART where we mask the adjective or adverb in the end of the literal sentence. The input is the masked text, with the hidden adjective or adverb (\textit{The city was \textbf{\textless MASK \textgreater}}), and the output is the original simile (\textit{The city was like a painting}). Through this learning paradigm, the model learns that it needs to generate simile when it encounters the mask token. At test time, we provide the model with the literal input, mask the adjective/adverb, and the model produces an output conditioned on the adjective/adverb masking training. \end{enumerate} \subsection{Evaluation Criteria} \paragraph{Automatic evaluation.} \textit{BLEU}~\cite{BLEU} is one of the most widely used automatic evaluation metric for generation tasks such as Machine Translation. However, for creative text generation, it is not ideal to expect significant n-gram overlaps between the machine-generated and the gold-standard sentences. We still report the BLEU scores for generated {\tt VEHICLE} after discarding the common prefix with the gold. \textit{BERTScore}~\cite{zhang2019bertscore} has been used recently for evaluating text generation using contextualized embeddings and said to somewhat ameliorate the problems with BLEU. It computes a similarity score using contextual embeddings for each token in the candidate (here {\tt VEHICLE} in generated simile) with each token in the reference ({\tt VEHICLE} in human written simile).To compute F1-Score it uses Recall (matching each token in reference to a token in candidate) and Precision(matching each token in candidate to a token in reference).We report F1Score of \textit{BERTScore.} \textit{Novelty.} To measure the model's generalization capability, we also want to test how well our models can generate novel content. We capture the proportion of generated {\tt VEHICLE} conditioned on an adverb/adjective literal {\tt PROPERTY} that does not appears in the training set. \begin{table}[] \small \centering \begin{tabular}{|l|l|l|l|l|} \hline & \bf B-1 & \bf B-2 & \bf BERT-S & \bf NOVELTY \\ \hline RTRVL & 0.0 & 0.0 & 0.13 & 92.6 \\ \hline BART & 3.25 & 0.32 & 0.12 & 92.6 \\ \hline META\_M & 3.73 & 0.96 & 0.15 & \textbf{93.3} \\ \hline SCOPE & \textbf{8.03} & \textbf{3.59} & \textbf{0.18} & 88.6 \\ \hline \end{tabular} \caption{Results using automatic metrics: BLEU-1 (B-1), BLEU-2 (B-2), BERTScores (BERT-S) and Novelty. Boldface denotes the best results.} \label{table:autoeval} \end{table} \begin{table}[] \small \centering \begin{tabular}{|@{ }l@{ }|@{ }l@{}|@{ }l@{}|@{ }l@{}|@{ }l@{ }|} \hline \bf System & \bf C & \bf R1 & \bf R2 & \bf OQ \\ \hline HUMAN1 & \textbf{3.61} (0.34) & \textbf{3.74} (0.43) & 3.90 (0.51) & \textbf{3.54} (0.40) \\ \hline HUMAN2 & 3.46 (0.31) & 3.72 (0.43) & \textbf{3.97} (0.47) & 3.44 (0.39) \\ \hline\hline RTRVL & 1.90 (0.39) & 1.85 (0.44) & 1.73 (0.50) & 1.85 (0.42) \\ \hline BART & 2.68 (0.39) & 2.78 (0.45) & 2.75 (0.51) & 2.61 (0.41) \\ \hline META\_M & 2.68 (0.42) & 2.72 (0.46) & 2.77 (0.47) & 2.59 (0.41) \\ \hline SCOPE & \underline{3.16} (0.35) & \underline{3.50} (0.43) & \underline{3.78} (0.52) & \underline{3.32} (0.43) \\ \hline \end{tabular} \caption{Human evaluation on several criteria of similes' quality for different systems' outputs and human written similes. We show average scores on a 1-5 scale with 1 denotes the worst and 5 be the best; the corresponding inter-annotator agreement (IAA) is in the parenthesis. Boldface denotes the best results and underscore denotes the second bests.} \label{table:example3} \end{table} \begin{table}[t] \small \centering \begin{tabular}{|p{0.3cm}|l|l|l|l|l|l|} \hline \multirow{2}{*}{} & \multicolumn{2}{l|}{\bf SCOPE/H1} & \multicolumn{2}{l|}{\bf SCOPE/H2} & \multicolumn{2}{l|}{\bf SCOPE/META\_M} \\ \cline{2-7} & w\% & l\% & w\% & l\% & w\% & l\% \\ \hline C & 28.0 & \textbf{58.6} & 26.6 & \textbf{57.3} & \textbf{58.6} & 31.3 \\ \hline R1 & 37.3 & \textbf{51.3} & 33.3 & \textbf{50.0} & \textbf{63.3} & 18.0 \\ \hline R2 & 42.6 & \textbf{45.3} & 37.3 & \textbf{44.6} & \textbf{69.3} & 17.3 \\ \hline OQ & 32.6 & \textbf{54.6} & 41.3 & \textbf{50.0} & \textbf{68.6} & 18.6 \\ \hline \end{tabular} \caption{Pairwise comparison between SCOPE and HUMAN1(H1), HUMAN2(H2), and META\_M. Win[w]\% (lose[l]\%) is the percentage of SCOPE gets a higher (lower) average score compared to HUMAN1, HUMAN2 and META\_M. The rest are ties.} \label{table:example4} \end{table} \paragraph{Human evaluation.} Automated metrics are not adequate on their own for evaluating methods to generate creative text so we present a human-based evaluation as well. We evaluate on a total of 900 utterances, 600 generated from 4 systems and 300 utterances generated by humans. We proposed a set of 4 criteria to evaluate the generated output: (1) \textit{Creativity (C)} (``How creative are the utterances?''), (2) \textit{Overall Quality (OQ)} (``How good is the simile overall?'' \footnote{Turk guidelines was to score based on how creative, well formed, meaningful and relevant it is with respect to the literal utterance}), (3) \textit{Relevance1 (R1)} (``How relevant is the generated {\tt VEHICLE} in terms of portraying the {\tt PROPERTY}?'') and (4) \textit{Relevance2 (R2)} (``How relevant is the {\tt VEHICLE} to the {\tt TOPIC} in the generation?''). As we evaluate on 4 separate dimensions for 900 utterances we have a total of 3600 evaluations. We hired Turkers on MTurk to rate outputs from the 4 systems and 2 humans. Each Turker was given the literal utterance as well as the 6 generate similes (randomly shuffled) Each criteria was rated on a scale from 1 (not at all) to 5 (very). Each utterance was rated by three separate Turkers. We hired 86,48,42,46 Turkers for the tasks of Creativity, Overall Quality, Relevance1, Relevance2 respectively. Further details in Appendix A.4 . \section{Experimental Results} \label{section:results} \subsection{Automatic Evaluation} Table \ref{table:autoeval} shows BLEU-1, BLEU-2 and BERTScore of our system compared to the three baselines. The low scores can be attributed to the nature of creative NLG tasks. To further validate this we also compute the BLEU-1 and BLEU-2 score between the two literary experts treating one as reference and other as candidate and get scores of $4.12$ and $0.52$ respectively. BERTScore is often a better metric as it utilizes contextualized embeddings. For example for a candidate [\textbf{desert}] with multi-reference as [[\textbf{sandy death trap}],[\textbf{wasteland}]] , we get a BERTscore of 0.99 while BLEU score is 0.0. Finally our best model SCOPE emerges as the winner for both BLEU and BERTScore. For novelty SCOPE can still generate novel content 88\% of the time proving it is generalizable to unseen test data. Further there are 5558 unique {\tt PROPERTY} in training data and 41\% of {\tt PROPERTY} in testing data does not appear in training, showing our model is generalizable on unseen {\tt PROPERTY} as well. \subsection{Human Evaluation Scores} Table ~\ref{table:example3} presents the scores of the aforementioned evaluation criteria for our model and the baselines on the test set. The results show that SCOPE is significantly ($p<.001$ according to approximate randomization test) better than the baselines on all four criteria. For all metrics our best system is comparable to humans. We also computed Pearson's correlation between OQ with other metrics and observed that R1 and R2 had moderate correlation of 0.54 and 0.52 with OQ , while C was fairly correlated (0.31) to OQ suggesting a relevance matters when deciding the quality of a simile. \paragraph{Pairwise Comparison between systems.} Table \ref{table:example4} shows the pairwise comparisons between the SCOPE and human generated simile (HUMAN1 and HUMAN2), and META\_M \cite{metagen2}, respectively. Given a pair of inputs, we decide win/lose/tie by comparing the average scores (over three Turkers) of both outputs. We see that SCOPE outperforms META\_M on all the metrics. For overall quality, although it is a given that literary experts are better, the SCOPE model still has a winning rate of 32.6\% and 41.3\% respectively. \begin{figure} \centering \includegraphics[scale=0.17]{bar-chart.png} \caption{\label{figure:cn} Barchart showing the percent of times each individual system won in terms of Overall Quality.} \end{figure} \section{Qualitative Analysis} Table \ref{table:example5} demonstrates several generation outputs from different systems along with human judgements on individual criteria. We observe that often our model is better than at least one human on a certain criteria while outperforming the baselines by a large margin. \subsection{Role of Relevance} While conditioning on the context of literal sentences might lead to grammatically correct similes, they are often not meaningful and relevant to the {\tt PROPERTY} in consideration. META\_M generates similes by fine-tuning BART on literal sentences where the common sense {\tt PROPERTY} is masked. The lack of relevance mapping during fine-tuning often leads to improper generations. For instance, referring to Table \ref{table:example5}, the context of `falling into the wrong hands' is more likely to lead to something bad and hence here `gift' is not appropriate while `nuclear bomb' is. One possible way of incorporating relevance is through common sense knowledge. \subsection{Role of Context} The role of context is necessary for simile generation. For example given the literal input \textit{`But times are hard, and silver bullets are \textbf{expensive}'} even though ConceptNet tells us \textbf{diamonds} are objects with \textit{HasProperty} expensive, a generated simile by RTRVL model \textit{`But times are hard, and silver bullets are like a \textbf{diamond}'} seems inappropriate suggesting that a context leads to better generation. Our SCOPE model generates \textit{`But times are hard, and silver bullets are like a \textbf{luxury item}'} \section{Task-based Evaluation: Simile for Story Generation} \label{section:story} Similes are often used to evoke imagery. Generating or transforming text to be evocative can be useful for journalism, poetry and story writing. Table \ref{table:example7} shows how we can use our simile generation module as a post processing step to replace literal sentences leading to more expressive and creative stories. To further test this hypothesis we conduct an experiment further outlined below. \begin{table}[] \small \centering \begin{tabular}{|c|c|c|} \hline GPT2 & GPT2+META\_M & GPT2+SCOPE \\ \hline 23\% & 25\% & \textbf{42\% } \\ \hline \end{tabular} \caption{\label{tab:analysis}Win\% (in terms of average score over three annotators) of stories generated with only GPT2, GPT2 with META\_M or SCOPE simile post processing. The rest are ties.} \end{table} \subsection{Story Generation} We use the ROCStories \cite{mostafazadeh2016corpus} dataset to generate stories using the \textit{Plan and Write } model outlined by \citet{yao2019plan}. We introduce a two step pipeline procedure where we fine-tune a pre-trained GPT2 \cite{gpt} model on titles and storyline from the training set to generate a storyline given a title (Row 1 Table \ref{table:story}). In parallel, we also fine-tune GPT2 on storylines and stories from the training set to generate a story given a storyline (Row 2 Table \ref{table:story}). At test time, we generate a storyline using an input title first and then use the generated storyline to generate a story. \subsection{Post Processing} There can be multiple sentences ending with an adjective or adverb and replacing each of them with a simile might lead to over-embellishment. Under such situations we feed only one randomly selected sentence to SCOPE and META\_M module and replace the sentence in GPT2 generated story with the output from SCOPE or META\_M, respectively. \subsection{Human evaluation.} We randomly select 50 titles from ROCStories data set and generate stories as described above. We postprocess it using both SCOPE and META\_M separately. Thus for each title we have 3 stories 1) the original GPT2 story 2)the GPT2 story postprocessed with SCOPE 3)the GPT2 story postprocessed with META\_M. For each given titles, we present these 3 stories each to workers in AMT and ask them to score them in a range of 1(poor) to 5 (excellent) based on creativity and evocativeness. Experimental results from Table \ref{tab:analysis} prove that effective usage of similes can improve evocativeness and reception of machine generated stories. \section*{Acknowledgments} This work was supported by the CwC program under Contract W911NF-15-1-0543 with the US Defense Advanced Research Projects Agency (DARPA). The views expressed are those of the authors and do not reflect the official policy or position of the Department of Defense or the U.S. Government. The authors would like to thank Kai-Wei Chang, Christopher Hidey, Christopher Robert Kedzie, Anusha Bala and Liunian Harold Li for useful discussions. The authors also thank members of PLUSLab at the University Of California Los Angeles and University Of Southern California and the anonymous reviewers for helpful comments.
{'timestamp': '2020-09-21T02:17:55', 'yymm': '2009', 'arxiv_id': '2009.08942', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08942'}
arxiv
\section{Analysis}\label{sec:simulation} To study the implications of a PGPP deployment, we create a simulation to model users, mobility, and cell infrastructure. We study the impact of PGPP's design on various cellular attacks that occur today. We then analyze the inherent tradeoffs from the PGPP operator's perspective, as improved privacy comes at the price of increased control traffic. Lastly, we examine PGPP in a lab testbed on real devices. \subsection{Simulation configuration} \textit{\acrshort{enb} dataset.} We select Los Angeles County, California as the region for our simulation, which provides a mix of both highly urban areas as well as rural areas. For \acrshort{enb} location information, we use OpenCellID~\cite{opencellid}, an open database that includes tower locations and carrier information. To simplify the simulation, we select \acrshort{enb}s from the database that are listed as providing LTE from AT\&T, the provider with the most \acrshort{enb}s (22,437) in the region. Given their geographic coordinates, we estimate coverage areas for every \acrshort{enb} using a Voronoi diagram. During the simulation, a \acrshort{ue} is assigned to the \acrshort{enb} that corresponds to the region the \acrshort{ue} is located within. While such discretization is not likely in reality as \acrshort{ue}s remain associated with an \acrshort{enb} based on received signal strength, this technique provides us with a tractable mobility simulation. A partial map of the simulation region is shown in Figure~\ref{fig:map}. ENodeB regions are shaded based on the tracking area value in the OpenCellID database. \begin{figure}[t] \centering \includegraphics[width=.85\columnwidth]{images/LAMap5.pdf} \caption{Partial simulation map. Cells are shaded by AT\&T LTE tracking area.} \label{fig:map} \end{figure} \begin{figure}[t] \centering \includegraphics[width=.75\columnwidth]{images/userseNBCDF_box.pdf} \caption{ENodeBs visited by simulated mobile users.} \label{fig:usereNodeBs} \end{figure} \textit{Mobility traces.} To simulate realistic mobility patterns ({\it i.e.}, users must follow available paths), we generate mobility traces using the Google Places~\cite{placesapi} and Directions~\cite{directionsapi} APIs. First, we use the Places API to find locations in the simulation region that are available when searching for ``post office.'' Each place is associated with latitudinal and longitudinal coordinates. We then generate mobility traces by randomly selecting start and end points, and use the Directions API to obtain a polyline with coordinates along with estimated times to reach points along the line. We generate 50,000 mobility traces: 25,000 cars and 25,000 pedestrians. We then use ns-3 to process the mobility traces and generate coordinates for each trace at 5-second intervals, in a method similar to~\cite{routesmobility}. We use this output, along with the \acrshort{enb} Voronoi diagram to assign each simulated \acrshort{ue} to an \acrshort{enb} for every 5-second interval in the mobility trace. Figure~\ref{fig:usereNodeBs} shows the distribution of the number of \acrshort{enb}s visited by \acrshort{ue}s in the simulation. As expected, car trips result in a significantly higher number of \acrshort{enb}s for a \acrshort{ue} compared with pedestrian trips. \textit{Synthetic traffic.}\label{sec:traffic} We simulate one hour. To create control traffic, at every 5-second interval we randomly select 5\% of the user population to receive a ``call.'' A call results in a paging message that is sent to all \acrshort{enb}s in the \acrshort{ue}'s tracking area. Each paged user enters a 3-minute ``call'' if it is not already in one, at which point further paging messages are suppressed for that user until the call is complete. We run the simulation with PGPP enabled as well as with the conventional infrastructure setup. \textit{Custom \acrshort{ta}s.}\label{sec:customtas} As we detail further in~\cref{sec:control}, large \acrshort{tal}s increase control traffic loads, which lowers the network's user capacity. Therefore, we generate new tracking areas in the underlying network in order to mitigate the control traffic burden. As tracking areas normally consist of groups of adjacent \acrshort{enb}s, we need a method by which we can cluster nearby \acrshort{enb}s into logical groupings. To do so, we use k-means clustering with the \acrshort{enb} geographic coordinates allowing for Euclidean distance to be calculated between \acrshort{enb}s. We generate several underlying tracking area maps, with the number of \acrshort{ta}s ({\it i.e.}, k-means centers) ranging from 25 to 1,000. For comparison, the AT\&T LTE network in the simulation is composed of 113 \acrshort{ta}s. \subsection{Cellular privacy attack analysis}\label{sec:attackanalysis} Given the taxonomy we presented in~\cref{sec:attacks}, we analyze the identity and location privacy benefits of PGPP in the simulated environment. \noindent\textbf{Global-bulk attacks.}\label{sec:globalbulk} By nullifying the value of \acrshort{imsi}s, separating authentication with connectivity, and increasing the broadcast domain for users, we increase user identity privacy even with an adversary that is capable of bulk surveillance over an entire network ({\it e.g.}, operators, governments). \textit{Anonymity analysis} We measure the anonymity of a user when under bulk attacks using \textit{degree of anonymity}~\cite{10.5555/1765299.1765304}. The degree of anonymity value ranges from zero to one, with ideal anonymity being one, meaning the user could be any member of the population with equal probability. In this case, we consider the IMSI value to be the target identity. The size of the anonymity set for a population of $ N $ users will result in a maximum entropy of: \begin{equation} H_{M}= log_{2}(N) \end{equation} The degree of anonymity is determined based on the size of the subset of user identities $ S $ that an attacker could possibly believe the victim to be: \begin{equation} d = \frac{H(X)}{H_{M}} = \frac{log_{2}(S)}{log_{2}(N)} \end{equation} \begin{figure}[t] \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/degree_anon.pdf} \caption{TALs.} \label{fig:talanon} \end{subfigure} \hfill \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/degree_anon_custom.pdf} \caption{Custom TAs.} \label{fig:customanon} \end{subfigure} \caption{Degree of anonymity using TALs and custom TAs.} \vspace{-3mm} \end{figure} Given global visibility into the network, we can reason about the anonymity set using the number of \acrshort{enb}s that a victim could possibly be connected to. This is because a cellular carrier can know the exact base station that a user is connected to once the \acrshort{ue} enters an active state. As a baseline, the anonymity set for traditional cellular is $ \frac{log_{2}(1)}{log_{2}(22,437)} = 0 $, as each \acrshort{imsi} is a unique value. With PGPP, \acrshort{imsi}s are identical, so from the perspective of the carrier, the victim could be connected to any \acrshort{enb} that has at least one PGPP client connected to it. Using our simulated environment we collect, for each paging message, the number of \acrshort{enb}s that had users within their range and use the median value to calculate the degree of anonymity. Figures~\ref{fig:talanon} and~\ref{fig:customanon} show the degree of anonymity using different configurations of \acrshort{tal}s and custom \acrshort{ta}s, respectively. We see that high degrees of anonymity are attainable despite an attacker's global visibility. For instance, with \acrshort{tal}s of length 8, the degree of anonymity is 0.748. \noindent\textbf{Local-bulk attacks.}\label{sec:localbulk} PGPP's use of identical \acrshort{imsi}s reduces the importance of \acrshort{imsi}s, and by extension the usefulness of local bulk attacks on user identity. An attacker that can view traffic at the \acrshort{enb}(s) can gain insight into nearby \acrshort{imsi}s. In traditional cell networks, each user has a globally unique \acrshort{imsi} ($S = 1$), resulting in a degree of anonymity of zero as the victim could only be one user. In our measurement study (\cref{sec:zaatarimeasurement}), we showed that \acrshort{imsi}s are routinely broadcast over cell networks, making an \acrshort{imsi} catcher or SDR attack powerful. The subset $ S $ in PGPP, on the other hand, is the size of the population of PGPP users in a given location, as all \acrshort{imsi} values are identical and a local bulk attacker cannot know the true identity of a single user. To get an idea of $ S $, we can calculate the number of PGPP users connected to each \acrshort{enb} in the simulation. Over the course of the simulation, we find a mean value of 223.09 users connected to each \acrshort{enb} that has users, which results in a degree of anonymity $ \frac{log_{2}(223.09)}{log_{2}(50,000)} = 0.50 $. While this value is somewhat low compared to the ideal value of $ 1 $, it is a drastic improvement over conventional cellular architecture, and is dependent on the overall user population in the network. As more PGPP users exist, the degree of anonymity increases. \noindent\textbf{Local-targeted attacks.}\label{sec:localtargeted} In PGPP, local-targeted attacks to discover a user's location are diminished in two ways: first, \acrshort{imsi}s are no longer a useful ID, so identifying an individual among all users is challenging; and second, we use \acrshort{tal}s to increase the paging broadcast domain for a given \acrshort{ue}. From an attacker's point of view, this broadens the scope of where the target \acrshort{ue} may be located. \begin{figure}[t] \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/areasCDF_new.pdf} \caption{TALs.} \label{fig:areas} \end{subfigure} \hfill \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/areasCustomTAsCDF_new.pdf} \caption{Custom TAs.} \label{fig:areacustom} \end{subfigure} \caption{Area anonymity using TALs and custom TAs.} \vspace{-3mm} \end{figure} In Figure~\ref{fig:areas}, we plot the CDF of geographic areas in which pages are broadcast as we increase \acrshort{tal} lengths using the base map consisting of 113 tracking areas. We calculate the area by generating a bounding box around all \acrshort{enb}s that are included in the broadcast domain. As shown, large \acrshort{tal}s result in drastically higher area anonymity compared with \acrshort{tal}s disabled, particularly considering the number of \acrshort{ue}s that could potentially be located in the larger geographic areas. For instance, the median area for the conventional simulation is 378.09 km\textsuperscript{2} whereas \acrshort{tal} lengths of 8 and 16 result in median areas of 5,876.96 and 9,585.17 km\textsuperscript{2}, respectively. We analyze anonymity with \acrshort{tal}s of length 16 while the underlying map is varied using custom \acrshort{ta}s. Figure~\ref{fig:areacustom} shows our results. We observe that as the number of tracking areas increase, resulting in smaller tracking areas, the area anonymity decreases. However, despite the decrease, the area anonymity remains considerably larger than anonymity with \acrshort{tal}s disabled as \acrshort{tal}s include additional tracking areas. For instance, the median area for the conventional case is 378.09 km\textsuperscript{2} whereas the median area for a base map of 500 tracking areas with \acrshort{tal} 16 is 4891.08 km\textsuperscript{2}, a nearly 13-fold increase from the perspective of a local targeted attacker. \subsection{Impact of PGPP on network capacity}\label{sec:control} From an operational perspective, the privacy benefits delivered by PGPP must coincide with feasibility in terms of control overhead in order for it to be deployable. Control traffic determines network capacity in terms of the number of users that are serviceable in a given area. In this section, we explore control traffic load when using \acrshort{tal}s. \subsubsection{Control overhead with PGPP TALs} We first seek to quantify control message overhead while we leverage tracking area lists to provide location anonymity against local-targeted attacks. Recall from~\cref{sec:tals} that we randomly select additional tracking areas from the simulated coverage area to create \acrshort{tal}s, which increases the broadcast domain for a page. Increased control traffic impacts both \acrshort{enb}s and \acrshort{mme}s, however, from our experience with real cellular networks the control traffic capacity at \acrshort{enb}s is the bottleneck as \acrshort{mme}s have much higher capacity. Thus, we focus on \acrshort{enb} control load. Figure~\ref{fig:control} shows a cumulative distribution function (CDF) for the number of pages broadcast by the simulated \acrshort{enb}s. In the figure, ``Conventional'' corresponds to disabling \acrshort{tal} functionality. As expected, larger \acrshort{tal} lengths result in increased control traffic for \acrshort{enb}s as they are more likely to be included in the paging broadcast domain for a given \acrshort{ue}. \begin{figure} \centering \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/controlCDF_new.pdf} \caption{Control traffic with TALs.} \label{fig:control} \end{subfigure} \hfill \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/userCapacityCDF_new.pdf} \caption{Capacity with TALs.} \label{fig:users} \end{subfigure} \caption{Control traffic and system capacities leveraging PGPP TALs in the simulated environment.} \end{figure} To gain insight into the control limitations of real \acrshort{enb}s, we consider the capabilities of a Huawei BTS3202E \acrshort{enb}~\cite{huawei-enodeb}, which is limited to 750 pages per second. When capacity planning, it is commonplace to budget paging traffic headroom; accordingly, we estimate the maximum paging capacity for an \acrshort{enb} to be 525 pages per second (70\% of the BTS3202E capacity). This value is depicted in the vertical red line in the figure (525 pages $\times$ 3600 seconds = 1,890,000 pages/hour). The simulation allows us to illustrate the user population that could be supported by the network, provided a population with similar mobility and traffic profiles as defined in~\cref{sec:traffic}. Recall that we simulate 50,000 users, both pedestrians and cars. We consider the paging load for the network and select the \acrshort{enb}s with the maximum paging load, the 95th percentile, and the median to estimate the number of users each could theoretically support by taking into account the max page limitation of the BS3202E. Figure~\ref{fig:users} shows the user capacity as \acrshort{tal} lengths are increased. A \acrshort{tal} length of one shows the conventional network, as the \acrshort{tal} is composed of a single tracking area. As expected, larger \acrshort{tal}s result in a reduction in the number of users the \acrshort{enb}s can handle compared with performance when \acrshort{tal}s are disabled, due to increased paging load. \begin{figure} \centering \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/controlCustomTAsCDF_new.pdf} \caption{Custom TAs: Control traffic.} \label{fig:controlcustom} \end{subfigure} \hfill \begin{subfigure}[b]{0.485\columnwidth} \centering \includegraphics[width=\columnwidth]{images/userCapacityCustomTAsCDF_new.pdf} \caption{Custom TAs: Capacity.} \label{fig:userscustom} \end{subfigure} \caption{Control traffic and system capacities with custom tracking areas in the simulated environment.} \end{figure} \subsubsection{Control overhead with custom tracking areas} As we've demonstrated, large \acrshort{tal}s result in \acrshort{enb}s with higher control traffic load, effectively reducing the user capacity the network. To explore whether we can re-gain control traffic we again consider new, custom tracking area maps that are generated using k-means where we vary the number of unique tracking areas in the simulated network. We run the simulation with various custom tracking area maps, with all \acrshort{ue}s using \acrshort{tal} lengths of 16. The results are shown in Figures~\ref{fig:controlcustom} and~\ref{fig:userscustom}. We observe that a basemap consisting of 25 tracking areas leads to even higher control traffic compared with the conventional ({\it i.e.}, AT\&T) tracking area map. A map consisting of more tracking areas results in \acrshort{ta}s with fewer \acrshort{enb}s, thus reducing the paging load. We see that a map of 500 \acrshort{ta}s, even with a \acrshort{tal} of length 16, results in similar paging load compared with the conventional map with \acrshort{tal} disabled. Correspondingly, the user capacity of the network with a higher number of tracking areas nears the conventional capacity from Figure~\ref{fig:users}. \subsection{Testbed analysis} We study our PGPP design on a lab testbed in order to understand potential drawbacks. We implement a software-based \acrshort{EPC} and connect commodity phones to the software-defined radio-based \acrshort{enb}. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{images/pgppgear2.jpg} \caption{PGPP prototype test hardware.} \label{f:pgppgear} \vspace{-2mm} \end{figure} \noindent\textbf{Prototype.}\label{sec:prototype} We create our prototype code on srsLTE~\cite{srsLTE}, an open-source platform that implements LTE-compliant \acrshort{enb} and \acrshort{EPC} functionality and can be run using software-defined radios. Our \acrshort{EPC} / \acrshort{enb} testbed, shown in Figure~\ref{f:pgppgear}, consists of an Intel Core i7 machine running Linux and a USRP B210 radio. We use off-the-shelf commodity phones (Moto X4, Samsung Galaxy S6, and two OnePlus 5s) with programmable \acrshort{sim} cards installed to allow the phones to connect to the PGPP LTE network. The srsLTE \acrshort{mme} maintains EPS mobility management (\acrshort{emm}) and EPS connection management (\acrshort{ecm}) contexts for connected \acrshort{ue}s. The contexts are stored as structs that include the \acrshort{ue} \acrshort{imsi} in a simple key-value store, with the \acrshort{imsi} serving as the key. When the \acrshort{mme} receives S1 application protocol (\acrshort{s1ap}) messages ({\it e.g.}, due to mobility), it looks up the appropriate \acrshort{ecm} or \acrshort{emm} contexts to handle the requests. We add an additional value, a PGPPIMSI, into the \acrshort{ecm} and \acrshort{emm} structs. The PGPPIMSI is generated by combining the \acrshort{imsi} with a temporary value that is unique to the individual \acrshort{ue}-\acrshort{enb}-\acrshort{mme} connection. Accordingly, each \acrshort{ue} has a unique PGPPIMSI, which then allows us to look up the correct context when managing states. \noindent\textbf{Identical IMSIs and Shared Keys.} Given identical \acrshort{imsi} values for all users, the PGPP attach procedure can result in additional steps compared with the traditional attach. This is caused by sequence number synchronization checks during the authentication and key agreement (\acrshort{aka}) procedure, which is designed to allow the \acrshort{ue} and the network to authenticate each other. The fundamental issue is that the \acrshort{hss} and the \acrshort{sim} maintain a sequence number (\acrshort{sqn}) value that both entities increment with each successful attach. As multiple devices use the same \acrshort{imsi}s, the sequence numbers held at the \acrshort{hss} and on individual devices will no longer match, causing an authentication failure (known as a sync\_failure). At that point the \acrshort{ue} re-synchronizes with the \acrshort{hss}. We include an overview figure and details of the procedure in Appendix~\ref{sec:sqn}. We explore the delay introduced by sync\_failures using our testbed. Figure~\ref{f:sqnconnect} shows a PDF of the delays to connection completion for \acrshort{ue}s that hold identical \acrshort{imsi}s and attempt to authenticate simultaneously. In order to trigger many simultaneous authentication requests, we use openairinterface5G~\cite{nikaein2014openairinterface} to create 100 simulated \acrshort{ue}s. We observe in that the first successful \acrshort{ue} usually takes roughly 200 ms to connect, while subsequent \acrshort{ue}s that experienced sync\_failures experience additional delays. In our relatively small experiment the \acrshort{ue}s all successfully connect to the network within 1.1 seconds. In a large-scale production network the number of UEs that simultaneously attempt to connect would be larger. PGPP-based networks can mitigate the issue by using more \acrshort{hss}es, which would reduce the number of \acrshort{ue}s that each \acrshort{hss} is responsible for. Fortunately, the push for 5G will lend itself to many \acrshort{hss}es as the core network entities are being redesigned to be virtualized and located nearer to \acrshort{ue}s. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth, trim={0 10 0 13},clip]{images/connectdelayPDF.pdf} \caption{Connection delays due to sync\_failure.} \label{f:sqnconnect} \end{figure} \section{Background} Here we provide a brief overview of the cellular architecture and describe the inherent privacy challenges. For simplicity we focus on 4G LTE, though the fundamental challenges exist in 5G (discussed in~\cref{sec:5g}) as well as legacy standards. \subsection{Cellular architecture overview}\label{sec:background} The 4G LTE architecture can be divided into two areas: the Evolved UMTS Terrestrial Radio Access Network (\acrshort{eutran}), which is responsible for radio access; and the Evolved Packet Core (\acrshort{EPC}), which includes the entities responsible for authentication and connectivity to the network core. Figure~\ref{fig:lte_arch} shows a simplified architecture for both conventional cellular as well as with PGPP. PGPP moves authentication and billing to a new entity, the PGPP-GW, that is external to the \acrshort{EPC}. We detail PGPP's specific changes in~\cref{sec:pgpp}. We include a glossary of cellular terms in Appendix~\ref{sec:glossary}. \textit{\acrshort{eutran}.} The \acrshort{eutran} is the network that facilitates connectivity between user devices (\acrshort{ue}s)---commonly a cell phone with a \acrshort{sim} card installed---and the serving base station (\acrshort{enb}). The \acrshort{eutran} is responsible for providing \acrshort{ue}s a means of connecting to the \acrshort{EPC} via \acrshort{enb}s. \begin{figure}[t] \centering \includegraphics[width=0.95\columnwidth]{images/CombinedPGPP.pdf} \caption{Simplified LTE architecture with and without PGPP. PGPP decouples authentication and connectivity credentials and shifts authentication to a new, external entity, the PGPP-GW. Details of the PGPP-GW are found in~\cref{sec:auth}.} \label{fig:lte_arch} \vspace{-3mm} \end{figure} \textit{\acrshort{EPC}.} The \acrshort{EPC} is the core of the cellular network and includes entities that provide authentication, billing, voice, SMS, and data connectivity. The \acrshort{EPC} entities relevant to our discussion are the Mobility Management Entity (\acrshort{mme}), the Home Subscriber Server (\acrshort{hss}), and the Serving and Packet Data Network Gateways (\acrshort{sgw} and \acrshort{pgw}, respectively). The \acrshort{mme} is the main point of contact for a \acrshort{ue} and is responsible for orchestrating mobility and connectivity. \acrshort{ue}s authenticate to the network by sending an identifier that is stored in the \acrshort{sim} to the \acrshort{mme}. The \acrshort{hss} is then queried to verify that the \acrshort{ue} is a valid subscriber. Once the \acrshort{ue} is authenticated, the \acrshort{mme} assigns the \acrshort{ue} to an \acrshort{sgw} and \acrshort{pgw}, which offer an IP address and connectivity to the Internet. Note that LTE networks can include many copies of these entities and contain many more entities; however, for the purposes of our discussion this simplified model suffices. \textit{\acrshort{mvno}s.} We design our solution to be implemented by a Mobile Virtual Network Operator (\acrshort{mvno}). \acrshort{mvno}s are virtual in that they offer cellular service without owning the infrastructure itself. Rather, \acrshort{mvno}s pay to share capacity on the infrastructure that an underlying carrier operates. \acrshort{mvno}s can choose whether they wish to operate their own LTE core entities such as the \acrshort{mme}, \acrshort{hss}, and \acrshort{pgw}, which is the type of operation we propose. \acrshort{mvno}s that run their own core network are often called ``full'' \acrshort{mvno}s. Critically, our architecture is now feasible as the industry moves toward ``whitebox'' \acrshort{enb}s that connect to a central office that is a datacenter with virtualized \acrshort{EPC} services, as in the Open Networking Foundation's M-CORD project~\cite{m-cord} and in the upcoming 5G standard. Recent work has shown that dramatic performance gains are possible using such newer architectures~\cite{PEPC,klein}. \subsection{Identity in the cellular architecture}\label{sec:privbackground} Maintaining user privacy has long been challenging in cellular networks as it is not a primary goal of the architecture. In order to authenticate users for access and billing purposes, networks use globally unique identifiers. Likewise, the infrastructure itself must always know the location of a user in order to minimize latency when providing connectivity. We briefly discuss cellular identifiers as well as location information available from the perspective of the network in this section. We use acronyms from the 4G LTE architecture; however, similar entities exist in all generations (2G, 3G, 5G). \textit{User identifiers.}\label{sec:ids} There are multiple identifiers that can be used to associate network usage with a given subscriber. The International Mobile Subscriber Identity (\acrshort{imsi}) is the identifier used to gain access to the network when a phone (\acrshort{ue}) performs initial attachment. The \acrshort{imsi} is globally unique, permanent, and is stored on the \acrshort{sim} card. Carriers maintain a \acrshort{hss} database containing the list of \acrshort{imsi}s that are provisioned for use on the network and subscription details for each. Given the \acrshort{imsi}'s importance and sensitivity, temporary identifiers are often used instead. The Globally Unique Temporary Identifier (\acrshort{guti}) can be thought of as a temporary replacement for an \acrshort{imsi}. Once a phone attaches to the network, the Mobility Management Entity (\acrshort{mme}) generates a \acrshort{guti} value that is sent to the \acrshort{ue}, which stores the value. The \acrshort{ue} uses the \acrshort{guti} rather than the \acrshort{imsi} when it attaches to the network in the future. The \acrshort{guti} can be changed by the \acrshort{mme} periodically. Prior work recently found that \acrshort{guti}s are often predictable with consistent patterns, thus offering little privacy~\cite{hong2018guti}, but this can be remedied with a lightweight fix that we expect will be used going forward. \textit{User location information.}\label{sec:location} Cellular networks maintain knowledge of the physical location of each \acrshort{ue}. Location information is necessary to support mobility and to quickly find the \acrshort{ue} when there is an incoming call, SMS, or data for a user. The mechanism used to locate a \acrshort{ue} is known as ``paging'' and it relies on logical groupings of similarly located \acrshort{enb}'s known as ``tracking areas'' (\acrshort{ta}s). Each \acrshort{enb} is assigned to a single \acrshort{ta}. \acrshort{ta}s can be thought of as broadcast domains for paging traffic. If there is incoming data for an idle \acrshort{ue}, the paging procedure is used, where the network broadcasts a paging message to all \acrshort{enb}s in the user's last-known \acrshort{ta}. Prior work has shown that the paging mechanism can be leveraged by attackers that know an identifier of the victim ({\it e.g.}, phone number, WhatsApp ID) to generate paging messages intended for the victim, which enables an unprivileged attacker to identify a specific user's location~\cite{kune2012location}. Cellular operators also often store location metadata for subscriber, giving them the ability to trace user movement and location history. \section{Related Work} Prior work on anonymous communications often traded off latency and anonymity~\cite{vandenHooff:2015:VSP:2815400.2815417,199303,corrigan2010dissent,Corrigan-Gibbs:2015:RAM:2867539.2867658}. Likewise, Tor~\cite{dingledine2004tor} and Mixnets~\cite{chaum1981untraceable} also result in increased latency while improving anonymity. However, such solutions are inappropriate for cellular systems as, apart from SMS, cellular use cases require low latency. Additionally, the architecture continues to utilize identifiers ({\it e.g.}, \acrshort{imsi}) that can expose the user to \acrshort{imsi} catcher attack or allow for location tracking by the operator. There has been extensive prior work on finding security and privacy issues in cellular networks~\cite{4215735,8835335,practicalattackslte,lteinspector,kune2012location}. We decouple the \acrshort{imsi} from the subscriber by setting it to a single value for all users of the network. Altering the \acrshort{imsi} to specifically thwart \acrshort{imsi} catcher and similar passive attacks has been previously proposed~\cite{vandenBroek:2015:DIC:2810103.2813615, Khan:2017:TIC:3098243.3098248,sung2014location,Arapinisnew}. These techniques use pseudo-\acrshort{imsi}s (PMSIs), which are kept synchronized between the \acrshort{sim} and the \acrshort{hss}, or hypothetical virtual \acrshort{sim}s, allowing for user identification. We aim to go beyond thwarting \acrshort{imsi} catchers, and do so while considering active attacks without requiring fundamental changes on the \acrshort{ue}; we protect users from the operator itself. Hussain {\it et al.}{} introduce the TORPEDO attack~\cite{hussain2019privacy}, which allows attackers to identify the page frame index and using that, the presence or absence of a victim in a paging broadcast area ({\it i.e.}, a tracking area). However, our use of tracking area lists to provide additional paging anonymity (\cref{sec:locationprivacy}) increases the location in which a victim could potentially be, reducing the effectiveness of third-party paging-related localization attacks. The authors also define the PIERCER attack, which enables the attacker to reveal a victim's \acrshort{imsi} with only their phone number. PGPP nullifies this attack by making all \acrshort{imsi}s identical. Cellular signaling protocols have been demonstrated by multiple works to leave users' privacy vulnerable to attack~\cite{lorenz2001securing,sengar2006ss7,engel2008locating,holtmans2016detach,sonar}. Our initial design avoids signaling protocol vulnerabilities by providing data-only rather than voice/SMS, and roaming to other networks can be enabled by requiring home-routing rather than local breakout. Hussain {\it et al.}{} identifies a 5G vulnerability that allows an attacker to neutralize \acrshort{guti} refreshment in~\cite{Hussain:2019:PSP:3319535.3354263}. However, this requires a MiTM attack ({\it e.g.}, \acrshort{imsi} catcher), which necessarily means the attacker knows the victim's location. Additionally, the \acrshort{guti} is a temporary identifier, and is not associated with a specific user. Choudhury and K\o ien alter \acrshort{imsi} values, however both require substantial changes to network entities~\cite{Choudhury:2012:EUI:2360018.2360115,6673421}. We argue that a privacy-preserving architecture must be fully compatible with existing infrastructure as the global telecom infrastructure is truly a network of networks, comprised of multiple operators that connect via well-known APIs. \section{Concluding Remarks} User privacy is a hotly contested topic today, especially as law enforcement organizations, particularly in authoritarian states, insist upon increasingly ubiquitous surveillance. In addition, law enforcement has long demanded backdoor access to private user devices and user data~\cite{savage2018lawful}. We do not believe that users of PGPP, in its current form, would be capable of withstanding targeted legal or extra-legal attacks by nation-state organizations ({\it e.g.}, the FBI or NSA), though PGPP would likely limit the ability of such organizations to continue to operate a regime of mass surveillance of user mobility. In addition, a more common and problematic form of privacy loss today is due to the surreptitious sale of user data by network providers; this is a matter PGPP addresses in a manner that aligns with user autonomy. Our aim is to improve privacy in line with prior societal norms and user expectations, and to present an approach in which privacy-enhanced service can be seamlessly deployed. \section{Introduction} Cellular phone and data networks are an essential part of global communications infrastructure. In the United States, there are 129 cellular subscriptions for every 100 people and the total number of cellular subscriptions worldwide now stands at over 7.9 billion~\cite{worldbank}. Unfortunately, today's cellular architecture embeds privacy assumptions of a bygone era. In decades past, providers were highly regulated and centralized, few users had mobile devices, and data broker ecosystems were undeveloped. As a result, except for law enforcement access to phone records, user privacy was generally preserved. Protocols for cell communication embed an assumption of trusted hardware and infrastructure~\cite{3gpp.23.401}, and specifications for cellular backend infrastructure contain few formal prescriptions for preserving user data privacy. The result is that the locations of all users are constantly tracked as they simply carry a phone in their pocket, \textit{without even using it}.\\[0.5ex] \noindent \textbf{Privacy violations by carriers.} In the last two years it has been extensively reported that mobile carriers have been selling and leaking mobile location data and call metadata of hundreds of millions of users~\cite{zdnet,nytimes-cell,adage,vice,vice2}. This behavior appears to have been legal and has left mobile users without a means of recourse due to the confluence of a deregulated industry, high mobile use, and the proliferation of data brokers in the landscape. As a result, in many countries every mobile user can be physically located by anyone with a few dollars to spend. This privacy loss is ongoing and is \emph{independent} of leakage by apps that users choose to install on their phones (which is a related but orthogonal issue). While this major privacy issue has long been present in the architecture, the practical reality of the problem and lack of technical countermeasures against bulk surveillance is beyond what was known before. However there is a fundamental technical challenge at the root of this problem: even if steps were taken to limit the sale or disclosure of user data, such as by passing legislation, the cellular architecture generally and operators specifically would still seemingly need to know where users are located in order to provide connectivity. Thus users must trust that network operators will do the right thing with respect to privacy despite not having done so to date.\\[0.5ex] \noindent \textbf{Architectural, deployable solution.} We aim to remedy this state of affairs by identifying and leveraging points of decoupling in the architecture. Our solution is designed to be deployed by Mobile Virtual Network Operators (\acrshort{mvno}s), where the \acrshort{mvno} operates the evolved packet core (\acrshort{EPC}) while the base stations (\acrshort{enb}s) are operated by a Mobile Network Operator (\acrshort{mno}). This presents us with architectural independence as the \acrshort{mvno} can alter its core functionality, so long as the \acrshort{EPC} conforms to LTE/5G standards. Our approach is made feasible by the industry-wide shift toward software-based \acrshort{EPC}s. In our approach, users are protected even against tracking by their own carrier (the \acrshort{mvno}). We decouple network connectivity from authentication and billing, which allows the carrier to run \acrshort{EPC} services that are unaware of the identity or location of their users but while still authenticating them for network use. We shift authentication and billing functionality to outside of the cellular core and separate traditional cellular credentials from credentials used to gain global connectivity Since it will take time for infrastructure and legislation to change, our work is explicitly \emph{not} clean slate. In addition, we assume that existing industry players are unlikely to adopt new technologies or have an interest in preserving user privacy unless legal remedies are instituted. As a result, we consider how privacy can be added on top of today's mobile infrastructure solely by new industry entrants ({\it i.e.}, \acrshort{mvno}s) \noindent \textbf{Contributions.} We describe our prototype implementation, Pretty Good Phone Privacy (PGPP). In doing so, we examine several key challenges in achieving privacy in today's cell architecture. In particular, we consider: 1) which personal identifiers are stored and transmitted within the cellular infrastructure; 2) which core network entities have visibility into them (and how this can be mitigated); 3) which entities have the ability to provide privacy and with what guarantees; and 4) how we can provide privacy while maintaining compatibility with today's infrastructure and without requiring the cooperation of established providers. We show PGPP's impact on control traffic and on user anonymity. We show that by altering the network coverage map we are able to gain control traffic headroom compared with today's networks; we then consume that headroom in exchange for improved anonymity. We analyze the privacy improvements against a variety of common cellular attacks, including those based on bulk surveillance as well as targeted attacks. We find that PGPP significantly increases anonymity where there is none today. We find that an example PGPP network is able to increase the geographic area that an attacker could believe a victim to be within by \textasciitilde 1,200\% with little change in control load.\\[1ex] \noindent Our contributions are as follows: \begin{itemize}[nolistsep,noitemsep] \item We conduct a measurement study to demonstrate privacy leakage that exists in today's mobile networks (\cref{sec:zaatarimeasurement}). \item We design a new architecture that decouples connectivity from authentication and billing functionality, allowing us to alter the identifiers used to gain connectivity (\cref{sec:imsis}) and enable PGPP-based operators to continue to authenticate and bill users (\cref{sec:auth}) without identifying them. \item We adapt existing mechanisms to grow control traffic broadcast domains, thus enhancing user location privacy while maintaining backwards compatibility (\cref{sec:locationprivacy}). \item We quantify the impacts of PGPP on both user privacy and network control traffic through simulation (\cref{sec:simulation}) and demonstrate PGPP's feasibility in a lab testbed. \end{itemize} \section{Measurement study}\label{sec:zaatarimeasurement} In this section we demonstrate the privacy leakage that exists in today's cellular architecture by conducting a measurement study while acting as a relatively weak attacker in a real-world environment. Recall from~\cref{sec:privbackground} that the \acrshort{imsi} is a globally unique, permanent identifier. Unfortunately for user privacy, the traditional cellular architecture uses \acrshort{imsi}s for authentication and billing, as well as providing connectivity, causing the \acrshort{imsi} to be transmitted for multiple reasons. Because of its importance and permanence, the \acrshort{imsi} is seen as a high-value target for those who wish to surveil cellular users. For example, in recent years there has been a proliferation of cell-site simulators, also known as \acrshort{imsi} catchers. These devices offer what appears to be a legitimate base station (\acrshort{enb}) signal. Since \acrshort{ue} baseband radios are na\"ive and automatically connect to the strongest signal, they attempt to attach to the \acrshort{imsi} catcher and offer their \acrshort{imsi}. \acrshort{imsi} catchers have been used extensively by law enforcement and state-level surveillance agencies, with and without warrants, to identify, track, and eavesdrop on cellular users~\cite{paget2010practical}.\\[0.5ex] \noindent \textbf{Dataset.}\label{sec:zaatari} We analyze a dataset of cellular traces that our team gathered previously in a large refugee camp over a period of three days. Details of the trace collection can be found in~\cite{hybridcell, zaatari}. The traces include messages that were sent on broadcast channels in plaintext for three cellular providers that offer service in the area. Traces were captured using software defined radios and mobile phones. The trace dataset provides a vantage point that is akin to an \acrshort{imsi} catcher.\footnote{Trace collection methodology and analysis received IRB approval.}\\[0.5ex] \noindent \textbf{\acrshort{imsi}s are often broadcast in-the-clear.} We discover that, while the architecture is designed to largely use temporary \acrshort{guti}s once \acrshort{ue}s are connected, \acrshort{imsi}s are often present in paging messages. Overall we see 588,921 total paging messages, with 38,917 containing \acrshort{imsi}s (6.6\% of all pages). Of those messages we see 11,873 unique \acrshort{imsi}s. We track the number of times each individual \acrshort{imsi} was paged and plot a CDF in Figure~\ref{fig:zaataripages}. As shown, more than 60\% of \acrshort{imsi}s were paged more than once in the traces. Note that we count multiple pages seen within one second as a single page. Given this network behavior, even a passive eavesdropper could learn the permanent identifiers of nearby users.\\[0.5ex] \noindent \textbf{\acrshort{imsi}s can be tracked over time.} Given that \acrshort{imsi}s are regularly broadcast, an eavesdropper can track the presence or absence of users over time. We investigate the intervals between pages containing individual \acrshort{imsi}s. In Figure~\ref{fig:zaatariintervals} we plot a CDF of intervals (greater than one second) between subsequent pages of individual \acrshort{imsi}s. Overall, we see that \acrshort{imsi}s are repeatedly broadcast over time, even though the design of the architecture should dictate that \acrshort{imsi}s should be used sparingly in favor of temporary \acrshort{guti}s.\\[0.5ex] \noindent \textbf{Individuals can be tracked over time.} Given that we can track \acrshort{imsi}s over time, a passive attacker can track individuals' movements. Figure~\ref{fig:zaatarimap} shows locations of base stations that broadcast the \acrshort{imsi} for a single user in the traces. As shown, we saw the user in multiple locations over the course of two days. Location A was recorded at 10am on a Monday; location B was thirty minutes later. The user connected to a base station at location C at noon that same day. Locations D and E were recorded the following day at noon and 1:30pm, respectively. From this we see that a passive observer unaffiliated with a cellular carrier can, over time, record the presence and location of nearby users. This attacker is weak, with a relatively small vantage point. In reality, carriers \textit{can and do} maintain this information for \textit{all} of their users. \section{0pt}{12pt plus 4pt minus 2pt}{4pt plus 2pt minus 2pt} \titlespacing\subsection{0pt}{8pt plus 4pt minus 2pt}{3pt plus 2pt minus 2pt} \titlespacing\subsubsection{0pt}{4pt plus 4pt minus 2pt}{0pt plus 2pt minus 2pt} \begin{document} \sloppy \title{Pretty Good Phone Privacy} \author{ {\rm Paul Schmitt}\\ Princeton University\\ \and {\rm Barath Raghavan}\\ University of Southern California \\ } \maketitle \begin{abstract} \input{abstract} \end{abstract} \input{intro} \input{case} \input{measurement} \input{questions} \input{pgpp} \input{analysis} \input{discussion}\label{lastpage} \bibliographystyle{plain} \interlinepenalty=10000 \section{PMVNO Design} \section{Design}\label{sec:pgpp} In this section we describe the mechanisms PGPP employs to increase user identity and location privacy. Ultimately, PGPP's design choices appear obvious in retrospect. We believe its simplicity is an asset, as PGPP is compatible with existing networks and immediately deployable. In order to provide identity privacy against bulk attacks, we nullify the value of the \acrshort{imsi}, as it is the most common target identifier for attackers. In our design, we choose to set all PGPP user \acrshort{imsi}s to an identical value to break the link between \acrshort{imsi} and individual users. This change requires a fundamental shift in the architecture, as \acrshort{imsi}s are currently used for connectivity as well as authentication, billing, and voice/SMS routing. We design a new cellular entity for billing and authentication that preserves identity privacy. Fortunately, the industry push for software-based \acrshort{EPC}s makes our architecture feasible. We describe the architecture in~\cref{sec:imsis}. To provide location privacy from targeted attacks, PGPP leverages an existing mechanism (\acrshort{tal}s) in the cellular specification in order to grow the broadcast domain for control traffic (\cref{sec:locationprivacy}). By changing the broadcast domain for every user, the potential location of a victim is broadened from the attacker's vantage point. \subsection{User identity privacy}\label{sec:imsis} As discussed in~\cref{sec:ids}, \acrshort{imsi}s are globally unique, permanent identifiers. As such, they are routinely targeted by attackers, both legal and illegal. In this section we re-architect the network in order to thwart {\em bulk} attacks introduced in~\cref{sec:attacks} that are based on identifying individuals via \acrshort{imsi}. We decouple back-end connectivity from the authentication procedure that normally occurs at the \acrshort{hss} when a \acrshort{ue} attaches to the network. Instead, the PGPP operator issues \acrshort{sim} cards with \textit{identical} \acrshort{imsi}s to all of its subscribers. In this model, the \acrshort{imsi} is used only to prove that a user has a valid \acrshort{sim} card to use the infrastructure and, in turn, the PGPP network can provide an IP address and connectivity and offer the client a \acrshort{guti}, providing the user with a unique identity necessary for basic connectivity. \label{sec:auth} LTE authentication is normally accomplished using \acrshort{imsi}s at the \acrshort{hss}; however, all PGPP users share a single \acrshort{imsi}. Thus, to authenticate a user, we designed a post-attach oblivious authentication scheme to ensure that the PGPP operator is able to account for the user without knowing who they are. \textit{PGPP Gateway.} In order to perform this authentication we create a new logical LTE entity called a PGPP Gateway (\acrshort{pgppgw}), which sits between the \acrshort{pgw} and the public Internet. The \acrshort{pgw} is configured to have a fixed tunnel to a \acrshort{pgppgw}, which can be located outside of the PGPP operator's network. Using this mechanism, the \acrshort{pgppgw} only sees an IP address, which is typically NATed by the \acrshort{pgw}, and whether that IP address is a valid user. Notably, it does not have any information about the user's \acrshort{imsi}. The \acrshort{pgppgw} design also allows for many different architectures. For instance, multiple \acrshort{pgppgw}s could be placed in multiple datacenters or even use a privacy service such as Tor.\footnote{We leave exploration into such scenarios to future work.} \textit{Authentication properties.} From the perspective of the \acrshort{pgppgw}, there are multiple properties an authentication scheme must guarantee: (1) the gateway can authenticate that a user is indeed a valid customer\footnote{Due to ``Know Your Customer'' rules in some jurisdictions, the provider may need to have a customer list, necessitating that the user authentication scheme be compatible with periodic explicit customer billing.}; (2) the gateway and/or any other entities cannot determine the user's identity, and thus cannot link the user's credentials/authentication data with a user identity; and (3) the gateway can determine whether a user is unique or if two users are sharing credentials. \begin{table}[t] \centering \small \scalebox{1.0}{ \begin{tabular}{|l||c|c|c|} \hline \textbf{Scheme} & \textbf{Customer?} & \textbf{Anonymous?} & \textbf{Unique?}\\\hline\hline Standard auth & $\bullet$ & & \\\hline Group/ring sig & $\bullet$ & $\bullet$ & \\\hline Linkable ring sig & $\bullet$ & & $\bullet$ \\\hline\hline Cryptocurrency & & $\bullet$ & $\bullet$ \\\hline PGPP tokens & $\bullet$ & $\bullet$ & $\bullet$ \\\hline \end{tabular}} \caption{Three properties needed for user authentication in a privacy-preserving cell network and schemes to achieve them.} \label{t:gateway-auth} \vspace{-3.5mm} \end{table} As we show in Table~\ref{t:gateway-auth}, the challenge is that standard approaches for authentication only provide one of the three required properties and widely-studied cryptographic mechanisms only provide two of the three properties. For example, an ordinary authentication protocol (of which there are many~\cite{bellare1993entity, jakobsson2001mutual}) can provide property 1) but not 2) and 3). A cryptographic mechanism such as group signatures~\cite{chaum1991group,boneh2004short} or ring signatures~\cite{cramer1994proofs,rivest2001leak} can protect the user's identity upon authentication, providing properties 1) and 2), but not 3) as providing the last property would violate the security of the signature scheme. Similarly, traitor tracing schemes~\cite{chor1994tracing} (such as for broadcast encryption~\cite{fiat1993broadcast}) can provide all three properties but in practice cannot provide property 3) as the traitor tracing would require actual physical confiscation of the ``traitor'' phone by the \acrshort{mvno}, which is infeasible. A variation on ring signatures known as linkable ring signatures~\cite{liu2004linkable} provides the ability for a user's identity to be revealed if the user signs multiple messages with the same key. While this is useful in establishing that the user is unique and hasn't shared their credentials, it also partially violates the user's anonymity, as that key cannot be used again. \textit{Effective authentication.} There are two approaches that we view as viable, depending on the circumstances. An anonymity-preserving cryptocurrency can provide properties 2) and 3), but not 1) as a cryptocurrency would combine billing and authentication at the \acrshort{pgppgw}. For \acrshort{mvno}s that are not required to know their customers, an anonymity-preserving cryptocurrency may be the ideal solution for both user authentication and payment, though even the best coins provide imperfect anonymity guarantees~\cite{kappos2018empirical}. To provide all three properties, we develop a simple scheme called \textbf{PGPP tokens} that helps us sidestep the issues with alternative approaches. The choice of authentication scheme is deployment-context specific. With PGPP tokens, when paying a monthly bill a user retrieves authentication tokens that are blind-signed using Chaum's classic scheme~\cite{chaum1983blind,bellare2003one} by the billing system. Later, when authenticating to the service, the user presents tokens and the service (the \acrshort{pgppgw}) verifies their signature before allowing the user to use the network. The token scheme ensures that the service can check the validity of tokens without identifying the user requesting access. The user then presents the next token in advance so as to ensure seamless service. Note that PGPP tokens disallow the post-pay model for cellular billing, as the network would be required to know the identity of users in order to accurately charge them for usage. Therefore, PGPP is pre-pay only, though this can be adjusted to emulate post-payment ({\it e.g.}, users pre-pay for tokens on an ongoing basis rather than only monthly, and tokens are valid for a longer time period, such as a year, rather than for only one billing period). Each token represents a unit of access, as is appropriate for the service provider. Some providers may choose to offer flat-rate unlimited-data service, in which case each token represents a fixed period of time; this is the default approach that we use to describe the scheme below. Other providers may choose to offer metered service, in which case each token represents a fixed unit of data, such as 100 MB or 1 GB, rather than a period of time. Still others may choose to provide two-tiered service priority by marking each token with a priority bit, in addition to either unlimited data or metered data service; such prioritization does come with slight privacy loss, as the \acrshort{mvno} and \acrshort{mno} alike would be able to differentiate which priority level was in use. The privacy loss of two-tiered data priority can be partially mitigated by offering all users some amount of time or GB of high-priority service after which they must fall back to low-priority service; such a service plan structure is fairly standard in the industry today. In such a setting, each user would have both high-priority and low-priority tokens and thus would not be clearly stratified into two identifiable groups of users. At the beginning of a billing period, the billing system defines $s$ time slices ({\it e.g.}, corresponding to hours) or another unit of access ({\it e.g.}, a unit of data) and generates $s$ RSA keypairs for performing blind signatures using Chaum's scheme. It then appends the public keys for this time period to a well-known public repository that is externally maintained ({\it e.g.}, on GitHub), and these are fetched by users. The user generates $s$ tokens where each token takes the form $i\|r$ where $i$ is the time slice index as a 256-bit unsigned value zero indexed from the beginning of the billing period, and $r$ is a 256-bit random value chosen by the user. The user then blinds these tokens. The user pays the bill using a conventional means of payment ({\it e.g.}, credit card), and presents the blinded tokens to the billing system to be signed; the system signs each token with the corresponding time slice key and returns these values to the user. The user unblinds the response values and verifies the signatures for each. Upon later authentication to the service, the user presents its signed token for the current time slice to the \acrshort{pgppgw}, which verifies the signature and if valid begins forwarding the user's traffic onto the Internet. Since the token signature was generated using Chaum's scheme, the service cannot determine which human user corresponds to which signed token. If the same token is used by two different users during the same time period then the service can conclude that a user has shared their credentials and is attempting to cheat. The costs of this scheme to both the PGPP operator and the user are low. The operator stores the list of used tokens in a standard consistent and replicated cloud database, so the service can operate multiple \acrshort{pgppgw}s, though it is likely that a small number of \acrshort{pgppgw}s can serve a large number of users: we benchmarked the 2048-bit RSA signature verification used here at 31$\mu$s per call using Crypto++~\cite{cryptopp} on a single core of a 2.6GHz Intel Xeon E5-2640 CPU, and thus with a single CPU core the \acrshort{pgppgw} can handle token verification for tens of millions of users. The tokens themselves are small and the storage cost to the provider is about 1.5 MB / user per time period, which is a small amount for any user's phone to store and for a provider even hundreds of millions of tokens amounts to mere GBs of data in cloud storage. \textit{User device agent.} To automate the process of authenticating with the \acrshort{pgppgw}, we create a simple agent that runs as background job on the user device. This agent leverages the Android JobScheduler API; in the event of cellular connectivity, the JobScheduler triggers PGPP-token-based authentication with the \acrshort{pgppgw}. The agent establishes a TLS connection to the \acrshort{pgppgw} and then sends the token for the current time slice. Once the user presents a valid token, the \acrshort{pgppgw} begins forwarding traffic for that user, and thus this behavior is akin to a captive portal though the authentication is automatic and unseen by the user. \subsection{Location privacy}\label{sec:locationprivacy} As described in~\cref{sec:location}, cellular operators track user location in the form of tracking areas for \acrshort{ue}s in order to quickly find users when there is incoming content. PGPP leverages an existing mechanism in the cellular standard to reduce the effectiveness of {\em local-targeted} attacks described in~\cref{sec:attacks}. Paging has been exploited in the past to discover user location by adversaries. However, the use of tracking areas is useful for the cellular provider in that it confines the signaling message load ({\it i.e.}, paging messages) to a relatively small subset of the infrastructure. Tracking areas reduce mobility signaling from \acrshort{ue}s as they move through the coverage zone of a single tracking area. Note that emergency calling represents a special case in cellular networks. When a device dials 911, the phone and network attempt to estimate accurate location information. In this work we do not alter this functionality as we anticipate that users dialing 911 are willing to reveal their location. \textit{TALs.}\label{sec:tals} In PGPP, we exploit the tracking area list (\acrshort{tal}) concept, introduced in 3GPP Release 8~\cite{3gpp.23.401}. Using \acrshort{tal}s, a \acrshort{ue} no longer belongs to a single tracking area, but rather is given a list of up to 16 tracking areas that it can freely move through without triggering a tracking area update, essentially creating larger tracking areas. Whereas prior work has focused on using \acrshort{tal}s to pre-compute optimal tracking area combinations for users~\cite{razavi,razavi2,razavi3}, in PGPP, we use \acrshort{tal}s to provide provide improved location anonymity. Typically, \acrshort{tal}s consist of groups of adjacent tracking areas that are pre-computed, essentially growing the tracking area for a \acrshort{ue} to the union of all tracking areas in the \acrshort{tal}. We do not use \acrshort{tal}s in this way. Instead, we generate \acrshort{tal}s on-the-fly and generate them uniquely for each \acrshort{ue}. When a \acrshort{ue} attaches or issues a tracking area update message, the \acrshort{mme} learns the \acrshort{enb} and tracking area the \acrshort{ue} is currently attached to. The \acrshort{mme} then generates a unique \acrshort{tal} by iteratively selecting at random some number (up to the \acrshort{tal} limit of 16) of additional, adjacent tracking areas. By generating unique \acrshort{tal}s for each user, attackers are unable to know a priori which set of tracking areas (or \acrshort{enb}s) that victim is within. We explore tradeoffs in terms of \acrshort{tal} length, control traffic overhead, and location anonymity in the next section. \section{Scope} We believe that many designs are possible to increase privacy in mobile networks, and no architecture, today or in the future, is likely to provide perfect privacy. Nevertheless, below we discuss various properties that PGPP strives to achieve. Prior work examined the security vulnerabilities in modern cell networks~\cite{lteinspector,practicalattackslte,kune2012location} and revealed a number of flaws in the architecture itself. In addition, data brokers and major operators alike have taken advantage of the cellular architecture's vulnerabilities to profit off of revealing sensitive user data. We believe mobile networks should aim to, at a minimum, provide one or both of the following privacy properties.\\[0.5ex] \noindent \textbf{Identity privacy.} A network can aim to protect users' identity. Networks---as well as third party attackers---identify users through \acrshort{imsi}s, which are intended to be uniquely identifying.\\[0.5ex] \noindent \textbf{Location privacy.} A network can aim to protect information about the whereabouts of a phone. Naturally, these privacy properties do not exist in isolation; they intersect in critical ways. For example, attackers often aim to learn not only who a user is but where a specific user is currently located, or where a user was when a specific call was made. Also, the definition of an attacker or adversary is a complex one, and depending on context may include individuals aiming to steal user data, mobile carriers and data brokers looking to profit off of user data, governments seeking to perform bulk surveillance, law enforcement seeking to monitor a user with or without due process, and many others. Due to context dependence, we do not expect all privacy-focused mobile networks to make the same choice of tradeoffs. \subsection{Cellular privacy threat model}\label{sec:attacks} Given the above discussion, we distinguish between bulk and targeted data collection. We define bulk collection to be the collection of information from existing cellular architecture traffic without the introduction of attack traffic; thus, bulk collection is passive. Bulk attacks commonly target user identities ({\it e.g.}, \acrshort{imsi}s). PGPP's core aim is to protect against bulk attacks. Targeted attacks are active and require injection of traffic to attack specific targets. Targeted attacks are often aimed at discovering a victim's location. We also delineate attacks by the adversary's capabilities, as they may have visibility into an entire network (global) versus, for an unprivileged attacker, some smaller subset of a network's infrastructure (local). Table~\ref{tab:attacks} gives the taxonomy of attacks. Carriers and governments are the most common \textbf{global-bulk} attackers. Such bulk surveillance is commonplace in cellular networks, and has been at the center of recent lawsuits and privacy concerns. Attacks that employ \acrshort{imsi} catchers or passively listen to broadcasts using software-defined radios are considered \textbf{local-bulk}. Here, an \acrshort{imsi} catcher is only able to monitor phones that connect directly to it, so its visibility is limited to its radio range. Similarly, SDR-based passive snooping (as in the example in~\cref{sec:zaatarimeasurement}) is only able to monitor nearby base stations and will miss portions of the network. We design PGPP with a primary focus on thwarting bulk attacks by nullifying the value of \acrshort{imsi}s (\cref{sec:imsis}). \begin{table}[t] \centering \small \resizebox{\columnwidth}{!}{ \begin{tabular}{ll|l|l|} \cline{3-4} & & \multicolumn{2}{c|}{\textbf{Attack type}} \\ \cline{3-4} \multicolumn{1}{l}{} & & \textbf{Bulk} & \textbf{Targeted} \\ \hline \multicolumn{1}{|l|}{\multirow{2}{*}{\rotatebox[origin=c]{90}{\textbf{Visibility\hspace{-0.3em}}}}} & \textbf{Global} & \begin{tabular}[c]{@{}l@{}}Carrier logs~\cite{zdnet,adage,vice,vice2} / \\ Government Surveillance~\cite{carpenter_v_united_states_2018}\end{tabular} & Carrier Paging \\ \cline{2-4} \multicolumn{1}{|l|}{} & \textbf{Local} & \begin{tabular}[c]{@{}l@{}}SDR~\cite{7146071, van2016effectiveness, mjolsnes2017easy} / \\ IMSI Catcher~\cite{paget2010practical, joachim2003method}\end{tabular} & Paging attack~\cite{hussain2019privacy, kune2012location}\\ \hline \end{tabular}} \caption{Common cellular attacks.} \label{tab:attacks} \vspace{-3mm} \end{table} \textbf{Local-targeted} attacks can be carried out by ordinary users by generating traffic that causes a network to page a victim ({\it e.g.}, phone call to the victim). As local-targeted attackers do not have visibility into the entire network, they must rely upon knowledge of the geographic area that is encompassed by a tracking area. Due to the prevalence of such attacks, as an enhancement, an operator can provide functionality, in cooperation with the user, that reduces the efficacy of local-targeted attacks through the use of \acrshort{tal}s~(\cref{sec:locationprivacy}). \textbf{Global-targeted} attacks represent a very powerful attacker who can actively probe a victim while having global visibility of the network. We envision defenses against such attacks would require fundamental changes to to communication models. PGPP does not mitigate global-targeted attacks as we focus on immediately deployable solutions; we leave this to future work. \subsection{Aims} Next we discuss the aims of PGPP by considering several common questions that arise. \textit{\textbf{What sort of privacy does PGPP provide?}} As its name suggests, PGPP aims to provide ``pretty good'' privacy; we don't believe there is a solution that provides perfect privacy, causes no service changes ({\it i.e.}, does not increase latency), and is incrementally deployable on today's cellular networks. The main focus is to offer privacy against global-bulk surveillance of mobility and location, a practice by carriers that is widespread and pernicious. We thwart this via eliminating the \acrshort{imsi} as an individual identifier and decoupling the authentication and connectivity mechanisms in the cellular architecture. \textit{\textbf{Isn't 5G more secure than legacy generations?}} \label{sec:5g} We are currently on the brink of a new generation of cellular connectivity: 5G. While the ITU requirements for what can be called 5G have not been fully ratified (they are scheduled for this year), many preliminary components of the standard have achieved widespread agreement. \textit{Encrypted \acrshort{imsi}s.} 5G includes the addition of encrypted \acrshort{imsi}s, where public key cryptography, along with ephemeral keys generated on the \acrshort{sim}, is used to encrypt the \acrshort{imsi} when sending it to the network. This protects user \acrshort{imsi}s from eavesdroppers. However, encrypted \acrshort{imsi}s do not prevent the cellular provider \textit{itself} from knowing the user's identity. An analogy for encrypted \acrshort{imsi}s can be found in TLS for web traffic: eavesdroppers cannot see unencrypted traffic, yet the endpoints (the web server for TLS, the cellular core in 5G) can. The goal of this work is to not only thwart local-bulk attacks, but also protect user privacy from mobile operators that would otherwise violate it ({\it i.e.}, global-bulk attacks). \textit{Small cell location privacy.} The 5G standard strives for reduced latencies as well as much higher data throughputs. This necessitates the use of cells that cover smaller areas in higher frequency spectrum in order to overcome interference compared with previous cellular generations that used macrocells to provide coverage to large areas. A (likely unintended) byproduct of 5G's use of smaller cells is a dramatic {\em reduction} in location privacy for users. As the 5G network provider maintains state pertaining to the location in the network for a given user for the purposes of paging, smaller cells result in the operator, or attacker, knowing user locations at a much higher precision compared with previous generations. \textit{\textbf{What about active | traffic analysis | signaling attacks?}} While active, targeted attacks aren’t our main focus, we improve privacy in the face of them by leveraging \acrshort{tal}s to increase and randomize the broadcast domain for paging traffic, making it more difficult for attackers to know where a victim is located (analyzed in~\cref{sec:localtargeted}). Further, the goal of many active attacks is to learn users' \acrshort{imsi}s, and our nullification of \acrshort{imsi}s renders such attacks meaningless. An attacker with a tap at the network edge could use traffic analysis attacks to reduce user privacy. We largely view this as out of scope as users can tunnel traffic and use other means to hide their data usage patterns. Cellular networks rely on signaling protocols such as Signaling System 7 (\acrshort{ss7}) and \acrshort{diameter} when managing mobility as well as voice and SMS setup and teardown. These protocols enable interoperability between carriers needed for roaming and connectivity across carriers. Unfortunately, these protocols were designed with inherent trust in the network players, and have thus been used to reduce user privacy and disrupt connectivity~\cite{lorenz2001securing,sengar2006ss7,engel2008locating,holtmans2016detach,sonar}. We design PGPP for 4G/5G data only, which renders legacy \acrshort{ss7} compatibility moot. Our PGPP design expects users to use outside messaging services rather than an in-EPC \acrshort{ims} system. \textit{\textbf{Can PGPP support roaming?}} Yes. While we envision that many PGPP users would explicitly not wish to roam, as roaming partners may not provide privacy guarantees, roaming is possible using a \acrshort{diameter} edge agent that only allows for home routed roaming, forcing traffic to route from the visited network's \acrshort{sgw} back to the PGPP operator's \acrshort{pgw}, rather than local breakout due to our authentication mechanism (\cref{sec:auth}). Roaming, and international roaming in particular, adds billing complexities for the PGPP operator. Typically, the visited network collects call data records for each roaming user on its network and calculates the wholesale charges payable by the home network. The visited network then sends a Transferred Account Procedure (\acrshort{tap}) file to the home network via a data clearing house. The home network then pays the visited network. In PGPP, the individual identity of the user that roamed is not known, yet the PGPP operator remains able to pay the appropriate fees to visited networks. \textit{\textbf{How does PGPP protect user privacy for voice or text service?}} Out of the box, PGPP doesn't provide protection for such service. Instead, PGPP aims provide privacy \textit{from the cellular architecture itself}, and in doing so users are free to use a third party VoIP provider (in which case the phone will operate identically to a normal phone for telephony service from a user's perspective) or use recent systems by Lazar et al.~\cite{yodel, karaoke} that provide strong metadata privacy guarantees for communications, or similar systems such as~\cite{199303, vandenHooff:2015:VSP:2815400.2815417,corrigan2010dissent,Corrigan-Gibbs:2015:RAM:2867539.2867658}. We view PGPP as complementary to such systems. \textit{\textbf{How does PGPP protect users against leaky apps?}} PGPP doesn't, as it is about providing protection in the cellular infrastructure. Even without leaky apps, users can always intentionally or inadvertently reveal their identity and location. Leaky apps make this worse as they collect and, sometimes, divulge sensitive user information. We see PGPP as complementary to work that has targeted privacy in mobile app ecosystems. Further, apps are not as fundamental as connectivity---users can choose whether to install and run a leaky app, and can constrain app permissions. However, phones are, by their nature, always connected to carrier networks, and those very networks have been selling user data to third parties. \textit{\textbf{If users can't be identified by carriers, how can carriers still make money?}} We introduce PGPP tokens in~\cref{sec:auth} as a mechanism for a PGPP operator to charge customers while protecting user anonymity. \textit{\textbf{Can't phone hardware be tracked as well?}} Phones have an International Mobile Equipment Identity (\acrshort{imei}). The \acrshort{imei} is assigned to the hardware by the manufacturer and identifies the manufacturer, model, and serial number of a given device. Some operators keep an \acrshort{imei} database to check whether a device has been reported as stolen, known as an equipment identity register (\acrshort{eir}); \acrshort{imei}s in the database are blacklisted. For many devices, the \acrshort{imei} can be changed through software, often without root access. We envision a PGPP \acrshort{mvno} would allow for subscribers to present their unchanged device \acrshort{imei}, giving the PGPP operator the opportunity to check against a \acrshort{eir} to verify the phone has not been reported as stolen. At that point, the \acrshort{imei} could be reprogrammed to a single value, similar to our changes to the \acrshort{imsi}. Note that different jurisdictions have different rules about whether, how, and by whom an \acrshort{imei} can be changed, so only in some cases \acrshort{imei} changes require cooperation with the \acrshort{mvno}. \textit{\textbf{Is PGPP legal?}} Legality varies by jurisdiction. For example, U.S. law (CALEA~\cite{calea}), requires providers to offer lawful interception of voice and SMS traffic. A PGPP-based MVNO is data-only, with voice and messaging provided by third parties. CALEA requires the provider to offer content of communication data at the \acrshort{pgw}, {\it e.g.}, raw (likely-encrypted) network traffic. This is supported by PGPP. \section{Sequence number check}\label{sec:sqn} When multiple \acrshort{ue}s attach to the network using identical \acrshort{imsi}s, the sequence number check will fail in the network, triggering synch\_failure messages and introducing delay before successful attachment. Figure~\ref{fig:aka} shows the message sequence of the LTE authentication procedure, used today on most celluar networks, and notes what occurs if duplicate IMSIs are present. When a \acrshort{ue} sends an attach request, the \acrshort{hss} feeds the following to its \acrshort{aka} function: a new nonce value \acrshort{rand}, the shared key K that is stored for the \acrshort{imsi}, and the locally-held sequence number SQN\textsubscript{HSS} for that \acrshort{imsi}. The \acrshort{aka} function generates an authentication token (AUTN\textsubscript{HSS}) that includes the SQN\textsubscript{HSS}, an expected response (\acrshort{xres}), and a key (K\textsubscript{ASME}) that is ultimately used for \acrshort{ue} and \acrshort{mme} authentication. The \acrshort{mme} forwards the \acrshort{rand} and the AUTN\textsubscript{HSS} to the \acrshort{ue}. The \acrshort{ue} then uses its own SQN\textsubscript{UE}, its shared key K, and the \acrshort{rand} to generate its own AUTN\textsubscript{UE}, a response (RES), and the key (K\textsubscript{ASME}). The \acrshort{ue} checks if the AUTN\textsubscript{UE} and AUTN\textsubscript{HSS} match and whether the its SQN\textsubscript{UE} matches the SQN\textsubscript{HSS} in the AUTN\textsubscript{HSS}. In PGPP, this will fail for most attach procedures, as individual \acrshort{sim}s will not have the same \acrshort{sqn} value as the \acrshort{hss} for the shared \acrshort{imsi}. When the \acrshort{sqn} check fails the \acrshort{ue} will send an authentication failure message with the cause: \texttt{sync\_failure}, along with the \acrshort{ue}'s current \acrshort{sqn} which allows the \acrshort{hss} to re-synchronize the \acrshort{sqn} value. The \acrshort{ue} then begins the attach sequence again, which will then succeed as the \acrshort{hss} and \acrshort{ue} should begin the attach procedure with the same \acrshort{sqn} values.
{'timestamp': '2020-09-23T02:15:34', 'yymm': '2009', 'arxiv_id': '2009.09035', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09035'}
arxiv
\section{Introduction} \label{sec:intro} As machine learning algorithms are being increasingly used in real-world decision making scenarios, there has been growing concern that these methods may produce decisions that discriminate against particular groups of people. The relevant applications include online advertising, hiring, loan approvals, and criminal risk assessment~\cite{datta2015automated,barocas2016big,chouldechova2017fair,berk2018fairness}. To address these concerns, various methods have been proposed to quantify and ensure fairness in automated decision making systems~\cite{chouldechova2017fair,dwork2012fairness,feldman2015certifying,kusner2017counterfactual,kamishima2012fairness,zemel2013learning}. A widely used notion of fairness is demographic parity, which states that sensitive attributes such as gender or race must be statistically independent of the class predictions. In this paper, we study the problem of enforcing demographic parity in probabilistic classifiers. In particular, we focus on the fact that class labels in the data are often biased, and then propose a latent variable approach that treats the observed labels as biased proxies of hidden, fair labels that satisfy demographic parity. The process that generated bias is modeled by a probability distribution over the fair label, observed label, and other features including the sensitive attributes. Moreover, we show that group fairness guarantees for a probabilistic model hold in the real world only if the model accurately captures the real-world data. Therefore, the goal of learning a fair probabilistic classifier also entails learning a distribution that achieves high likelihood. Our first contribution is to systematically derive the assumptions of a fair probabilistic model in terms of independence constraints. Each constraint serves the purpose of explaining how the observed, biased labels come from hidden fair labels and/or ensuring that the model closely represents the data distribution. Secondly, we propose an algorithm to learn probabilistic circuits (PCs)~\cite{pcTutorialUAI}, a type of tractable probabilistic models, so that the fairness constraints are satisfied. Specifically, this involves encoding independence assumptions into the circuits and developing an algorithm to learn PCs from incomplete data, as we have a latent variable. Finally, we evaluate our approach empirically on synthetic and real-world datasets, comparing against existing fair learning methods as well as a baseline we propose that does not include a latent variable. The experiments demonstrate that our method achieves high likelihoods that indeed translate to more trustworthy fairness guarantees. It also has high accuracy for predicting the true fair labels in the synthetic data, and the predicted fair decisions can still be close to unfair labels in real-world data. \section{Related Work} \label{sec:related} Several frameworks have been proposed to design fairness-aware systems. We discuss a few of them here and refer to \citet{romei2014multidisciplinary,barocas-hardt-narayanan} for a more comprehensive review. Some of the most prominent fairness frameworks include individual fairness and group fairness. Individual fairness~\citep{dwork2012fairness} is based on the idea that similar individuals should receive similar treatments, although defining similarity between individuals can be challenging. On the other hand, group fairness aims to equalize some statistics across groups defined by sensitive attributes. These include equality of opportunity~\citep{hardt2016equality} and demographic (statistical) parity~\citep{calders2010three,kamiran2009classifying} as well as its relaxed notion of disparate impact~\citep{feldman2015certifying,zafar2017fairness}. There are several approaches to achieve group fairness, which can be broadly categorized into (1) pre-processing data to remove bias~\citep{zemel2013learning,kamiran2009classifying,calmon2017optimized}, (2) post-processing of model outputs such as calibration and threshold selection~\citep{hardt2016equality,pleiss2017fairness}, and (3) in-processing which incorporates fairness constraints directly in learning/optimization~\citep{corbett2017algorithmic,agarwal2018reductions,kearns2018preventing}. Some recent works on group fairness also consider bias in the observed labels, both for evaluation and learning~\cite{Fogliato2020FairnessEI,blum2020recovering,jiang2020identifying}. For instance, \citet{blum2020recovering} studies empirical risk minimization (ERM) with various group fairness constraints and showed that ERM constrained by demographic parity does not recover the Bayes optimal classifier under one-sided, single-group label noise (this setting is subsumed by ours). In addition, \citet{jiang2020identifying} developed a pre-processing method to learn fair classifiers under noisy labels, by reweighting according to an unknown, fair labeling function. Here, the observed labels are assumed to come from a biased labeling function that is the ``closest'' to the fair one; whereas, we aim to find the bias mechanism that best explains the observed data. We would like to point out that while pre-processing methods have the advantage of allowing any model to be learned on top of the processed data, it is also known that certain modeling assumptions can result in bias even when learning from fair data~\citep{ChoiAAAI20}. Moreover, certain post-processing methods to achieve group fairness are shown to be suboptimal under some conditions~\citep{woodworth2017learning}. Instead, we take the in-processing approach to explicitly optimize the model's performance while enforcing fairness. Many fair learning methods make use of probabilistic models such as Bayesian networks~\citep{calders2010three,mancuhan2014combating}. Among those, perhaps the most related to our approach is the latent variable naive Bayes model by \citet{calders2010three}, which also assumes a latent decision variable to make fair predictions. However, they make a naive Bayes assumption among features. We relax this assumption and will later demonstrate how this helps in more closely modeling the data distribution, as well as providing better fairness guarantees. \section{Latent Fair Decisions} \label{sec:model} We use uppercase letters (e.g., $X$) for discrete random variables (RVs) and lowercase letters ($x$) for their assignments. Negation of a binary assignment $x$ is denoted by $\bar{x}$. Sets of RVs are denoted by bold uppercase letters ($\rvars{X}$), and their joint assignments by bold lowercase ($\jstate{x}$). Let $S$ denote a \textit{sensitive attribute}, such as gender or race, and let $\rvars{X}$ be the \textit{non-sensitive attributes} or features. In this paper, we assume $S$ is a binary variable for simplicity, but our method can be easily generalized to multiple multi-valued sensitive attributes. We have a dataset $\ensuremath{\mathcal{D}}$ in which each individual is characterized by variables $S$ and $\rvars{X}$ and labeled with a binary decision/class variable $D$. One of the most popular and yet simple fairness notions is demographic (or statistical) parity. It requires that the classification is independent of the sensitive attributes; i.e., the rate of positive classification is the same across groups defined by the sensitive attributes. Since we focus on probabilistic classifiers, we consider a generalized version introduced by \citet{pleiss2017fairness}, sometimes also called \emph{strong demographic parity}~\citep{jiang2019wasserstein}: \begin{defn}[Generalized demographic parity] Suppose $f$ is a probabilistic classifier and $p$ is a distribution over variables $\rvars{X}$ and $S$. Then $f$ satisfies demographic parity w.r.t.\ $p$ if: \begin{linenomath} \begin{equation*} \Ex_p[f(\rvars{X},S) \mid S=1) = \Ex_p[f(\rvars{X},S) \mid S=0]. \end{equation*} \end{linenomath} \end{defn} Probabilistic classifiers are often obtained from joint distributions $\Pr(.)$ over $D,\rvars{X},S$ by computing $\Pr(D \vert \rvars{X},S)$. Then we say the distribution satisfies demographic parity if $\Pr(D \vert S\!=\!1) = \Pr(D \vert S\!=\!0)$, i.e., $D$ is independent of $S$. \subsection{Motivation} A common fairness concern when learning decision making systems is that the dataset used is often biased. In particular, observed labels may not be the true target variable but only its proxy. For example, re-arrest is generally used as a label for recidivism prediction, but it is not equivalent to recidivism and may be biased. We will later show how the relationship between observed label and true target can be modeled probabilistically using a latent variable. Moreover, probabilistic group fairness guarantees hold in the real world only if the model accurately captures the real world distribution. In other words, using a model that only achieves low likelihood w.r.t\ the data, it is easy to give false guarantees. For instance, consider a probabilistic classifier $f(X,S)$ over a binary sensitive attribute $S$ and non-sensitive attribute $X$ shown below. \begin{center} \scalebox{0.76}{ \begin{tabular}{lc|cc|cc} \toprule $S,X$ & $f(X,S)$ & $P_{\text{data}}(X\vert S)$ & $\Ex_{P_{\text{data}}}[f\vert S]$ & $Q(X\vert S)$ & $\Ex_{Q}[f\vert S]$ \\ \midrule 1,1 & 0.8 & 0.7 & \multirow{2}{*}{0.65} & 0.5 & \multirow{2}{*}{0.55} \\ 1,0 & 0.3 & 0.3 & & 0.5 & \\ \midrule 0,1 & 0.7 & 0.4 & \multirow{2}{*}{0.52} & 0.5 & \multirow{2}{*}{0.55}\\ 0,0 & 0.4 & 0.6 & & 0.5\\ \bottomrule \end{tabular} } \end{center} Suppose in the data, the probability of $X=1$ given $S=1$ (resp.\ $S=0$) is 0.7 (resp.\ 0.4). Then this classifier does not satisfy demographic parity, as the expected prediction for group $S=1$ is $0.8\cdot0.7+0.3\cdot0.3=0.65$ while for group $S=0$ it is 0.52. On the other hand, suppose you have a distribution $Q$ that incorrectly assumes the feature $X$ to be uniform and independent of $S$. Then you would conclude, incorrectly, that the prediction is indeed fair, with the average prediction for both protected groups being 0.55. Therefore, to provide meaningful fairness guarantees, we need to model the data distribution closely, i.e., with high likelihood. \subsection{Modeling with a latent fair decision} We now describe our proposed latent variable approach to address the aforementioned issues. We suppose there is a hidden variable that represents the true label without discrimination. This latent variable is denoted as $D_f$ and used for prediction instead of $D$; i.e., decisions for future instances can be made by inferring the conditional probability $\Pr(D_f \vert \jstate{e})$ given some feature observations $\jstate{e}$ for $\rvars{E} \subseteq \rvars{X} \cup S$. We assume that the latent variable $D_f$ is independent of $S$, thereby satisfying demographic parity. Moreover, the observed label $D$ is modeled as being generated from the fair label by altering its values with different probabilities depending on the sensitive attribute. In other words, the probability of $D$ being positive depends on both $D_f$ and $S$. \begin{figure}[tb] \centering \begin{subfigure}[b]{0.49\columnwidth} \centering \scalebox{0.9}{ \begin{tikzpicture}[bayesnet] \def0bp{0bp} \def-40bp{-40bp} \node (S) at (-20bp,0bp) [bnnode] {$S$}; \node (Df) at (20bp,0bp) [bnnode] {$D_f$}; \node (X) at (-20bp,-40bp) [bnnode] {$\rvars{X}$}; \node (D) at (20bp,-40bp) [bnnode] {$D$}; \begin{scope}[on background layer] \draw [bnarrow] (S) -- (X); \draw [bnarrow] (S) -- (D); \draw [bnarrow] (Df) -- (X); \draw [bnarrow] (Df) -- (D); \end{scope} \end{tikzpicture}} \caption{} \label{fig:fair-BN} \end{subfigure} \begin{subfigure}[b]{0.49\columnwidth} \centering \scalebox{0.9}{ \begin{tikzpicture}[bayesnet] \def0bp{0bp} \def-40bp{-40bp} \node (S) at (-20bp,0bp) [bnnode] {$S$}; \node (D) at (20bp,0bp) [bnnode] {$D$}; \node (X) at (-20bp,-40bp) [bnnode] {$\rvars{X}$}; \begin{scope}[on background layer] \draw [bnarrow] (S) -- (X); \draw [bnarrow] (D) -- (X); \end{scope} \end{tikzpicture}} \caption{} \label{fig:alt-BN} \end{subfigure} \caption{Bayesian network structures that represent the proposed fair latent variable approach (left) and model without a latent variable (right). Abusing notation, the set of features $\rvars{X}$ is represented as a single node, but refers to some local Bayesian network over $\rvars{X}$.} \end{figure} In addition, our model also assumes that the observed label $D$ and non-sensitive features $\rvars{X}$ are conditionally independent given the latent fair decision and sensitive attributes, i.e., $D \independent \rvars{X} \vert D_f,S$. This is a crucial assumption to learn the model from data where $D_f$ is hidden. To illustrate why, suppose there is no such independence. Then the induced model allows variables $S, \rvars{X}, D$ to depend on one another freely. Thus, such model can represent any marginal distribution over these variables, regardless of the parameters for $D_f$. We can quickly see this from the fact that for all $s,\jstate{x},d$, \begin{linenomath}\begin{align*} \Pr(s\jstate{x} d) &= \Pr(s) \Pr(\jstate{x} d \vert s) \\ &= \Pr(s) \big( \Pr(\jstate{x} d \vert s,D_f\!=\!1) \Pr(D_f\!=\!1) \\ &\phantom{=\Pr(s) \big(}+ \Pr(\jstate{x} d \vert s, D_f\!=\!0) \Pr(D_f\!=\!0) \big). \end{align*}\end{linenomath} That is, multiple conditional distributions involving the latent fair decision $D_f$ will result in the same marginal distribution over $S,\rvars{X},D$, and thus the real joint distribution is not identifiable when learning from data where $D_f$ is completely hidden. For instance, the learner will not be incentivized to learn the relationship between $D_f$ and other features, and may assume the latent decision variable to be completely independent of the observed variables. This is clearly undesirable because we want to use the latent variable to make decisions based on feature observations. The independence assumptions of our proposed model are summarized as a Bayesian network structure in Figure~\ref{fig:fair-BN}. Note that the set of features $\rvars{X}$ is represented as a single node, as we do not make any independence assumptions among the features. In practice, we learn the statistical relationships between these variables from data. This is in contrast to the latent variable model by \citet{calders2010three} which had a naive Bayes assumption among the non-sensitive features; i.e., variables in $\rvars{X}$ are conditionally independent given the sensitive attribute $S$ and $D_f$. As we will later show empirically, such strong assumption not only affects the prediction quality but also limits the fairness guarantee, as it will hold only if the naive Bayes assumption is indeed true in the data distribution. The latent variable not only encodes the intuition that observed labels may be biased, but it also has advantages in achieving high likelihood with respect to data. Consider an alternative way to satisfy statistical parity: by directly enforcing independence between the observed decision variable $D$ and sensitive attributes $\rvars{S}$: see Figure~\ref{fig:alt-BN}. We will show that, on the same data, our proposed model can always achieve marginal likelihood at least as high as the model without a latent decision variable. We can enforce the independence of $D$ and $\rvars{S}$ by setting the latent variable $D_f$ to always be equal to $D$, which results in a marginal distribution over $S,\rvars{X},D$ with the same independencies as in Figure~\ref{fig:alt-BN}: \begin{linenomath}\begin{align*} &\Pr(s\jstate{x} d) \\ &= \Pr(\jstate{x} \mid s,D_f\!=\!1) \Pr(d \mid s,D_f\!=\!1)\Pr(s)\Pr(D_f\!=\!1) \\ &\quad + \Pr(\jstate{x} \mid s,D_f\!=\!0)\Pr(d \mid s, D_f\!=\!0)\Pr(s)\Pr(D_f\!=\!0) \\ &= \Pr(\jstate{x} \mid s d) \Pr(s) \Pr(d) \end{align*}\end{linenomath} Thus, any fair distribution without the latent decision can also be represented by our latent variable approach. In addition, our approach will achieve strictly better likelihood if the observed data does not satisfy demographic parity, because it can also model distributions where $D$ and $S$ are dependent. Lastly, we emphasize that Bayesian network structures were used in this section only to illustrate the independence assumptions of our model. In practice, other probabilistic models can be used to represent the distribution as long as they satisfy our independence assumptions; we use probabilistic circuits as discussed in the next section. \section{Learning Fair Probabilistic Circuits} \label{sec:pc} There are several challenges in modeling a fair probability distribution. First, as shown previously, fairness guarantees hold with respect to the modeled distribution, and thus we want to closely model the data distribution. A possible approach is to learn a deep generative model such as a generative adversarial networks (GANs)~\citep{goodfellow2014generative}. However, then we must resort to approximate inference, or deal with models that have no explicit likelihood, and the fairness guarantees no longer hold. An alternative is to use models that allow exact inference such as Bayesian networks. Unfortunately, marginal inference, which is needed to make predictions $\Pr(D_f \vert \jstate{e})$, is \#P-hard for general BNs~\cite{Roth1996}. Tree-like BNs such as naive Bayes allow polytime inference, but they are not expressive enough to accurately capture the real world distribution. Hence, the second challenge is to also support tractable exact inference without sacrificing expressiveness. Lastly, the probabilistic modeling method we choose must be able to encode the independencies outlined in the previous section, to satisfy demographic parity and to learn a meaningful relationship between the latent fair decision and other variables. In the following, we give some background on \emph{probabilistic circuits (PCs)} and show how they satisfy each of the above criteria. Then we will describe our proposed algorithm to learn fair probabilistic circuits from data. \subsection{Probabilistic Circuits} \paragraph{Representation} \emph{Probabilistic circuits (PCs)}~\cite{PCTuto20} refer to a family of tractable probabilistic models including arithmetic circuits~\cite{darwicheKR02,darwicheJACM-POLY}, sum-product networks~\cite{poon2011sum}, and cutset networks~\cite{rahman2014cutset}. A probabilistic circuit $\ensuremath{\mathcal{C}} = (\ensuremath{\mathcal{G}},\mathcal{\boldsymbol{\theta}})$ over RVs $\rvars{X}$ is characterized by its structure $\ensuremath{\mathcal{G}}$ and parameters $\mathcal{\boldsymbol{\theta}}$. The circuit structure $\ensuremath{\mathcal{G}}$ is a directed acyclic graph (DAG) such that each inner node is either a \textit{sum} node or a \textit{product} node, and each \textit{leaf} (input) node is associated with a univariate input distribution. We denote the distribution associated with leaf $n$ by $f_n(.)$. This may be any probability mass function, a special case being an indicator function such as $[X=1]$. Parameters $\mathcal{\boldsymbol{\theta}}$ are each associated with an input edge to a sum node. Note that a subcircuit rooted at an inner node of a PC is itself a valid PC. Figure~\ref{fig:fair-pc} depicts an example probabilistic circuit.\footnote{The features $\rvars{X}$ and $D$ are shown as leaf nodes for graphical conciseness, but refer to sub-circuits over the respective variables.} \begin{figure}[tb] \centering \scalebox{0.8}{ \begin{tikzpicture} \sumnode[line width=1.0pt]{s1}; \prodnode[line width=1.0pt, below=17pt of s1, xshift=-2*17pt]{p2}; \prodnode[line width=1.0pt, below=17pt of s1, xshift=2*17pt]{p3}; \prodnode[line width=1.0pt, left=2*17pt of p2]{p4}; \prodnode[line width=1.0pt, right=2*17pt of p3]{p5}; \bernode[line width=1.0pt, below=17pt of p4, xshift=13pt]{v1}{$S\!=\!1$}; \bernode[line width=1.0pt, below=17pt of p2, xshift=-13pt]{v2}{$D_f\!=\!1$}; \bernode[line width=1.0pt, below=17pt of p3, xshift=13pt]{v3}{$D_f\!=\!0$}; \bernode[line width=1.0pt, below=17pt of p5, xshift=-13pt]{v4}{$S\!=\!0$}; \prodnode[line width=1.0pt, below=17pt+13pt of p4, xshift=-13pt]{p6}; \prodnode[line width=1.0pt, below=17pt+13pt of p2, xshift=13pt]{p7}; \prodnode[line width=1.0pt, below=17pt+13pt of p3, xshift=-13pt]{p8}; \prodnode[line width=1.0pt, below=17pt+13pt of p5, xshift=13pt]{p9}; \contnode[line width=1.0pt, below=17pt of p6, xshift=-13pt]{v5}{$D$}; \contnode[line width=1.0pt, below=17pt of p6, xshift=13pt]{v6}{$\rvars{X}$}; \contnode[line width=1.0pt, below=17pt+13pt of v2]{v7}{$D$}; \contnode[line width=1.0pt, right=13pt of v7]{v8}{$\rvars{X}$}; \contnode[line width=1.0pt, below=17pt+13pt of v3]{v9}{$\rvars{X}$}; \contnode[line width=1.0pt, left=13pt of v9]{v10}{$D$}; \contnode[line width=1.0pt, below=17pt of p9, xshift=-13pt]{v11}{$D$}; \contnode[line width=1.0pt, below=17pt of p9, xshift=13pt]{v12}{$\rvars{X}$}; \weigedge[line width=1.0pt,above,pos=0.45,color=red] {s1} {p4} {\footnotesize $\color{red}\theta_1$}; \weigedge[line width=1.0pt,left,pos=0.37,color=ForestGreen] {s1} {p2} {\footnotesize $\color{ForestGreen}\theta_2$}; \weigedge[line width=1.0pt,right,pos=0.37] {s1} {p3} {\footnotesize $\theta_3$}; \weigedge[line width=1.0pt,above,pos=0.45] {s1} {p5} {\footnotesize $\theta_4$}; \edge[line width=1.0pt,left,>=stealth,draw=red] {p4} {v1}; \edge[line width=1.0pt,right,>=stealth,draw=red] {p4} {v2}; \edge[line width=1.0pt,left,>=stealth,color=ForestGreen] {p2} {v1}; \edge[line width=1.0pt,right,>=stealth,color=ForestGreen] {p2} {v3}; \edge[line width=1.0pt,left,>=stealth] {p3} {v2}; \edge[line width=1.0pt,right,>=stealth] {p3} {v4}; \edge[line width=1.0pt,left,>=stealth] {p5} {v3}; \edge[line width=1.0pt,right,>=stealth] {p5} {v4}; \edge[line width=1.0pt,left,>=stealth,draw=red] {p4} {p6}; \edge[line width=1.0pt,left,>=stealth,color=ForestGreen] {p2} {p7}; \edge[line width=1.0pt,left,>=stealth] {p3} {p8}; \edge[line width=1.0pt,left,>=stealth] {p5} {p9}; \edge[line width=1.0pt,left,>=stealth,draw=red] {p6} {v5}; \edge[line width=1.0pt,left,>=stealth,draw=red] {p6} {v6}; \edge[line width=1.0pt,left,>=stealth,color=ForestGreen] {p7} {v7}; \edge[line width=1.0pt,left,>=stealth,color=ForestGreen] {p7} {v8}; \edge[line width=1.0pt,left,>=stealth] {p8} {v9}; \edge[line width=1.0pt,left,>=stealth] {p8} {v10}; \edge[line width=1.0pt,left,>=stealth] {p9} {v11}; \edge[line width=1.0pt,left,>=stealth] {p9} {v12}; \end{tikzpicture} } \caption{ A probabilistic circuit over variables $S,\rvars{X},D,D_f$} \label{fig:fair-pc} \end{figure} Let $\ensuremath{\mathsf{ch}}(n)$ be the set of children nodes of an inner node $n$. Then a probabilistic circuit $\ensuremath{\mathcal{C}}$ over RVs $\rvars{X}$ defines a joint distribution $\Pr_{\ensuremath{\mathcal{C}}}(\rvars{X})$ in a recursive way as follows: \begin{linenomath}\begin{equation*} {\Pr}_n(\jstate{x})= \begin{cases} f_n(\jstate{x}) &\text{if $n$ is a leaf node} \\ \prod_{c\in\ensuremath{\mathsf{ch}}(n)} \Pr_c(\jstate{x}) &\text{if $n$ is a product node} \\ \sum_{c\in\ensuremath{\mathsf{ch}}(n)} \theta_{n,c} \Pr_c(\jstate{x}) &\text{if $n$ is a sum node} \end{cases} \label{eq:EVI} \end{equation*}\end{linenomath} Intuitively, a product node $n$ defines a factorized distribution, and a sum node $n$ defines a mixture model parameterized by weights $\{\theta_{n,c}\}_{c\in\ensuremath{\mathsf{ch}}(n)}$. $\Pr_n$ is also called the \textit{output} of $n$. \paragraph{Properties and inference} A strength of probabilistic circuits is that (1) they are expressive, achieving high likelihoods on density estimation tasks~\cite{rahman2016merging,LiangUAI17,peharz2020random}, and (2) they support tractable probabilistic inference, enabled by certain structural properties. In particular, PCs support efficient marginal inference if they are smooth and decomposable. A circuit is said to be \emph{smooth} if for every sum node all of its children depend on the same set of variables; it is \emph{decomposable} if for every product node its children depend on disjoint sets of variables~\citep{darwiche2002knowledge}. Given a smooth and decomposable probabilistic circuit, computing the marginal probability for any partial evidence is reduced to simply evaluating the circuit bottom-up. This also implies tractable computation of conditional probabilities, which are ratios of marginals. Thus, we can make predictions in time linear in the size of the circuit. Another useful structural property is \emph{determinism}; a circuit is deterministic if for every complete input $\jstate{x}$, at most one child of every sum node has a non-zero output. In addition to enabling tractable inference for more queries~\citep{ChoiDarwiche17}, it leads to closed-form parameter estimation of probabilistic circuits given complete data. We also exploit this property for learning PCs with latent variables, which we will later describe in detail. \paragraph{Encoding independence assumptions} Next, we demonstrate how we encode the independence assumptions of a fair distribution as in Figure~\ref{fig:fair-BN} in a probabilistic circuit. Recall the example PC in Figure~\ref{fig:fair-pc}: regardless of parameterization, this circuit structure always encodes a distribution where $D$ is independent of $\rvars{X}$ given $S$ and $D_f$. To prove this, we first observe that the four product nodes in the second layer each correspond to four possible assignments to $S$ and $D_f$. For instance, the left-most product node returns a non-zero output only if the input sets both $S=1$ and $D_f=1$. Effectively, the sub-circuits rooted at these nodes represent conditional distributions $\Pr(D,\rvars{X} \vert s, d_f)$ for assignments $s,d_f$. Because the distributions for $D$ and $\rvars{X}$ factorize, we have $\Pr(D,\rvars{X} \vert s,d_f) = \Pr(D \vert s,d_f) \cdot \Pr(\rvars{X} \vert s,d_f)$, thereby satisfying the conditional independence $D \independent \rvars{X} \vert D_f,S$. We also need to encode the independence between $D_f$ and $S$. In the example circuit, each edge parameter $\theta_i$ corresponds to $\Pr(s,d_f)$ for a joint assignment to $S,D_f$. With no restriction on these parameters, the circuit structure does not necessarily imply $D_f\!\independent\!S$. Thus, we introduce auxiliary parameters $\phi_s$ and $\phi_{d_f}$ representing $\Pr(S\!=\!1)$ and $\Pr(D_f\!=\!1)$, respectively, and enforce that: \begin{linenomath}\begin{gather*} \phi_s = \theta_1 + \theta_2, \quad \phi_{d_f} = \theta_1 + \theta_2, \\ \theta_1 = \phi_s \cdot \phi_{d_f},\; \theta_2 = \phi_s \cdot (1-\phi_{d_f}), \\ \theta_3 = (1-\phi_s) \cdot \phi_{d_f},\; \theta_4 = (1-\phi_s) \cdot (1-\phi_{d_f}). \end{gather*}\end{linenomath} Hence, when learning these parameters, we limit the degree of freedom such that the four edge parameters are given by two free variables $\phi_s$ and $\phi_{d_f}$ instead of the four $\theta_i$ variables. Next, we discuss how to learn a fair probabilistic circuit with latent variable from data. This consists of two parts: learning the circuit structure and estimating the parameters of a given structure. We first study parameter learning in the next section, then structure learning in Section~\ref{sec:str-learning}. \subsection{Parameter Learning} \label{sec:param-learn} Given a complete data set, maximum-likelihood parameters of a smooth, decomposable, and deterministic PC can be computed in closed-form~\citep{KisaVCD14}. For an edge between a sum node $n$ and its child $c$, the associated maximum-likelihood parameter for a complete dataset $\ensuremath{\mathcal{D}}$ is given by: \begin{equation} \theta_{n,c} = F_{\ensuremath{\mathcal{D}}}(n,c) / \sum_{c\in\ensuremath{\mathsf{ch}}(n)} F_{\ensuremath{\mathcal{D}}}(n,c) \label{eq:param} \end{equation} Here, $F_{\ensuremath{\mathcal{D}}}(n,c)$ is called the \emph{circuit flow} of edge $(n,c)$ given $\ensuremath{\mathcal{D}}$, and it counts the number of data samples in $\ensuremath{\mathcal{D}}$ that ``activate'' this edge. For example, in Figure \ref{fig:fair-pc}, the edges activated by sample $\{D_f\!=\!1,S\!=\!1,d,\jstate{x}\}$, for any assignments $d,\jstate{x}$, are colored red.\footnote{See Appendix~\ref{sec:app-EF} for a formal definition and proof of Equation~\ref{eq:param}.} However, our proposed approach for fair distribution includes a latent variable, and thus must be learned from incomplete data. One of the most common methods to learn parameters of a probabilistic model from incomplete data is the Expectation Maximization (EM) algorithm~\citep{PGM,darwiche2009}. EM iteratively completes the data by computing the probability of unobserved values (E-step) and estimates the maximum-likelihood parameters from the expected dataset (M-step). We now propose an EM parameter learning algorithm for PCs that does not explicitly complete the data, but rather utilizes circuit flows. In particular, we introduce the notion of \emph{expected flows}, which is defined as the following for a given circuit $\ensuremath{\mathcal{C}}=(\ensuremath{\mathcal{G}},\mathcal{\boldsymbol{\theta}})$ over RVs $\rvars{Z}$ and an incomplete dataset $\ensuremath{\mathcal{D}}$: \begin{linenomath}\begin{align*} \EF_{\ensuremath{\mathcal{D}},\mathcal{\boldsymbol{\theta}}}(n,c) :=& \mathbb{E}_{\pr_{\ensuremath{\mathcal{C}}}}[F_{\ensuremath{\mathcal{D}}_i}(n,c)] \\ =& \sum_{\ensuremath{\mathcal{D}}_i \in \ensuremath{\mathcal{D}}} \sum_{\jstate{z} \models \ensuremath{\mathcal{D}}_i} \pr_{\ensuremath{\mathcal{C}}}(\jstate{z} \vert \ensuremath{\mathcal{D}}_i) \cdot F_{\jstate{z}}(n,c). \end{align*}\end{linenomath} Here, $\ensuremath{\mathcal{D}}_i$ denotes the i-th sample in the dataset, and $\jstate{z} \models \ensuremath{\mathcal{D}}_i$ are the possible completions of sample $\ensuremath{\mathcal{D}}_i$. For example, in Figure~\ref{fig:fair-pc}, the expected flows of the edges highlighted in red and green, given a sample $\{S\!=\!1,d,\jstate{x}\}$, are $\Pr_{\ensuremath{\mathcal{C}}}(D_f\!=\!1 \mid S\!=\!1,d,\jstate{x})$ and $\Pr_{\ensuremath{\mathcal{C}}}(D_f\!=\!0 \mid S\!=\!1,d,\jstate{x})$, respectively. Similar to circuit flows, the expected flows for all edges can be computed with a single bottom-up and top-down evaluation of the circuit. Then, using expected flows, we can perform both the E- and M-step by the following closed-form solution. \begin{prop}\label{prop:em} Given a smooth, decomposable, and deterministic circuit with parameters $\mathcal{\boldsymbol{\theta}}$ and an incomplete data $\ensuremath{\mathcal{D}}$, the parameters for the next EM iteration are given by: \begin{linenomath}\begin{equation*} \theta_{n,c}^{\text{(new)}} = \EF_{\ensuremath{\mathcal{D}},\mathcal{\boldsymbol{\theta}}}(n,c) / \sum_{c\in\ensuremath{\mathsf{ch}}(n)} \EF_{\ensuremath{\mathcal{D}},\mathcal{\boldsymbol{\theta}}}(n,c). \end{equation*}\end{linenomath} \end{prop} Note that this is very similar to the ML estimate from complete data in Equation~\ref{eq:param}, except that expected flows are used instead of circuit flows. Furthermore, the expected flow can be computed even if each data sample has different variables missing; thus, the EM method can naturally handle missing values for other features as well. We refer to Appendix~\ref{sec:app-EF} for details on computing the expected flows and proof for above proposition. \paragraph{Initial parameters using prior knowledge} Typically the EM algorithm is run starting from randomly initialized parameters. While the algorithm is guaranteed to improve the likelihood at each iteration until convergence, it still has the problem of multiple local maxima and identifiability, especially when there is a latent variable involved~\citep{PGM}. Namely, we can converge to different learned models with similar likelihoods but different parameters for the latent fair variable, thus resulting in different behaviors in the prediction task. For example, for a given fair distribution, we can flip the value of $D_f$ and the parameters accordingly such that the marginal distribution over $S,\rvars{X},D$, as well as the likelihood on the dataset, is unchanged. However, this clearly has a significant impact on the predictions which will be completely opposite. Therefore, instead of random initialization, we encode prior knowledge in the initial parameters that determine $\Pr(D \vert S, D_f)$. In particular, it is obvious that $D_f$ should be equal to $D$ if the observed labels are already fair. Furthermore, for individual predictions, we would want $D_f$ to be close to $D$ as much as possible while ensuring fairness. Thus, we start the EM algorithm from a conditional probability $\Pr(d \vert s,d_f) = [d=d_f]$. \subsection{Structure Learning} \label{sec:str-learning} Lastly, we describe how a fair probabilistic circuit structure is learned from data. As described previously, top layers of the circuit are fixed in order to encode the independence assumptions of our latent variable approach. On the other hand, the sub-circuits over features $\rvars{X}$ can be learned to best fit the data. We adopt the \textsc{Strudel}\ algorithm to learn the structures~\citep{DangPGM20}.\footnote{PCs learned this way also satisfy properties such as structured decomposability that are not necessary for our use case.} Starting from a Chow-Liu tree initial distribution~\citep{ChowLiu}, \textsc{Strudel}\ performs a heuristic-based greedy search over possible candidate structures. At each iteration, it first selects the edge with the highest circuit flow and the variable with the strongest dependencies on other variables, estimated by the sum of pairwise mutual informations. Then it applies the \textit{split} operation -- a simple structural transformation that ``splits'' the selected edge by introducing new sub-circuits conditioned on the selected variable. Intuitively, this operation aims to model the data more closely by capturing the dependence among variables (variable heuristic) appearing in many data samples (edge heuristic). After learning the structure, we update the parameters of the learned circuit using EM as described previously. \section{Experiments} \label{sec:exp} We now empirically evaluate our proposed model \textsc{FairPC}\ on real-world benchmark datasets as well as synthetic data. \paragraph{Baselines} We first compare \textsc{FairPC}\ to three other probabilistic methods: fair naive Bayes models (\textsc{2NB}\ and \textsc{LatNB}) by \citet{calders2010three} and PCs without latent variable (\textsc{NLatPC}) as described in Sec~\ref{sec:model}. We also compare against existing methods that learn discriminative classifiers satisfying group fairness: (1) \textsc{FairLR}~\citep{zafar2017fairness}, which learns a classifier subject to co-variance constraints; (2) \textsc{Reduction}~\citep{agarwal2018reductions}, which reduces the fair learning problem to cost-sensitive classification problems and learns a randomized classifier subject to fairness constraints; and (3) \textsc{Reweight}~\citep{jiang2020identifying} which corrects bias by re-weighting the data points. All three methods learn logistic regression classifiers, either with constraints or using modified objective functions. \paragraph{Evaluation criteria} For predictive performance, we use accuracy and F1 score. Note that models with latent variables use the latent fair decision $D_f$ to make predictions, while other models directly use $D$. Moreover, in the real-world datasets, we do not have access to the fair labels and instead evaluate using the observed labels which may be ``noisy'' and biased. We emphasize that the accuracy w.r.t\ unfair labels is not the goal of our method, as we want to predict the true target, not its biased proxy. Rather, it measures how similar the latent variable is to the observed labels, thereby justifying its use as fair decision. To address this, we also evaluate on synthetic data where fair labels can be generated. For fairness performance, we define the discrimination score as the difference in average prediction probability between the majority and minority groups, i.e., $\Pr(D_f\!=\!1\vert S\!=\!0)-\Pr(D_f\!=\!1\vert S\!=\!1)$ estimated on the test set. \begin{figure}[t] \centering \begin{tabular}{ccc} \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/compas_Log-likelihood.pdf}& \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/compas_F1.pdf}& \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/compas_Discrimination.pdf}\\ \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/adult_Log-likelihood.pdf}& \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/adult_F1.pdf}& \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/adult_Discrimination.pdf}\\ \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/german_Log-likelihood.pdf}& \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/german_F1.pdf}& \includegraphics[width=0.28\columnwidth,trim=0cm 1.5cm 3.5cm 0.5cm]{figs/histograms/german_Discrimination.pdf}\\ \end{tabular} \caption{Comparison of fair probability distributions. \textbf{Columns:} log-likelihood, F1-score, discrimination score (higher is better for the first two; lower is better for last). \textbf{Rows:} COMPAS, Adult, German datasets. The four bars in each graph from left to right are: 1) \textsc{2NB}, 2) \textsc{LatNB}, 3) \textsc{NLatPC}, 4) \textsc{FairPC}. \label{fig:exp-realworld-4base}} \end{figure} \subsection{Real-World Data} \label{sec:exp-realworld} \paragraph{Data} We use three datasets: COMPAS~\cite{compas}, Adult, and German~\cite{Dua2019}, which are commonly studied benchmarks for fair ML. They contain both numerical and categorical features and are used for predicting recidivism, income level, and credit risk, respectively. We wish to make predictions without discrimination with respect to a protected attribute: ``sex'' for Adult and German, and ``ethnicity'' for COMPAS. As pre-processing, we discretize numerical features (e.g.\ age), remove unique or duplicate features (e.g.\ names of individuals), and remove low frequency counts. \paragraph{Probabilistic methods} We first compare against probabilistic methods to illustrate the effects of using latent variables and learning more expressive distributions. Figure~\ref{fig:exp-realworld-4base} summarizes the result. The bars, from left to right, correspond to \textsc{2NB}, \textsc{LatNB}, \textsc{NLatPC}, and \textsc{FairPC}. First and last two bars in each graph correspond to NB and PC models, respectively. Blue bars denote non-latent model, and yellow/orange denote latent-variable approach. In terms of log-likelihoods, both PC-based methods outperform NB models, which aligns with our motivation for relaxing the naive Bayes assumption---to better fit the data distribution. Furthermore, models with latent variables outperform their corresponding non-latent models, i.e., \textsc{LatNB}\ outperforms \textsc{2NB}\ and \textsc{FairPC}\ outperforms \textsc{NLatPC}. This validates our argument made in Section~\ref{sec:model} that the latent variable approach can achieve higher likelihood than enforcing fairness directly in the observed label. Next, we compare the methods using F1-score as there is class imbalance in these datasets. Although it is measured with respect to possibly biased labels, \textsc{FairPC}\ achieves competitive performance, demonstrating that the latent fair decision variable still exhibits high similarity with the observed labels. Lastly, \textsc{FairPC}\ achieves the lowest discrimination scores in COMPAS and Adult datasets by a significant margin. Moreover, as expected, PCs achieve lower discrimination scores than their counterpart NB models, as they fit the data distribution better. \begin{figure} \centering \begin{tabular}{ll} \includegraphics[width=0.49\columnwidth]{figs/rw-benchmark/compas_test_Acc.pdf}& \includegraphics[width=0.49\columnwidth]{figs/rw-benchmark/compas_test_F1.pdf}\\ \includegraphics[width=0.49\columnwidth]{figs/rw-benchmark/adult_test_Acc.pdf}& \includegraphics[width=0.49\columnwidth]{figs/rw-benchmark/adult_test_F1.pdf}\\ \includegraphics[width=0.49\columnwidth]{figs/rw-benchmark/german_test_Acc.pdf}& \includegraphics[width=0.49\columnwidth]{figs/rw-benchmark/german_test_F1.pdf} \end{tabular} \caption{Predictive performance (y-axis) vs.\ discrimination score (x-axis) for \textsc{FairPC}\ and fair classification methods (\textsc{FairLR}, \textsc{Reduction}, \textsc{Reweight}), in addition with two trivial baselines (\textsc{Rand}\ and \textsc{LR}). \textbf{Columns:} accuracy, F1-score. \textbf{Rows:} COMPAS, Adult, German datasets. \label{fig:exp-rw-benchmark}} \end{figure} \paragraph{Discriminative classifiers} Next we compare \textsc{FairPC}\ to existing fair classification methods. Figure~\ref{fig:exp-rw-benchmark} shows the trade-off between predictive performance and fairness. We add two other baselines to the plot: \textsc{Rand}, which makes random predictions, and \textsc{LR}, which is an unconstrained logistic regression classifier. They represent the two ends of the fairness-accuracy tradeoff. \textsc{Rand}\ has no predictive power but low discrimination, while \textsc{LR}\ has high accuracy but unfair. Informally, the further above the line between these baselines, the better the method optimizes this tradeoff. On COMPAS and Adult datasets, our approach achieves a good balance between predictive performance and fairness guarantees. In fact, it achieves the best or close to best accuracy and F1-score, again showing that the latent decision variable is highly similar to the observed labels even though the explicit objective is not to predict the unfair labels. However, on German dataset, while \textsc{FairLR}\ and \textsc{Reweight}\ achieve the best performance on average, the estimates for all models including the trivial baselines are too highly noisy to draw a statistically significant conclusion. This may be explained by the fact that the dataset is relatively small with 1000 samples. \subsection{Synthetic Data} \label{sec:exp-synthetic} As discussed previously, ideally we want to evaluate against the true target labels, but they are generally unknown in real-world data. Therefore, we also evaluate on synthetic data with fair ground-truth labels in order to evaluate whether our model indeed captures the hidden process of bias and makes accurate predictions. \paragraph{Generating Data} We generate data by constructing a fair PC $\ensuremath{\mathcal{C}}_{true}$ to represent the ``true distribution'' and sampling from it. The process that generates biased labels $d$ is represented by the following (conditional) probability table: \begin{center} \scalebox{0.76}{ \footnotesize \begin{tabular}{c|cc||c|cccc} \toprule $\cdot$ & $D_f$ & $S$ & $d_f, s$ & 1,1 & 1,0 & 0,1 &0,0\\ \midrule \normalsize $\Pr(\cdot\!=\!1)$ & 0.5 & 0.3 & $\Pr(D\!=\!1\mid D_f\!=\!d_f,S\!=\!s)$& 0.8 & 0.9 & 0.1 & 0.4 \\ \bottomrule \end{tabular} } \end{center} Here, $S=1$ is the minority group, and the unfair label $D$ is in favor of the majority group: $D$ is more likely to be positive for the majority group $S\!=\!0$ than for $S\!=\!1$, for both values of fair label $D_f$ but at different rates. The sub-circuits of $\ensuremath{\mathcal{C}}_{true}$ over features $\rvars{X}$ are randomly generated tree distributions, and their parameters are randomly initialized with Laplace smoothing. We generated different synthetic datasets with the number of non-sensitive features ranging from 10 to 30, using 10-fold CV for each. \begin{figure}[t] \centering \begin{tabular}{cc} \includegraphics[width=0.45\columnwidth]{figs/synthetic-basemodel.pdf}& \includegraphics[width=0.45\columnwidth]{figs/synthetic-benchmark.pdf}\\ \end{tabular} \captionof{figure}{\label{fig:exp-sync}Accuracy (y-axis) vs.\ discrimination score (x-axis) on synthetic datasets. We compare \textsc{FairPC}\ with \textsc{2NB}, \textsc{LatNB}, \textsc{NLatPC}\ (left) and with \textsc{Reduction}, \textsc{Reweight}, \textsc{FairLR}\ (right). Each dot is a single run on a generated dataset using the method indicated by its color.} \end{figure} \paragraph{Results} We first test \textsc{FairPC}, \textsc{LatNB}, \textsc{NLatPC}\ and \textsc{NLatPC}\ on the generated datasets. Figure~\ref{fig:exp-sync} (left) illustrates the accuracy and discrimination scores on separate test sets with fair decision labels. In terms of accuracy, PCs outperform NBs, and latent variable approaches outperform non-latent ones, which shows that adopting density estimation to fit the data and introducing a latent variable indeed help improve the performance. When comparing the average discrimination score for each method, \textsc{2NB}\ and \textsc{NLatPC}\ always have negative scores, showing that the non-latent methods are more biased towards the majority group; while \textsc{LatNB}\ and \textsc{FairPC}\ are more equally distributed around zero on the x-axis, thus demonstrating that a latent fair decision variable helps to correct this bias. While both latent variable approaches achieve reasonably low discrimination on average, \textsc{FairPC}\ is more stable and has even lower average discrimination score than \textsc{LatNB}. Moreover \textsc{FairPC}\ also outperforms the other probabilistic methods in terms of likelihood; see Appendix~\ref{sec:app-exp}. We also compare \textsc{FairPC}\ to \textsc{FairLR}, \textsc{Reduction}, and \textsc{Reweight}, the results visualized in Figure~\ref{fig:exp-sync} (right). Our method achieves a much higher accuracy w.r.t.\ the generated fair labels; for instance, the average accuracy of \textsc{FairPC}\ is around 0.17 higher than that of \textsc{FairLR}. Also, we are still being comparable in terms of discrimination score, illustrating the benefits of explicitly modeling the latent fair decision. \subsection{Additional experiments} Appendix~\ref{sec:app-exp} includes learning curves, statistical tests, and detailed performance of our real-world data experiments, as well as the following additional experiments. We empirically validated that initializing parameters using prior knowledge as described in Section~\ref{sec:param-learn} indeed converges closer to the true distribution of $\Pr(D \vert S,D_f)$ than randomly initializing parameters. In addition, as mentioned in Section~\ref{sec:param-learn}, our method can be applied even on datasets with missing values, with no change to the algorithm. We demonstrate this empirically and show that our approach still gets comparably good performance for density estimation. \section{Conclusion} In this paper, we proposed a latent variable approach to learning fair distributions that satisfy demographic parity, and developed an algorithm to learn fair probabilistic circuits from incomplete data. Experimental evaluation on simulated data showed that our method consistently achieves the highest log-likelihoods and a low discrimination score. It also accurately predicts true fair decisions, and even on real-world data where fair labels are not available, our predictions remain close to the unfair ones. \subsubsection*{Acknowledgments} This work is partially supported by NSF grants \#IIS-1943641, \#IIS-1633857, \#CCF-1837129, DARPA grant \#N66001-17-2-4032, a Sloan Fellowship, Intel, and Facebook.
{'timestamp': '2020-09-22T02:01:55', 'yymm': '2009', 'arxiv_id': '2009.09031', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09031'}
arxiv
\section{Introduction} Linear TV programs play crucial roles in our daily lives. With the quickly increasing number of TV channels and programs, it is important to develop effective recommender systems for TV users. Although the development of recommender systems has been stimulated by the rapid growth of information on the Internet, and many algorithms have been successfully applied to various online services (e.g., music and video streaming services)~\cite{Gomez-Uribe16, Yang2018,Chen2019}, little has been done for personalized TV recommendation (TV Rec) in the literature. Most well-developed recommendation algorithms are not applicable for such a recommendation problem due to the following two key challenges of TV Rec: (1) Complete-item cold start: Unlike video on demand (VOD), new TV programs are released on a daily basis (although some drama or movies are replayed, they usually have different titles or descriptions);\footnote{Another practical challenge is that the programs that share common content do not share an identical ID, which rules out directly adopting collaborative filtering or matrix factorization in real-world scenarios.} (2) Context awareness: user viewing behavior for TV programs strongly depends on their conditions (e.g., time and mood); for instance, watching news during dinner but preferring sports in the morning. To address the first challenge, some studies adopt content-based approaches combined with collaborative filtering (CF) for TV Rec~\cite{ali2004tivo,cotter2000ptv,fernandez2006avatar,Smyth1999,david2012}. However, these approaches do not consider the second key characteristic---context awareness---in TV Rec, for which another line of work focuses mainly on characterizing users' time-aware preferences~\cite{ardissono2004user,turrin2014time,david2012,Yu17,Kim2018ATR}. Although, these studies model users' time-aware preferences regarding channels and program genres, they do not precisely reflect users' viewing preferences regarding program content. This is due to the fact that users' access to channels also depends on their viewing habits or location, and that genres are merely coarse-grained information about programs and thus provide little information about program content. Moreover, ~\cite{Hsu2007} further accounts user moods but such user data is difficult to obtain and even harder to measure. To address the above two challenges within a unified framework, we propose a two-stage ranking approach for TV Rec which consists of two components: one to model viewing behavior and the other for viewing preferences. Specifically, viewing behavior refers to users' viewing patterns regarding time and TV channels, whereas viewing preferences refers to preferences regarding the content of TV programs. For the former, we adopt a finer granularity in terms of time than previous work (e.g., days$\times$hours in \cite{ardissono2004user,turrin2014time}), whereas for the latter, we leverage textual information about programs to better model user viewing preferences. Moreover, inspired by the capabilities and limitations of the two components, we propose fusing them with a simple yet effective two-stage ranking algorithm that locates potential candidates based on the first component and then further ranks them based on the second component. Also note that in the literature, this is the first work to formally define the problem of TV Rec and provide a unified approach to capture both user viewing behavior and preferences. Empirical results on a real-world TV dataset demonstrate its effectiveness in recommendation; at the same time, this approach is advantageous and practical for real-world applications due to its time-efficient and parameter-free design. \section{Methodology} \label{sec:methodology} \subsection{Problem Formulation} Personalized TV recommendation (TV Rec) is the task of recommending yet-to-be-released TV programs to a group of users. To properly formulate the problem and our proposed method, we first define three terms: 1) weekly time slot, 2) interaction tensor, and 3) program meta information required for TV Rec. With these definitions, we formalize personalized TV Rec as a top-$k$ recommendation problem given user-implicit feedback. \begin{definition}[{\bf Weekly time slot}] A weekly time interval can be equally divided into $n$ weekly time slots, each of which is denoted as $w_i=(t_i,t_{i+1}]$, where $t_i$ ($t_{i+1}$) denotes the beginning time (the end time, respectively) of the $i$-th time slot. Together, all of the time slots compose set $W=\{ w_i|1\leq i \leq n\}$. Thus, any given timestamp $\mathbf{s}\in S$ can be projected onto a weekly time slot $w_{\mathcal{T}(\mathbf{s})} \in W$ by function $\mathcal{T}(\cdot):S\rightarrow\{1,\cdots,n\}$, where $S$ denotes a set of arbitrary timestamps. \end{definition} For example, when we divide a week into 168 time slots (i.e., one hour for each time slot), we have $W=\{w_1=[\text{Mon 00:00}, \text{Mon 01:00}),\cdots, w_{168}=[\text{Sun 23:00}, \text{Mon 00:00}) \}$, in which the specific timestamp ``May 11, 2020, 05:30 (Mon)'' belongs to the 6th time slot, $w_6$. Note that a given time span $[\mathbf{s},\mathbf{e}]$ can also be projected onto a set of time slots $\{ w_j |\mathcal{T}(\mathbf{s})\leq j\leq \mathcal{T}(\mathbf{e}) \}$. Also note that in our later empirical studies, we adopt a finer granularity in terms of time (i.e.,~15 minutes as the length of the time slot) than prior art. \begin{definition} [{\bf Interaction tensor}] Let $U$, $I$, and $C$ denote the sets of users, TV programs, and TV channels, respectively. An interaction tensor, denoted as $\mathcal{A}=(a_{u,i,w,c})\in \mathbb{R}^{|U|\times |I|\times |W|\times |C|}$, represents user-item associations through a certain channel within a certain weekly time slot, where $a_{u,i,w,c}$ denotes the weight of the association. Note that the tensor is binary for implicit feedback; that is, if user $u\in U$ views program $i\in I$ played in channel $c\in C$ within time slot $w\in W$, $a_{u,i,w,c}=1$; otherwise, $a_{u,i,w,c}=0$. \end{definition} \begin{definition}[{\bf Program meta information}] \label{def:meta} Given a set of TV programs $I$, meta information for each $i\in I$ records that program $i$ is broadcast by channel $\mathrm{CH}({i}) \in C$ at the time interval $[\mathbf{s}_i,\mathbf{e}_{i}]$ with the content information $\mathrm{CNT}(i)$, where $\mathrm{CH}(\cdot)$ and $\mathrm{CNT}(\cdot)$ are the projection functions respectively mapping program $i$ to its channel and its textual information (e.g., title, artists, and abstract). \end{definition} \begin{problem} \label{def:problem setting} \textbf{Top-$k$ TV Recommendation from Implicit Feedback.} Let $I_{\rm train}$ and $I_{\rm test}$ denote the sets of TV programs broadcast in the past (training data) and in the future (test data), respectively; note that for the problem of TV Rec, $I_{\rm train}\bigcap I_{\rm test}= \emptyset$. Given a historical interaction tensor $\mathcal{A}_{\rm train}=(a_{u,i,w,c}) \in \mathbb{R}^{|U|\times |I_{\rm train}|\times|W| \times |C|}$, for each user $u \in U$, we identify the top-$k$ programs from the set of yet-to-be-released (new) programs $I_{\rm test}$ by leveraging the information from $\mathcal{A}_{\rm train}$ and meta information of $I_{\rm train}\bigcup I_{\rm test}$. \end{problem} \subsection{Proposed Method} With a TV recommender system, we seek to leverage historical viewing logs and content information of programs to infer two user characteristics: (1) behavior and (2) preferences, which are addressed in Sections~\ref{sec:behavior} and~\ref{sec:preference}, respectively. We then propose a simple yet effective two-stage ranking method in Section~\ref{sec:algorithm} that takes into account both user characteristics, thereby fusing user viewing habits and preferences into the modeling process. \subsubsection{Viewing behavior}\label{sec:behavior} Here, we define the so-called \emph{viewing behavior} of users based on the following observations. As suggested by \cite{turrin2014time}, most TV users exhibit predictable viewing behavior strongly connected to weekly time slots and TV channels. Intuitively, users prefer to watch TV during their leisure time, which heavily depends on their work and lifestyle. In addition, users tend to switch between a limited number of channels even though they have a large number to choose from. Thus a user's TV viewing behavior can be defined as the probability distribution of watching TV on a given channel at a given time. Given a historical user-item interaction tensor $\mathcal{A}_{\rm train}=(a_{u,i,w,c}) \in \mathbb{R}^{|U|\times |I_{\rm train}|\times|W| \times |C|}$, we extract each user $\mathbf{u}$'s viewing behavior by computing his or her viewing probability distribution over weekly time slots $W$ and TV channels $C$. Formally speaking, we represent each $\mathbf{u}$'s viewing behavior as a probability distribution matrix, $\mathcal{B}^{\mathbf{u}}=(b^{\mathbf{u}}_{\mathbf{w},\mathbf{c}}) \in \mathbb{R}^{\left| W \right| \times \left| C \right|} $, where each element $b^{\mathbf{u}}_{\mathbf{w},\mathbf{c}}$ is defined as \begin{equation} \label{eq:watching_behavior} b^{\mathbf{u}}_{\mathbf{w},\mathbf{c}}= \left( \sum\limits_{i,w,c}a_{\mathbf{u},i,w,c} \mathbbm{1}_{ \{ w=\mathbf{w} \} } \mathbbm{1}_{ \{ c=\mathbf{c}\} } \right)\left/ \left(\sum\limits_{i, w, c }a_{\mathbf{u},i, w, c } \right)\right. . \end{equation} Additionally, in order to recommend yet-to-be-released TV programs for users based on their viewing behavior, we construct the matrix $\mathcal{B}^{\mathbf{i}'}=(b^{\mathbf{i}'}_{\mathbf{w},\mathbf{c}}) \in \mathbb{R}^{\left| W \right| \times \left| C \right|} $ for each new item $\mathbf{i}' \in I_{\rm }$ using the meta information defined in Definition~\ref{def:meta}, where $b^{\mathbf{i}'}_{\mathbf{w},\mathbf{c}}= \mathbbm{1}_{ \{ \mathbf{w} \in \{ w_j |\mathcal{T}(\mathbf{s}_{\mathbf{i}'})\leq j\leq \mathcal{T}(\mathbf{e}_{\mathbf{i}'}) \} \} } \cdot \mathbbm{1}_{ \{ \mathrm{CH}(\mathbf{i}')=\mathbf{c}\} } $. Recall that $[\mathbf{s}_{\mathbf{i}'},\mathbf{e}_{\mathbf{i}'}]$ denotes the time interval during which program $\mathbf{i}'$ is broadcast. Finally, we compute the matching score between $\mathbf{u}$ and $\mathbf{i}^{'}$ given viewing behavior as \begin{equation} \label{eq:watching_behavior_score} \begin{aligned} s_{\mathbf{u},\mathbf{i'}}^{b} =\mathrm{MAX}\left(\mathcal{B}^{\mathbf{u}} \odot \mathcal{B}^{\mathbf{i'}}\right) \text{ and } (w,c) = {\rm IdxMax}\left(\mathcal{B}^{\mathbf{u}} \odot \mathcal{B}^{\mathbf{i'}}\right), \end{aligned} \end{equation} where $\odot$ denotes element-wise multiplication between two matrices, $\mathrm{MAX}(\cdot)$ is the function to extract the maximum element in a matrix, and ${\rm IdxMax}(\cdot)$ locates the indices of the maximum element.\footnote{In practice, there is no need to conduct the element-wise multiplication to get $s^{b}_{\mathbf{u},\mathbf{i}'}$; instead, for each $\mathbf{i}'$, $s^{b}_{\mathbf{u},\mathbf{i}'}$ is the maximum in the set $\{b^{\mathbf{u}}_{\mathbf{w},\mathbf{c}}| \mathbf{w} \in \{ w_j |\mathcal{T}(\mathbf{s}_{\mathbf{i}'})\leq j\leq \mathcal{T}(\mathbf{e}_{\mathbf{i}'})\}\wedge \mathbf{c}={\rm CH}(\mathbf{i}') \}$.} Note that $s_{\mathbf{u},\mathbf{i'}}^{b}$ is the estimated probability that user $\mathbf{u}$ views item $\mathbf{i'}$ given his or her historical viewing behavior. \subsubsection{Viewing Preferences}\label{sec:preference} In contrast to the aforementioned user behavior, a user's preferences are usually associated with the content of his or her preferred items. We formally define a user's \emph{viewing preferences} as the program contents he or she prefers to watch, which we represent in the proposed method using the textual information of programs. Note that as with a typical TV Rec scenario, all candidate items in $I_{\rm test}$ for recommendation are new, which is the same as the complete cold-start problem in typical recommender systems. Such a problem is commonly addressed using content-based approaches~\cite{david2012, Chou2016}; likewise, we here use textual item information to locate new items for recommendation. For each program $\mathbf{i} \in I_{\rm train}$, we map its content information to a $d$-dimensional embedding~$h_{\mathbf{i}}$ using a text encoder~$\mathcal{E}$: \begin{equation} \label{eq:text_enc} {h}_{\mathbf{i}}=\mathcal{E}\left(\mathrm{CNT}(\mathbf{i})\right) \in \mathbb{R}^{d}. \end{equation} In order to map user~$\mathbf{u}$'s preferences to the same embedding space, we gather all the programs associated with $\mathbf{u}$ in the training data, after which we compute the average pooling over their embeddings to obtain $\mathbf{u}$'s viewing preferences~$h_{\mathbf{u}}$ as \begin{equation} h_{\mathbf{u}}= \frac{\sum_{i\in I^{\mathbf{u}}_{\rm train}} h_i}{|I_{\rm train}^{\mathbf{u}}|} \in \mathbb{R}^{d}, \label{eq:gpreference} \end{equation} where $I^{\mathbf{u}}_{\rm train}= \{ i\,|\,i \in I_{\rm train} \wedge \exists\, w\in W, c\in C\, a_{\mathbf{u},i,w,c}=1\}$. Similarly, for each item $\mathbf{i}' \in I_{\rm test}$, we project its content information using the same text encoder~$\mathcal{E}$ from Eq.~(\ref{eq:text_enc}). Finally, the matching score for $\mathbf{u}$ and $\mathbf{i}^{'}$ in terms of of viewing preferences is computed as \begin{equation} \label{eq:preference_score} s^{p}_{\mathbf{u},\mathbf{i}'}=\langle h_{\mathbf{u}}, {h_{\mathbf{i}'}}\rangle, \end{equation} where $\langle\cdot,\cdot\rangle$ denotes the dot product of two vectors. In addition, for TV Rec, it is common that multiple users (i.e., family members) share the same account, under which these users may have different viewing preferences and watch TV at different weekly time slots. For example, whereas children enjoy watching cartoons after school, parents prefer to watch news or dramas after work. We address this by further tailoring the viewing preferences of an ``account'' to time-aware preferences; that is, for each account~$\mathbf{u}\in U$ and each time slot~$\mathbf{w}\in W$, we have \begin{equation} h_{\mathbf{u}, \mathbf{w}}= \frac{\sum_{i \in I^{\mathbf{u}, \mathbf{w}}_{\rm train}}h_i}{|I_{\rm train}^{\mathbf{u}, \mathbf{w}}|} \in \mathbb{R}^{d}, \label{eq:tpreference} \end{equation} where $I^{\mathbf{u},\mathbf{w}}_{\rm train}= \{ i\,|\,i \in I_{\rm train}\wedge \exists\,c\in C\, a_{\mathbf{u},i,\mathbf{w},c}=1\}$. With these fine-grained viewing preferences, the score of user~$\mathbf{u}$ for item $\mathbf{i}'$ becomes \begin{equation} \label{eq:time_preference_score} s^{p}_{\mathbf{u},\mathbf{i}'}=\langle h_{\mathbf{u},{w}_j}, {h_{\mathbf{i}'}}\rangle, \end{equation} where ${w}_{j}\in W$ denotes the time slot in which item $\mathbf{i}'$ begins playing; i.e., $j=\mathcal{T}(\mathbf{s}_{\mathbf{i}'})$. \subsubsection{Two-stage Ranking}\label{sec:algorithm} In this section, we propose a two-stage ranking approach that leverages the above two features---user viewing behavior and user viewing preferences---for TV Rec. Before describing the proposed approach, we make observations and lay out the motivation of our design based on the limitations of each feature as follows. \begin{itemize}[leftmargin=*] \item \textbf{Viewing behavior}: In practice, there are usually multiple programs broadcast on the same channel at the same time slot; in this case, these programs are given the same matching score for a user in terms of his or her viewing behavior. Thus, recommendation that is based solely on user viewing behavior chooses all the programs from a certain channel and time slot.\footnote{When multiple programs have the same score, we assign a higher rank to programs with earlier starting times.} However, in a real-world scenario, it is unlikely that a user at a given time slot watches more than one TV program, especially for short time slots;\footnote{In the experiments, we adopted 15 minutes as our time slot interval, an optimal setting for using only viewing behavior for recommendation; even in this case, each time slot nevertheless contains 1.5 programs on average.} in this case recommending multiple programs from the same channel at a given time slot could lead to poor recommendation quality. \item \textbf{Viewing preferences}: Although user preferences are useful for recommendation, recommending linear TV programs based solely thereon usually results in low accuracy. For example, if an office worker enjoys watching action movies during the weekend, it is unreasonable to recommend action movies at midnight during weekdays. \end{itemize} Based on the above characteristics and limitations, we propose two-stage ranking to leverage the two features for TV Rec, as detailed in Algorithm~\ref{alg:ts_ranking}. Briefly speaking, for each user~$\mathbf{u}$, we propose first ranking the program set~$I_{\rm test}$ according to viewing behavior~($s^{b}_{\mathbf{u},\mathbf{i}'}$) (lines 2--6); then, at the second stage (lines 7--15), for those programs broadcast on the same channel at the same weekly time slot, we choose only one program among them according to the user's viewing preferences~($s^p_{\mathbf{u},\mathbf{i}'}$). Note that we put the model for viewing behavior at the first stage as previous studies indicate that the viewing behavior usually dominates the recommendation performance~\cite{turrin2014time}, which is also consistent with the finding in our later experiments. This approach boasts two advantages: 1) it is parameter-free, and 2) it is computationally efficient as only a limited number of preference matching scores~$s^{b}_{\textbf{u},\textbf{i}'}$ are computed at the second stage. Thus, the computational cost of the proposed two-stage ranking method is only slightly higher than for recommendation based solely on viewing behavior; this is also discussed in later experiments. \begin{algorithm} \small \caption{Two-stage Ranking} \label{alg:ts_ranking} \KwIn{ $\mathcal{A}_{\rm train}$, $I_{\rm train}$, $I_{\rm test}$, $k$, $\mathbf{u}$} \KwOut{${\hat{I}}^{\mathbf{u}}_{\rm test}$ (set consisting of recommended programs in $I_{\rm test}$ for user $\mathbf{u}$)} $\mathcal{S}^{b} \leftarrow [ ]; \mathcal{S}^{p} \leftarrow []; {\hat{I}}_{\mathbf{u}} \leftarrow []$\\ Construct $\mathcal{B^{\mathbf{u}}}$ with Eq.~(\ref{eq:watching_behavior}) \\ \For {each $\mathbf{i}'$ in $I_{\rm test}$}{ Compute $s^{b}_{\mathbf{u},\mathbf{i'}}$ and $(w, c)$ with Eq.~(\ref{eq:watching_behavior_score})\\ $\mathcal{S}^{b}$.append$\left( \left(\mathbf{i}', (w, c),s^{b}_{\mathbf{u},\mathbf{i}'}\right) \right)$\\ } Sort $\mathcal{S}^{b}$ in ascending order according to $s^{b}_{\mathbf{u},\mathbf{i}'}$\\ \While {$\left(\left|{\hat{I}}^{\mathbf{u}}_{\rm test}\right|< k\right)$}{ $(\mathbf{i}', (w, c),s^{b}_{\mathbf{u},\mathbf{i}'}) \leftarrow\mathcal{S}^{b}$.pop() \\ Compute $h_{{w}_j,\mathbf{u}}$ (or $h_{\mathbf{u}}$), $h_{\mathbf{i}'}$ and $s^p_{\mathbf{u},\mathbf{i}'}$ with Eqs.~(\ref{eq:text_enc})--(\ref{eq:time_preference_score})\\ \If{$\mathcal{S}^p \neq \emptyset$ {\bf and} $(w,c) \neq (w_{0}, c_{0})$}{ Sort $\mathcal{S}^{p}$ in ascending order according to $s^{p}_{\mathbf{u},\mathbf{i}'}$ \\ ${\hat{I}}^{\mathbf{u}}_{\rm test}$.append$\left( \mathcal{S}^{p}.{\rm pop()} \right)$ \\ $\mathcal{S}^{p} \leftarrow []$ \\ } $(w_{0}, c_{0}) \leftarrow (w,c)$ \\ $\mathcal{S}^p$.append$\left( \left(\mathbf{i}', s^{p}_{\mathbf{u},\mathbf{i}'}\right) \right)$ } \KwRet{${\hat{I}}^{\mathbf{u}}_{\rm test}$} \end{algorithm} \vspace{-0.6cm} \section{Experiment} \label{sec:experiment} \subsection{Dataset and Preprocessing} We collected user viewing logs, denoted as $D_{\rm raw}$, from a set of set-top boxes providing linear television service to end users in Japan from Jan 1, 2019 to June 1, 2019. This period comprises a total of 42,301 unique users and 875,550 distinct programs (denoted as $I_{\rm raw}$), where each user was anonymized using a hashed ID. Each log records a channel-switching event for a user, denoted as $d=(u, i, c, t, \Delta t)$, indicating that user~$u$ switched to channel~$c$ broadcasting program~$i$ at UTC timestamp~$t$. Above, $\Delta t$ is the interval between channel-switching events, which can be considered as the duration of the user's viewing of the program. Note that each program was broadcast only once on a channel in the linear TV system. In addition, each program~$i \in I_{\rm raw}$ was associated with its meta information (see Definition~\ref{def:meta}). Given these data logs~$D_{\rm raw}$ and TV programs~$I_{\rm raw}$, we first removed viewing logs whose duration was less than $\Delta_{t_\theta}$ (e.g., 15 minutes in the experiments) to filter out logs where users were just flipping channels rather than watching a program. Formally, we constructed the preprocessed data logs~$D=\{d=(u,i,c,t,\Delta t)| d\in D_{\rm raw} \wedge \Delta t \geq \Delta t_{\theta}\}$. We then generated training and testing sets by splitting the processed data logs~$D$ based on a timestamp~$t_{\rm split}$ and extracting the logs of period~$T_{\rm train}=[t_{\rm split}-\Delta{t_{\rm train}},t_{\rm split})$ for training (denoted as $D_{\rm train}$) and $T_{\rm test}=[t_{\rm split},t_{\rm split}+\Delta{t_{\rm test}})$ for testing ($D_{\rm test}$); thus $I_{\rm train}=\{i\,|\,i\in I_{\rm raw}, \mathbf{s}_i \in T_{\rm train}\}$ and $I_{\rm test}=\{i\,|\,i\in I_{\rm raw}, \mathbf{s}_i \in T_{\rm test}\}$. In our experiments, we constructed four datasets with different values for $t_{\rm split}$ and set $\Delta t_{\rm train}$, $\Delta t_{\rm test}$ to 90 and 7 days, respectively. Table~\ref{table: data stat} contains the dataset statistics. With user logs in $D_{\rm train}$, the interaction tensor is $\mathcal{A}_{\rm train}=(a_{\mathbf{u},\mathbf{i},\mathbf{w},\mathbf{c}}) \in \mathbb{R}^{|U|\times |I_{\rm train}|\times|W| \times |C|}$, where $a_{\mathbf{u},\mathbf{i},\mathbf{w},\mathbf{c}}= \sum_{ (u,i,c,t,\Delta t)\in D_{\rm train}} \mathbbm{1}_{\left\{\left(u,i,w_{\mathcal{T}(t)},c\right)=\left(\mathbf{u},\mathbf{i},\mathbf{w},\mathbf{c}\right)\right\}}.$ Here we consider only user sets $U$ appearing at least once both in $D_{\rm train}$ and $D_{\rm test}$. The length of each weekly time slot~$w_i \in W$ was set to 15 minutes by setting $n$ to $672$. For validation, we adopted user-implicit feedback extracted from $I_{\rm test}$; that is, for each user~$\mathbf{u} \in U$, we constructed program set~${I}^{\mathbf{u}}_{\rm test}=\{i\,|\,i\in I_{\rm test} \wedge (\mathbf{u},i,c,t,\Delta t)\in D_{\rm test} \}$ as our ground truth. \input{data_stat} \subsection{Baselines and Experimental Setup} We first built two baselines based on viewing behavior and viewing preferences, the user characteristics introduced in Sections~\ref{sec:behavior} and~\ref{sec:preference}, respectively. Note that for viewing preferences, we tokenized the textual information of each program using MeCab,\footnote{\url{ https://taku910.github.io/mecab/}} after which we used the term frequency-inverse document frequency (tf-idf) vectorizer as the text encoder (see $\mathcal{E}(\cdot)$ in Eq.~(\ref{eq:text_enc})) to represent items in $I_{\rm train}\bigcup I_{\rm test}$. In addition, we compared the proposed two-stage ranking approach with a ranking fusion method that combines the recommendations from the above two baselines using reciprocal rank fusion (RRF)~\cite{Cormack09}. In information retrieval (IR), RRF is a simple but effective method for combining document rankings from multiple IR systems. Formally speaking, given a set of items~$I_{\rm test}$ and a set of ranking functions~$\mathcal{K}$, where each $\kappa\in \mathcal{K}$ is a function mapping item~$i \in I_{\rm test}$ to its ranking~$\kappa(i)$, the fusion score for each item~$i$ is computed as $s_{\rm RRF}(i)=\sum_{\kappa\in \mathcal{K}} \frac{1}{\kappa(i)+\eta}$, where $\eta$ is a hyperparameter to reduce the impact of high-ranking items from any of the systems. With the two ranking functions based on viewing behavior and preferences (denoted as $\kappa_{b}$ and $\kappa_{p}$, respectively), we have $s_{\rm RRF}(i)= \frac{1}{\kappa_{b}(i)+\eta}+\frac{1}{\kappa_{p}(i)+\eta}$. Another baseline is an RRF variant with an additional hyperparameter $\xi$ to control the impact of two ranking systems, $s_{\rm RRF}^{\xi}(i)=\frac{\xi}{\kappa_{b}(i)+\eta}+\frac{1-\xi}{\kappa_{p}(i)+\eta}$. We use the following metrics to evaluate our models: (1) nDCG, (2) precision, and (3) recall. For each user~$\mathbf{u} \in U$, we recommend $k=30$ programs among $I_{\rm test}$ and evaluate model performance with cut-offs $N\in\{10,20,30\}$. To fine-tune the hyperparameters for the RRF fusion methods (denoted as RRF and RRF$^\xi$), we randomly selected 10\% of the users in Dataset~1 as the development set and searched $\eta$ and $\xi$ in the range of $\{ 1,2,\cdots 100 \}$ and $\{ 0,0.1,\cdots 1 \}$, respectively, for the best performance in terms of Recall@30. Additionally, to examine the efficiency of each model, we evaluated each model's CPU time cost for inference (seconds/user).\footnote{As the inference time is measured on a per-user basis, the number of threads does not impact the measurement.} For models using viewing preferences (including fusion methods), we computed and indexed $h_{\mathbf{u},\mathbf{w}}$ (or $h_{\mathbf{u}}$) and $h_{\mathbf{i'}}$ in advance; thus, for each user at the inference stage, the computation cost is mainly associated with the dot product between $h_{\mathbf{u},\mathbf{w}}$ (or $h_{\mathbf{u}}$) and $h_{\mathbf{i'}}$ (for all programs $\mathbf{i}' \in I_{\rm test}$). In modeling the viewing behavior, the time cost results are primarily due to the construction of matrix $\mathcal{B}^{\mathbf{u}}$ and the calculation of $s^{b}_{\mathbf{u},\mathbf{i}'}$. \subsection{Quantitative Results} \begin{table*}[t!] \centering \resizebox{1\linewidth}{!}{ \setlength{\tabcolsep}{2.5pt} \begin{tabular}{clcrrrrrrrrrrr} \toprule & &&\multicolumn{3}{c}{$N=10$}&\multicolumn{3}{c}{$N=20$}&\multicolumn{3}{c}{$N=30$}& \\ \cmidrule(lr){4-6} \cmidrule(lr){7-9} \cmidrule(lr){10-12} & &Time-aware& nDCG & Prec. & Recall & nDCG & Prec. & Recall & nDCG & Prec. & Recall & Time\\ \midrule \multicolumn{2}{c}{Behavior}&&35.25&33.79&12.26&34.68&30.42&18.39&34.25&27.97&22.91& $\dagger$\textbf{0.27}\\ \multicolumn{2}{c}{Preferences} & \checkmark&13.79&12.91&4.61&13.96&12.13&7.63&14.11&11.45&9.98&1.45\\ \cdashline{1-13}\\[-0.3cm] \multirow{6}{*}{Fusion}&\multirow{2}{*}{RRF}& & 43.82&38.27&12.89&38.87&30.30&17.97&36.41&26.01&21.59&1.45\\ & &{\checkmark} & 45.99&40.64&13.15&41.02&32.58&18.72&38.25&27.82&22.43&1.46\\ \cdashline{2-13}\\[-0.3cm] &\multirow{2}{*}{RRF$^{\xi}$}& &45.44&39.93&13.69&41.78&33.53&19.66&39.80&29.60&23.83&1.45\\ & &{\checkmark}&47.79&41.90&13.93&43.35&34.65&19.86&41.13&30.53&24.11&1.46\\ \cdashline{2-13}\\[-0.3cm] &\multirow{2}{*}{Two-stage}&&46.32&40.92&13.61&42.61&34.45&19.23&40.54&30.44&23.27&0.30\\ &&{\checkmark}&$\dagger$\textbf{48.92}&$\dagger$\textbf{43.28}&\textbf{14.12}&$\dagger$\textbf{44.90}&$\dagger$\textbf{36.41}&\textbf{19.98}&$\dagger$\textbf{42.64}&$\dagger$\textbf{32.13}&\textbf{24.20}&0.31\\ \bottomrule \end{tabular}% } \caption{Recommendation performance. $\checkmark$ denotes methods using time-aware user preferences, and $\dagger$ denotes statistical significance at $p < 0.05$. } \label{table:main results} \vspace{-1cm} \end{table*} Table~\ref{table:main results} compares model performance in terms of the aforementioned metrics and inference time. In the table, the best result for each column is in boldface; $\dagger$ denotes statistical significance at $p < 0.05$ (paired $t$-test over four datasets) with respect to all other methods, and $\checkmark$ indicates methods using time-aware user preferences (i.e., $h_{\textbf{u},\textbf{w}}$ in Eq.~(\ref{eq:tpreference})) as opposed to global preferences (i.e., $h_{\textbf{u}}$ in Eq.~(\ref{eq:gpreference})). First, the comparison between the methods using only behavior or preferences (denoted as Behavior and Preferences, respectively, in the table and hereafter) is strong evidence that in the TV Rec scenario, user viewing behavior dominates recommendation performance, which underscores the importance of putting the model for viewing behavior at the first stage of the proposed two-stage ranking approach. In addition, note that the inference time cost of Behavior is five times less than that of Preferences. On the other hand, as demonstrated in the table, fusing the two user characteristics significantly boosts ranking performance. Specifically, RRF outperforms Behavior in terms of nDCG and Precision by over 7\% in the low cut-off regions (i.e., $N=\{10, 20\}$). Tuning the impact of Behavior and Preferences (the second row of RRF$^\xi$ with $\xi=0.6$) further improves overall ranking performance in terms of nDCG and precision by over 10\% and recall by over 5\%. However, both RRF and RRF$^\xi$ include exhaustive dot product computation over all programs in $I_{\rm test}$, resulting in a time cost per user approximately equal to that of Preferences. Table~\ref{table:main results} shows that the proposed two-stage ranking consistently outperforms other (fusion) methods in terms of efficiency and the three evaluation metrics. Specifically, the method significantly surpasses the strongest baseline RRF$^{\xi}$ by over 2\% in terms of nDCG and precision when modeling user preferences both globally and in a time-dependent fashion; also note that time-aware preferences better capture user viewing preferences and thus yield better performance. Most importantly, from an efficiency perspective, the time cost of the two-stage ranking shown in the table is much lower than that of the two fusion methods and is approximate to that of Behavior, because in our method, only a limited number of preference matching scores involving the dot product operation are computed at the second stage. Combining such efficiency and the fact that our method is parameter-free, we conclude that the proposed method is much more practical than RRF-based methods. \section{Conclusion} We propose a two-stage ranking approach to fuse two user characteristics---viewing behavior and viewing preferences---in a unified manner for TV Rec. The empirical results on a real-world TV dataset show that our proposed approach consistently outperforms other baseline methods; more importantly, our two-stage ranking approach is parameter-free and efficient at inference, making it applicable and practical to real-world TV Rec scenarios. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-09-21T02:18:13', 'yymm': '2009', 'arxiv_id': '2009.08957', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08957'}
arxiv
\section{Introduction} Solving optimisation problems is at the heart of every scientific discipline to improve our understanding and interpretation of scientific findings. Evolution-based and swarm intelligence search and optimisation have been in remarkable growth over the years to tackle complex problems ranging from scientific research \cite{abraham2006swarm} to industry \cite{sanchez2012industrial} and commerce \cite{freitas2002review}. Hybridizing evolutionary, swarm, and annealing algorithms \cite{grosan2007hybrid} (the focus of this work) is an active area of research, since usually hybrid algorithms can offer several advantages over standalone algorithms in terms of stability, search speed, and exploration capabilities, where these advantages highlight the goals of these hybrid studies. Few examples of successful demonstration of hybrid algorithms in different domains are: (1) genetic algorithm (GA) and particle swarm optimisation (PSO) \cite{kao2008hybrid}, (2) GA and Simulated Annealing (SA) \cite{chen2009hybrid}, (3) GA and SA \cite{ma2014hybrid}, (4) PSO and tabu search \cite{shen2008hybrid}, (5) PSO and evolution strategies (ES) \cite{jamasb2019novel}, and many more. For the authors' interests on nuclear power plant design, evolutionary, swarm, and annealing algorithms have been proposed in several research studies in standalone and hybrid forms to optimise nuclear fuel assemblies and cores of light water reactors \cite{zameer2014core,rogers2009optimization,de2009particle}, to reduce fuel costs and improve nuclear reactor safety \cite{kropaczek1991core}. As improving capabilities of evolutionary and stochastic algorithms in solving optimisation problems is always a research target due to their widely usage, we propose a new algorithm called PESA (\textbf{P}SO, \textbf{E}S, and \textbf{S}A \textbf{A}lgorithm). PESA hybridizes three known optimisation techniques by exchanging their search data on-the-fly, storing all their solutions in a buffer, and replaying them frequently based on their importance. The concept of experience replay was first introduced in deep reinforcement learning (RL) \cite{mnih2015human,schaul2015prioritized} to improve agent learning by replaying relevant state/action pairs weighted by their temporal difference and reward values. Accordingly, we introduce experience replay into evolutionary algorithms to determine whether this concept would improve the performance. First, we hybridize PSO, ES, and SA to create a replay memory with diverse samples by taking the search advantages of each individual algorithm. Next, two modes of experience replay are applied: (1) prioritized replay to enhance exploration capabilities of PESA, and (2) ``backdoor'' greedy replay to improve algorithm exploitation, such that once the search is close to end, PESA prioritizes its main experience. To enhance search speed, PSO, ES, and SA are parallelized during search such that the three algorithms can run simultaneously to collect experiences, before updating the memory and executing the replay. We benchmark PESA against its standalone components: PSO, ES, and SA to show its promise. Variety of commonly used continuous benchmark functions are utilized in this paper, which also have a high dimensional nature to represent realistic optimisation problems. We evaluate PESA performance by its ability to find a known global optima, exploration/exploitation capabilities, and computational efficiency. \section{Methodology} \label{sec:method} The workflow of PESA is sketched in Figure \ref{fig:pesa}, which shows how the algorithms are connected to each other through the replay memory. The choices of PSO, ES, and SA are not arbitrary. PSO \cite{kennedy1995particle} is known to excel in continuous optimisation, ES \cite{beyer2002evolution} (which originated from the genetic algorithms) performs well in both continuous/discrete spaces, while SA \cite{kirkpatrick1983optimization} is introduced to ensure exploration due to its stochastic nature, and more importantly to drive PESA exploitation to the best solution found, as will be described in the next section. \begin{figure}[h] \centering \includegraphics[width=\textwidth]{figures/pesa_arxiv.png} \caption{PESA algorithm workflow. Red arrows represent memory feedback, $\alpha_{backdoor}$ is the probability to use backdoor greedy replay in SA. $\eta$ and $\eta'$ are the number of PSO particles surviving from previous generation and from the memory, respectively. $\mu$ and $\mu'$ are the number of ES individuals surviving from previous generation and from the memory, respectively. $\lambda$ is the full size of ES offspring. All hyperparameters are defined in detail later in this section} \label{fig:pesa} \end{figure} \subsection{Evolutionary, Swarm, and Annealing Computation} \label{sec:evol} Evolution strategies (ES) \cite{beyer2002evolution} are inspired by the theory of natural selection. In this work, the well-known $(\mu, \lambda)$ strategy is used, which is indeed similar to the continuous GA in terms of the operators (e.g., crossover, mutation, and reproduction). However, the mutation strength of each gene/attribute in the individual ($\vec{x}$) is not constant, but learned during the evolution. Accordingly, each individual in the population carries a strategy vector of same size as ($\vec{x}$), where the strategy vector is adapted during the evolution, and controls the mutation strength of each attribute. We adopt log-normal adaptation for the strategy vector (see \cite{beyer2002evolution}), where the min and max strategies are bounded between $1/n$ and 0.5, respectively, as suggested by the literature, where $n$ is the size of $\vec{x}$. On the population level, the crossover operation selects two random individuals for mating with probability $CX$, where we use the classical two-point crossover in this work. After crossover, some of the individuals may be selected for mutation with a small probability $MUT$. Notice that for $(\mu, \lambda)$, both $MUT$ and $CX$ on the population level remain fixed, unlike the internal mutation strength for each individual. After fitness evaluation of the population, the selected individuals $\mu$ are passed to the next generation, where these $\mu$ individuals participate in generating the next offspring of size $\lambda$ (i.e., $\lambda \geq \mu$). Particle swarm optimisation (PSO) \cite{kennedy1995particle} is inspired by the movement of organisms in bird or fish flocks. Each particle in the swarm experiences position update ($x^{t+1}_i = x^t_i + v^{t+1}_i$), where $i$ is the attribute index and $v$ is the velocity value for that attribute. We implement the constriction approach by Clerc and Kennedy \cite{clerc2002particle} for velocity update, which can be expressed as follows \begin{align} v^{t+1}_i &= K[v^t_i + c_1r_1(pbest^t_i - x^t_i) + c_2r_2(gbest^t - x^t_i)] \\ K &= \frac{2}{|2- \phi - \sqrt{\phi^2-4\phi}|} \\ \phi &= c_1 + c_2, \quad \phi > 4 \end{align} where $c_1$, $c_2$ are the cognitive and social speed constants, respectively, $r_1$, $r_2$ are uniform random numbers between [0,1], and $pbest$, $gbest$ are the local best position for each particle and global best position of the swarm, respectively. Lastly, $K$ is the constriction coefficient introduced to balance PSO exploration/exploitation and improve stability. Typically, when $c_1 = c_2 = 2.05$, then $K=0.73$. Another advantage of using constriction is it exempts us from using velocity clamping; therefore there is no need to specify minimum and maximum velocities, which reduces PSO hyperparameters, and PESA by definition. The number of particles in the swarm is given by $\eta$. Simulated Annealing (SA) \cite{kirkpatrick1983optimization} is inspired from the concept of annealing in physics to reduce defects in crystals through heating followed by progressive cooling. In optimisation, SA combines high climbing and pure random-walk to help us find an optimum solution through implementing five basic steps: (1) generate a candidate solution, (2) evaluate candidate fitness, (3) generate a random neighbor solution and calculate its fitness, (4) compare the old and new fitness evaluations (i.e., $\Delta E$ increment), if better continue with the new solution, if worse, accept the old solution with probability $\alpha=exp^{-\Delta E/T}$, where T is the annealing temperature, (5) repeat steps 3-4 until convergence. Temperature is annealed between $T_{max}$ and $T_{min}$ over the annealing period, where the fast annealing schedule is adopted in this work \begin{equation} \label{eq:fast} T = T_{max}\cdot exp\bigg[\frac{-log(T_{max}/T_{min})N}{N_{steps}}\bigg], \end{equation} where $N$ is the current annealing step, which builds up from 1 to $N_{steps}$. New SA candidates are generated using random-walk with a small probability $\chi$, where each input attribute is subjected to perturbation once $rand \sim U[0,1] < \chi$ is satisfied. Small value of $\chi$ between 0.05-0.15 seemed to yield better performance in this work. \subsection{Experience Replay} \label{sec:er} Two modes of experience replay are relevant to this work: (1) greedy and (2) prioritized replay. Greedy replay sorts the memory from min to max (assuming a minimization problem), and replays the sample(s) with lowest fitness every time. Intuitively, replaying always the best samples could lead to improvement early on, but will restrict the diversity of the search, and likely to end with premature convergence (i.e., methods converge to a local optima). Therefore, greedy replay in PESA is used in a special form with SA described later. Prioritized replay balances between uniform and greedy sampling through using uniform replay early on, allowing PESA to explore more at first and exploit at the end. Probability of replaying sample $i$ can be defined as follows: \begin{equation} \label{eq:prior1} P_i = \frac{p_i^\alpha}{\sum_{d=1}^D p_d^\alpha} \end{equation} where $D$ is the current memory size and exponent $\alpha$ is the priority coefficient $\in [0,1]$, explaining how much prioritization is used. $\alpha = 0$ corresponds to uniform replay (i.e., all samples have equal weights), while $\alpha =1$ corresponds to the fully prioritized replay. Notice here we describe $\alpha =1$ as ``fully prioritized`` replay rather than greedy replay (i.e., min operator). When $\alpha =1$, the best samples (lowest fitness) are ``more likely'' to be replayed due to their larger weight, but in greedy replay these quality samples are ``100\%'' replayed (because of applying the $min$ operator). Next, $p_i$ refers to the priority of sample $i$, which can take different forms. For our case, we choose a prioritization based on sample rank: \begin{equation} \label{eq:prior2} p_i = \frac{1}{rank(i)} \end{equation} where $rank(i)$ is the sample rank based on fitness value when the memory is sorted from minimum fitness to maximum. After sorting, sample 1 has $p_i = 1$, sample 2 has $p_i = 0.5$, and so on. According to \cite{schaul2015prioritized}, rank-based prioritization is robust since it is insensitive to outliers. Now, to balance between exploration/exploitation in prioritized replay, we start PESA evolution with small value of $\alpha = \alpha_{init} = 0.01$ (more exploration), and then gradually increasing until $\alpha =\alpha_{end} = 1.0$ (more exploitation) by the end of evolution. After a generation $k$, priorities are calculated by Eq.\eqref{eq:prior2}, sampling probability is determined by Eq.\eqref{eq:prior1}, and replay is performed by sampling from a non-uniform distribution with probabilities [$P_1, P_2, ..., P_D$]. Notice that redundant samples (if any) are removed from the memory before re-sampling to avoid biasing the replay toward certain samples. \begin{algorithm}[!h] \small \caption{Evolution Strategy ($\mu + \mu', \lambda$) in PESA} \label{alg:es} \begin{algorithmic}[1] \State \textbullet Given ES hyperparameters: $\mu$, $\mu'$, $\lambda$, $MUT$, $CX$ \For{a generation $k$} \State \textbullet Apply crossover operator to the population ($\mu + \mu'$) with probability $CX$ \State \textbullet Apply mutation operator to the population ($\mu + \mu'$) with probability $MUT$ \If {$MUT + CX < 1$} \State \textbullet Apply reproduction to the population ($\mu + \mu'$) with probability $1 - MUT - CX$ \EndIf \State \textbullet Generate final offspring $\lambda$ from the population ($\mu + \mu'$) \State \textbullet \textit Evaluate fitness of the offspring \State \textbullet Select $\mu$ individuals with best fitness for next generation \EndFor \State \textbullet Return the selected individuals $\bm{\mu} = \{(\vec{x}_1, y_1), (\vec{x}_2, y_2),...,(\vec{x}_\mu, y_\mu)\}$ \end{algorithmic} \end{algorithm} As in Figure \ref{fig:pesa}, prioritized replay is used with all three algorithms at the beginning of each generation. For ES, the replay memory provides $\mu'$ individuals at the beginning of every generation, which mix with original $\mu$ individuals (from previous generation) using crossover, mutation, and reproduction operations (see Figure \ref{fig:pesa}). Therefore, the ($\mu,\lambda$) algorithm becomes ($\mu + \mu',\lambda$) for PESA, as $\mu'$ individuals are mixed with $\mu$ before forming the next $\lambda$ offspring. The ES algorithm in PESA is given in Algorithm \ref{alg:es}. The prioritized replay for PSO is similar to ES, where the swarm particles at every generation constitute from $\eta$ particles of the previous generation and $\eta'$ particles from the memory, before going through velocity and position updates as described in section \ref{sec:evol}. In both cases (ES, PSO), the values of $\mu'$ and $\eta'$ can be tuned for better performance. The PSO algorithm in PESA is given in Algorithm \ref{alg:pso}. \begin{algorithm}[!h] \small \caption{Particle Swarm Optimisation ($\eta + \eta'$) in PESA} \label{alg:pso} \begin{algorithmic}[1] \State \textbullet Given PSO hyperparameters: $\eta$, $\eta'$, $c_1$, $c_2$ \For{a generation $k$} \State \textbullet Update velocity of swarm particles ($\eta + \eta'$) with constriction coefficient \State \textbullet Generate new swarm by updating all particle positions ($\eta + \eta'$) \State \textbullet Evaluate fitness of the swarm \State \textbullet Select $\eta$ particles with best fitness for next generation \EndFor \State \textbullet Return the selected particles $\bm{\eta} = \{(\vec{x}_1, y_1), (\vec{x}_2, y_2),...,(\vec{x}_\eta, y_\eta)\}$ \end{algorithmic} \end{algorithm} For SA, prioritized replay is used to make an initial guess for the chain before starting a new annealing generation. Given SA is running in series in this work, a single chain is used. Once the generation is done, SA updates the memory by the last pair ($\vec{x}^{last},y^{last}$) and best pair ($\vec{x}^{best},y^{best}$) observed by the chain in that generation. The SA algorithm in PESA is given in Algorithm \ref{alg:sa}. \begin{algorithm}[!h] \small \caption{Simulated Annealing in PESA} \label{alg:sa} \begin{algorithmic}[1] \State \textbullet Given SA hyperparameters: $T_{max}$, $T_{min}$, $\alpha_{backdoor}$ \State \textbullet Draw initial state from the memory, $\theta' = (\vec{x}_0, y_0)$ \State \textbullet Set $\vec{x}_{prev} \xleftarrow{} \vec{x}_0$, $E_{prev} \xleftarrow{} y_0$ \For{a generation $k$} \If {$rand \sim$ U[0,1] $< \alpha_{backdoor}$} \State \textbullet Draw the best sample from the memory $(\vec{x}',y')$ \State \textbullet Set $\vec{x}\xleftarrow{} \vec{x}'$, $E \xleftarrow{} y'$ \Else \State \textbullet Perform a random walk as next chain state $(\vec{x})$ \State \textbullet Evaluate fitness $E$ for the new state \EndIf \State \textbullet Calculate $\Delta E = E - E_{prev}$ \If {$\Delta E < 0$ OR $exp(-\Delta E/T) > rand \sim$ U[0,1]} \State \textbullet Accept the candidate \State \textbullet Set $E_{prev} \xleftarrow{} E$, $\vec{x}_{prev} \xleftarrow{} \vec{x}$ \Else \State \textbullet Reject the candidate and restore previous state \State \textbullet Set $E_{prev} \xleftarrow{} E_{prev}$, $x_{prev} \xleftarrow{} x_{prev}$ \EndIf \State \textbullet Anneal $T$ between $T_{max}$ and $T_{min}$ \EndFor \State \textbullet Return the last chain state ($\vec{x}^{last},y^{last}$) and best state ($\vec{x}^{best},y^{best}$) \end{algorithmic} \end{algorithm} The backdoor greedy replay for SA in Figure \ref{fig:pesa} and Algorithm \ref{alg:sa} has two main benefits: (1) ensuring PESA exploitation at the end of evolution and (2) providing more guidance to SA that relies extensively on random-walk. Unlike prioritized replays that occur explicitly at the beginning of every generation of all algorithms including SA, backdoor replay obtained this name since it occurs implicitly during SA generation, by giving the SA chain a choice between its regular random-walk or the best quality sample in the memory with probability $rand \sim U[0,1] < \alpha_{backdoor}$. Since SA tends to accept low quality solutions early on, but tightens the acceptance criteria at the end by rejecting low quality solutions, this means SA will implicitly drive PESA to always converge to the best solution in the memory once the evolution is close to end. Second, as SA lacks the learning capabilities of PSO and ES (velocity update, crossover, etc.), the backdoor replay will frequently correct the SA chain to focus the search in relevant space regions as found by her sisters (PSO, ES) so far during the evolution. We typically recommend small value for $\alpha_{backdoor}$ (i.e., $<$ 0.15), since obviously large values lead to repetitive greedy replays, which in turn cause a bias in the chain, eventually leading to premature convergence in SA. \subsection{PESA Algorithm} By combining all parts presented in sections \ref{sec:evol}-\ref{sec:er}, PESA algorithm can be constructed as given in Algorithm \ref{alg:pesa}. The flow of PESA can be summarised in three main phases: \begin{enumerate} \item Warmup (lines 1-4 in Algorithm \ref{alg:pesa}): Hyperparameters of all individual algorithms (ES, PSO, SA) are specified. The memory is initialized with a few warmup samples ($N_{warmup}$) and maximum capacity ($D_{max}$). \item Evolution (lines 8-17 in Algorithm \ref{alg:pesa}): The three algorithms, ES, PSO, and SA are executed in parallel according to Algorithm \ref{alg:es}, Algorithm \ref{alg:pso}, and Algorithm \ref{alg:sa}, respectively. \textit{Each individual algorithm runs its iterations in serial}. \item Memory management (lines 6-7, 18-20 in Algorithm \ref{alg:pesa}): This phase involves updating the memory with new samples, calculating and updating sample priority, annealing the prioritization coefficient ($\alpha$), and cleaning the memory from duplicates. \end{enumerate} \begin{algorithm}[!h] \small \caption{PESA Algorithm with Prioritized Replay} \label{alg:pesa} \begin{algorithmic}[1] \State \textbullet Set hyperparameters of ES, SA, PSO \State \textbullet Set replay parameters: $\alpha_{backdoor}$, $\alpha_{init}$, $\alpha_{end}$ \State \textbullet Construct the replay memory with size $D_{max}$ and initialize with warmup samples $N_{warmup}$ \State \textbullet Set $\alpha \xleftarrow{} \alpha_{init}$ \For{GEN $i = 1$ to $N_{gen}$} \State \textbullet Calculate $p_i = 1/rank(i)$ and priorities $P(i) = p_i^\alpha/\sum_d p_d^\alpha$ \State \textbullet With probabilities $P(i)$, draw samples $\bm{\mu'}$, $\bm{\eta'}$, and $\bm{\theta'}$ \For{\textit{Parallel} Process 1: ES} \State \textbullet Given $\bm{\mu'} = \{(\vec{x}_1, y_1),...,(\vec{x}_\mu, y_{\mu'})\}$, run ES Algorithm \ref{alg:es} \State \textbullet Obtain ES population $\bm{\mu} = \{(\vec{x}_1, y_1), (\vec{x}_2, y_2),...,(\vec{x}_\mu, y_\mu)\}$ \EndFor \For{\textit{Parallel} Process 2: PSO} \State \textbullet Given $\bm{\eta'} = \{(\vec{x}_1, y_1),...,(\vec{x}_\eta, y_{\eta'})\}$, run PSO Algorithm \ref{alg:pso} \State \textbullet Obtain PSO population $\bm{\eta} = \{(\vec{x}_1, y_1), (\vec{x}_2, y_2),...,(\vec{x}_\eta, y_\eta)\}$ \EndFor \For {\textit{Parallel} Process 3: SA} \State \textbullet Given $\bm{\theta'} = \{(\vec{x}', y')\}$, run SA Algorithm \ref{alg:sa} \State \textbullet Obtain SA population $\bm{\theta} = \{(\vec{x}^{last}, y^{last})\}$ \State \textbullet Obtain SA best population $\bm{\theta}^{best} = \{(\vec{x}^{best}, y^{best})\}$ \EndFor \State \textbullet Update the memory with samples $\bm{\mu}, \bm{\eta}$, $\bm{\theta}$, and $\bm{\theta}^{best}$ \State \textbullet Remove duplicated samples from the memory \State \textbullet Anneal $\alpha$ between $\alpha_{init}$, $\alpha_{end}$ \EndFor \end{algorithmic} \end{algorithm} As can be noticed from Algorithm \ref{alg:pesa}, algorithm-based parallelism can be observed in PESA (see steps 8, 11, and 14 in Algorithm \ref{alg:pesa}), which involves running the three algorithms simultaneously. This feature exists in the algorathim, but not activated in this work, since the functions investigated are too fast-to-evaluate. Internal parallelization of each algorithm is left for future, since again the benchmark functions tested in this work are cheap-to-evaluate, so multiprocessing of each algorithm is also not advantageous. With an effort to minimize the number of hyperparameters in PESA, we assume similar size of generation across algorithms. For example, lets assume a generation of 60 individuals assigned for each algorithm. In this case, the ES population has size $\lambda=60$, PSO swarm has 60 particles, SA chain has size of $C_{size}=60$ steps. Although previous assumptions do not necessarily guarantee the most optimal performance, the authors believe that such symmetry in PESA has two main advantages. First, the burden of hyperparameter optimisation is significantly reduced. Second, algorithm dynamics is improved as all internal algorithms will finish their generation roughly same time, which allows them to stay up to date with the memory. This is clearly under the assumption that fitness evaluation cost ($y$) is roughly the same regardless of the input value ($\vec{x}$). \section{Numerical Tests} \label{sec:tests} The mathematical forms of selected benchmark functions are given in Table \ref{tab:funcs}, which are all well-known optimisation benchmarks \cite{jamil2013literature}. All functions have $n$-dimensions nature, where here we select $n=50$ to represent a more high-dimensional problem. All functions have a known global minima at $f(\vec{x}) = 0$, except for the Ridge and Exponential functions, which have their global minima at -5 and -1, respectively. \begin{table}[htbp] \centering \footnotesize \caption{List of continuous benchmark functions with $n$-dimensional space} \begin{adjustbox}{max width=\textwidth} \begin{tabular}{llll} \toprule Name & Formula & $\vec{x}$ Range & Global Optima \\ \midrule (1) Cigar & $ f(\vec{x}) = x_0^2 + 10^6\sum_{i=1}^n\,x_i^2$ & $[-10,10]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (2) Sphere & $ f(\vec{x}) = \sum_{i=1}^n x_i^2$ & $[-100,100]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (3) Ridge & $ f(\vec{x}) = x_1 + (\sum_{i=2}^{n}x_i^2)^{0.5}$ & $[-5,5]^n$ & $\vec{x}^* = [-5,0, ..., 0], f(\vec{x}^*) = -5$ \\ (4) Ackley & $ f(\vec{x}) = 20-20exp\Big(-0.2\sqrt{\frac{1}{n}\sum_{i=1}^{n}x_i^2}\Big)-exp\Big(\frac{1}{n}\sum_{i=1}^{n}cos(2\pi x_i)\Big) + e$ & $[-32,32]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (5) Bohachevsky & $f(\vec{x}) = \sum_{i=1}^{n-1}(x_i^2 + 2x_{i+1}^2 - 0.3\cos(3\pi x_i) - 0.4\cos(4\pi x_{i+1}) + 0.7)$ & $[-100,100]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (6) Griewank & $ f(\vec{x}) = \frac{1}{4000}\sum_{i=1}^n\,x_i^2 - \prod_{i=1}^n\cos\left(\frac{x_i}{\sqrt{i}}\right) + 1$ & $[-600,600]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (7) Brown & $ f(\vec{x}) = \sum_{i=1}^{n-1}(x_i^2)^{(x_{i+1}^{2}+1)}+(x_{i+1}^2)^{(x_{i}^{2}+1)}$ & $[-1,4]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (8) Exponential & $ f(\vec{x})=-exp(-0.5\sum_{i=1}^n{x_i^2})$ & $[-1,1]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = -1$ \\ (9) Zakharov & $ f(\vec{x})=\sum_{i=1}^n x_i^{2}+(\sum_{i=1}^n 0.5ix_i)^2 + (\sum_{i=1}^n 0.5ix_i)^4$ & $[-5,10]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (10) Salomon & $ f(\vec{x})=1-cos(2\pi\sqrt{\sum_{i=1}^{n}x_i^2})+0.1\sqrt{\sum_{i=1}^{n}x_i^2}$ & $[-100,100]^n$ & $\vec{x}^* = \vec{0}, f(\vec{x}^*) = 0$ \\ (11) Quartic & $ f(\vec{x})=\sum_{i=1}^{n}ix_i^4+\text{random}[0,1)$ & $[-1.28,1.28]^n$ & $\vec{x}^*=\vec{0}, f(\vec{x}^*) = 0 + \text{noise}$ \\ (12) Levy & $\begin{aligned} f(\vec{x}) & = sin^2(\pi w_1) + \sum_{i=1}^{n-1}(w_i-1)^2[1+10sin^2(\pi w_i+1)] \\ & + (w_n-1)^2[1+sin^2(2\pi w_n)], \quad w_i = 1 + (x_i-1)/4 \end{aligned}$ & $[-10,10]^n$ & $\vec{x}^* = \vec{1}, f(\vec{x}^*) = 0$ \\ \bottomrule \end{tabular}% \end{adjustbox} \label{tab:funcs}% \end{table}% The hyperparameters selected to perform the tests are as follows: For ES ($CX=0.6, MUT=0.15, \lambda=60, \mu=30, \mu'=30$), for PSO ($c_1=2.05, c_2=2.05, \eta=30, \eta'=30$), for SA ($T_{max} = 10000, T_{min} = 1, \chi=0.1, C_{size} = 60$), while for replay parameters ($\alpha_{init}=0.01, \alpha_{end}=1.0, \alpha_{backdoor}=0.1$). The tests are executed with $N_{gen} = 100$ generations and $N_{warmup} = 500$ samples. The previous hyperparameters yielded satisfactory performance for all test functions. \textit{It is very important highlighting that the hyperparameters, initial starting points, and number of generations are preserved between PESA and the standalone algorithms to isolate their effects}. This means that any difference in performance comes purely from the ``experience share and replay'', the contribution of this work. The convergence of fitness results is plotted in Figure \ref{fig:pesa}, which compares PESA against the standalone algorithms given the prescribed hyperparameters. For brevity, the plotted results include the minimum fitness found in each generation, since it is our end goal, so the first generation point is not necessarily the initial guess in all algorithms. In addition, log-scale is used for some functions (Cigar, Sphere, Brown, etc.) to reflect a better scale, where we set $10^{-2}$ as a lower bound to represent the zero global minima. Obviously, the results clearly show PESA outperforming the standalone ES, PSO, and SA by a wide margin in terms of number of generations to reach global minima. First, in all benchmarks, PESA successfully found and converged to the global optima, while the standalone algorithms failed to do so in most cases. In addition, PESA tends to converge much faster to the feasible region, thanks to the collaborative environment that PESA creates. We can notice that PSO is the most competitive algorithm to PESA. This is expected, since PSO was developed for continuous optimization, which is the feature of all the considered benchmarks. However, PSO alone seems to converge slowly. Due to the high dimensionality, standalone SA struggles to resolve the search space or to converge to a relevant solution in all cases. Standalone ES performance in Figure \ref{fig:pesa} is bounded between PSO and SA in most cases, except for the Levy function at which ES outperforms PSO. \begin{figure}[h] \centering \includegraphics[width=\textwidth]{figures/bench_arxiv.png} \caption{Comparison of fitness convergence of PESA against ES, PSO, and SA in \textbf{standalone} form for minimization of 12 continuous benchmarks, dimensionality $n=50$ (See Table \ref{tab:funcs})} \label{fig:bench} \end{figure} To demonstrate PESA exploration capabilities, Figure \ref{fig:explore} plots the Ackley fitness mean and $1-\sigma$ standard deviation for PESA against standalone ES, PSO, and SA. The statistics are calculated based on ``all'' individuals within each generation (i.e., low and high quality solutions). Obviously, PESA features a much bigger error bar than the standalone algorithms, which reflects sample diversity within each PESA generation. The diversity of samples helps PESA to have better exploration of the search space, and overall better performance. On the other hand, the very small error bar of ES in Figure \ref{fig:explore} implies more exploitative behavior than PSO, which fairly explores the space. \begin{figure}[h] \centering \includegraphics[width=0.55\textwidth]{figures/explore.png} \caption{Convergence of fitness mean and standard deviation of PESA against \textbf{standalone} ES, PSO, and SA for the Ackley function} \label{fig:explore} \end{figure} To explain how PESA improved the performance of the three individual algorithms, Figure \ref{fig:prog} shows how ES, PSO, and SA perform \textbf{during PESA search} (i.e. NOT as standalone algorithms). First, we notice that PSO is leading PESA search early on as can be seen from the lower PSO fitness. Afterward, experience replay takes over by first guiding SA and preventing it from divergence as seen in Figure \ref{fig:bench}, and second by allowing ES and SA to lead PESA search as can be observed in some generations between 5-10. Additionally, thanks to the backdoor greedy replay, which allows SA to stay close to ES and PSO over the whole search period, investigating relevant search regions. At the end of the evolution, the three algorithms converge to each other due to the experience share of high quality solutions across the three algorithms. Unlike Figure \ref{fig:explore}, which shows PESA exploration ability, Figure \ref{fig:prog} shows how PESA uses SA to continuously exploit toward best solutions over the whole evolution period. \begin{figure}[h] \centering \includegraphics[width=0.55\textwidth]{figures/prog.png} \caption{Fitness convergence of ES, PSO, and SA \textit{\textbf{within PESA}} for the Sphere function} \label{fig:prog} \end{figure} Comparison of computational time between the four algorithms for three selected functions is given in Table \ref{tab:time}. The memory management phase in the forms of sorting the memory, updating and re-sampling from the memory, calculating the priorities, annealing $\alpha$, and cleaning the memory from duplicates result in a longer run time for PESA compared to the standalone algorithms as expected. It is important mentioning that the numbers in Table \ref{tab:time} involve running PESA and other algorithms in serial (single core), meaning that PSO, ES, and SA parts in PESA are not running in parallel, since we found that parallelization not necessary for these benchmarks. Therefore, from Table \ref{tab:time}, out of about $\sim$12s of PESA computing time, about 65\% ($\sim$7-8s) of the time is taken by the algorithms, while the rest are taken by the memory. The user can reduce the memory effect by controlling the full capacity of the memory ($D_{max}$), as interpreting large memories later in the evolution is consuming more time. The tests below in Table \ref{tab:time} involve registering every possible unique solution without limits (to obtain best performance), which would justify the significant portion consumed by the memory. \begin{table}[htbp] \centering \footnotesize \caption{Computing time in seconds required by different algorithms to run 100 generations for three selected functions} \begin{tabular}{llll} \toprule Method & Cigar & Sphere & Ackley \\ \midrule PESA (serial) & 11.7s & 11.0s & 12.8s \\ ES (serial) & 1.2s & 1.3s & 1.2s \\ PSO (serial) & 5.6s & 5.2s & 6.2s \\ SA (serial) & 0.5s & 0.5s & 0.9s \\ \bottomrule \end{tabular}% \label{tab:time}% \end{table}% \section{Conclusions} The concepts of experience share and replay are demonstrated through the proposed PESA algorithm to improve the search performance of evolutionary/stochastic algorithms. Experience share is preformed through connecting particle swarm optimisation (PSO), evolution strategies (ES), and simulated annealing (SA) with a replay memory, storing all their observed solutions. Experience replay is conducted by re-sampling with priority coefficient from the memory to guide the learning of all algorithms. In addition, greedy replay is used in backdoor form with SA to improve PESA exploitation behavior. The validation against 12 high-dimensional continuous benchmark functions shows superior performance by PESA against standalone ES, PSO, and SA, under similar initial starting points, hyperparameters, and number of generations. PESA shows much better exploration behaviour, faster convergence, and ability to find the global optima compared to its standalone counterparts. Given the promising performance, the authors are now focusing on fully-parallelizing PESA such that ES, PSO, and SA can evaluate each generation in shorter time. This is especially important when the fitness evaluation is complex (e.g., requires computer simulation). Additionally, PESA will go through additional benchmarking against other hybrid evolutionary methods in the literature, e.g. ES/SA or RL/PSO. Lastly, combinatorial PESA version will be developed and benchmarked in solving engineering combinatorial problems with heavy constraints. \section*{Acknowledgment} This work is sponsored by Exelon Corporation, a nuclear electric power generation company, under the award (40008739) \section*{Data Availability} The PESA GitHub repository will be released to the public once the peer-review process is done, which will include the source implementation and wide range of unit tests from benchmarks to engineering applications. \bibliographystyle{elsarticle-num} { \footnotesize
{'timestamp': '2020-09-21T02:17:40', 'yymm': '2009', 'arxiv_id': '2009.08936', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08936'}
arxiv
\section{Introduction} Machine learning (ML) systems are increasingly used to automate decisions with direct impact on our daily lives such as credit scoring, loan assessments, crime prediction, hiring, and college admissions. There is increasing awareness that ML algorithms can affect people in unfair ways with legal or ethical consequences when used to automate decisions~\cite{barocas2016big,angwin2016machine}, for example, exhibiting discrimination towards certain demographic groups. As social media platforms are a major contributor to the number of automated data-driven decisions that we as individuals are subjected to, it is clear that such ML fairness issues in social media can potentially cause substantial societal harm. Recommender systems are the primary method for a variety of ML tasks for social media data, e.g. suggesting targets of advertisements, products (e.g. movies, music etc.), friends, web pages, and potentially consequential suggestions such as romantic partners or even career paths. Despite the practical challenges due to labor market dynamics~\cite{kenthapadi2017personalized}, professional networking site-based job recommendation approaches~\cite{bastian2014linkedin,frid2019find,gutierrez2019explaining} are helpful for job seekers and employers. However, biases inherent in social media data can lead recommender systems to produce unfair suggestions. For example, XING, a job platform similar to LinkedIn, was found to rank less qualified male candidates higher than more qualified female candidates~\cite{lahoti2019ifair}. Recommendations in educational and career choices are another important motivating application for fair recommender systems. Students' academic choices can have significant impacts on their future careers and lives. In 2010, women accounted for only 18\% of the bachelor’s degrees awarded in computer science~\cite{broad2014recruiting}, and interventions to help bridge this gap are crucial ~\cite{beede2011women}. Recommender systems can reinforce this disparity, or ---potentially--- help to mitigate it. In this paper, we investigate gender bias in recommender systems trained on social media data for suggesting sensitive items (e.g. academic concentrations or career paths). For social media data in particular, we typically have abundant implicit feedback for user preferences of various \emph{non-sensitive} items in which gender disparities are acceptable, or even desirable (e.g. ``liked'' Facebook pages, movies, or music), but limited data on the \emph{sensitive} items (e.g., users typically have only one or two college concentrations or occupations). User embeddings learned from the non-sensitive data can help predict the sparse sensitive items, but may encode harmful stereotypes, as has been observed for word embeddings~\cite{bolukbasi2016man}. Furthermore, the distribution of sensitive items typically introduces further unwanted bias due to societal disparities in academic concentrations and career paths, e.g. from the ``leaky pipeline'' in STEM education \cite{beede2011women}. We propose a practical technique to mitigate gender bias in sensitive item recommendations while resolving the above challenges. Our approach, which we call \emph{neural fair collaborative filtering (NFCF)}, achieves accurate predictions while addressing \emph{\textbf{sensitive data sparsity}} by pre-training a deep neural network on big implicit feedback data for non-sensitive items, and then fine-tuning the neural network for sensitive item recommendations. We perform two bias corrections, to address \emph{(1) bias in the \textbf{input embeddings} due to the non-sensitive items}, and \emph{(2) bias in the \textbf{prediction outputs} due to the sensitive items}. An ablation study shows that \emph{\textbf{both} interventions are important for fairness}. We demonstrate the utility of our method on two datasets: \emph{MovieLens} (non-sensitive \emph{movie ratings} and sensitive \emph{occupations}), and a \emph{Facebook} dataset (non-sensitive \emph{Facebook page ``likes''} and sensitive \emph{college majors}). Our main contributions include: \begin{itemize} \item We propose a pre-training + fine-tuning neural network method for fair recommendations on social media data. \item We propose two de-biasing methods: 1) de-biasing latent embeddings, and 2) learning with a fairness penalty. \item We perform extensive experiments showing both fairness and accuracy benefits over baselines on two datasets. \end{itemize} \section{Background and Related Work} In this section we formalize the problem, and discuss collaborative filtering with implicit data, and fairness metrics. \subsection{Problem Formulation} Let $M$ and $N$ denote the number of users and items, respectively. Suppose we are given a user-item interaction matrix $\textbf{Y}\in \mathbb{R}^{M\times N}$ of \emph{implicit feedback} from users, defined as \begin{equation} y_{ui} = \begin{cases} 1, & \text{if $u$ interacts with $i$}\\ 0, & \text{otherwise.} \end{cases} \end{equation} Here, $y_{ui}=1$ when there is an interaction between user $u$ and item $i$, e.g. when $u$ ``likes'' Facebook page $i$. In this setting, a value of $0$ does not necessarily mean $u$ is not interested in $i$, as it can be that the user is not yet aware of it, or has not yet interacted with it. While interacted entries reflects users' interest in items, the unobserved entries may just be missing data. Therefore, there is a natural scarcity of strong negative feedback. The collaborative filtering (CF) problem with implicit feedback is formulated as the problem of predicting scores of unobserved entries, which can be used for ranking the items. The CF model outputs $\hat{y}_{ui}=f(u,i|\Theta)$, where $\hat{y}_{ui}$ denotes the estimated score of interaction $y_{ui}$, $\Theta$ denotes model parameters, and $f$ denotes the function that maps model parameters to the estimated score. If we constrain $\hat{y}_{ui}$ in the range of [0,1] and interpret it as the probability of an interaction, we can learn $\Theta$ by minimizing the following negative log-likelihood objective function: \begin{equation}\label{eq:loss} L = - \sum_{(u,i)\in \chi \cup \chi^{-}} y_{ui}\log\hat{y}_{ui} + (1-y_{ui})\log(1-\hat{y}_{ui})\mbox{ ,} \end{equation} where $\chi$ represents the set of interacted user-item pairs, and $\chi^{-}$ represents the set of negative instances, which can be all (or a sample of) unobserved interactions. Learning with implicit feedback becomes more challenging when there is not enough observed interaction data per user. In our setting, we further suppose that items $i$ are divided into non-sensitive items ($i_n$) and sensitive items ($i_s$). For example, the $i_n$'s can be \emph{Facebook pages} where user preferences may reasonably be influenced by the protected attribute such as gender, and the user's ``likes'' of the pages are the implicit feedback. Since each user $u$ can (and often does) ``like'' many pages, $u$'s observed non-sensitive data ($u$-$i_n$) is typically large. On the other hand, $i_s$ may be the users' \emph{occupation} or \emph{academic concentration} provided in their social media profiles. We desire that the recommendations of $i_s$ to new users should be unrelated to the users' gender (or other protected attribute). Since each user $u$ may typically be associated with only a single occupation (or other sensitive personal data rarely disclosed), the data sparsity in the observed sensitive item interactions ($u$-$i_s$) is a major challenge. As a result, it is difficult to directly predict $u$-$i_s$ interactions based on other $u$-$i_s$ interactions. Typical collaborative filtering methods can suffer from overfitting in this scenario, and overfitting often amplifies unfairness or bias in the data such as harmful stereotypes \cite{zhao2017men,foulds2018intersectional}. Alternatively, the non-sensitive interactions $u$-$i_n$ can be leveraged, but these will by definition encode biases that are unwanted for predicting the sensitive items. For example, liking the \emph{Barbie doll} Facebook page may be correlated with being female and negatively correlated with \emph{computer science}, thus implicitly encoding societal bias in the career recommendations. \subsection{Neural Collaborative Filtering} Traditional matrix factorization (MF) models~\cite{koren2009matrix} map both users and items to a joint latent factor space of dimensionality $v$ such that user-item interactions are modeled as inner products in that space. Each item $i$ and user $u$ are associated with a vector $q_i\in R^{v}$ and $p_u\in R^{v}$, with \begin{equation}\label{eq:MF} \hat{y}_{ui} = q_{i}^{T}p_{u}+\mu + b_i + b_u\mbox{ ,} \end{equation} where $\mu$ is the overall average rating, and $b_u$ and $b_i$ indicate the deviations of user $u$ and item $i$ from $\mu$, respectively. Neural collaborative filtering (NCF)~\cite{he2017neural} replaces the inner products in matrix factorization with a deep neural network (DNN) that learns the user-item interactions. In the input layer, the users and items are typically one-hot encoded, then mapped into the latent space with an embedding layer. NCF combines the latent features of users ${p}_u$ and items ${q}_i$ by concatenating them. Complex non-linear interactions are modeled by stacking hidden layers on the concatenated vector, e.g. using a standard multi-layer perceptron (MLP). A commonly used architecture is a tower pattern, where the bottom layer is the widest and each successive layer has a smaller number of neurons~\cite{he2016deep}. \subsection{Fairness in Recommender Systems} The recommender systems research community has begun to consider issues of fairness in recommendation. A frequently practiced strategy for encouraging fairness is to enforce \emph{demographic parity} among different protected groups. Demographic parity aims to ensure that the set of individuals in each protected group have similar overall distributions over outcomes (e.g. recommended items) ~\cite{zemel2013learning}. Some authors have addressed the unfairness issue in recommender systems by adding a regularization term that enforces demographic parity~\cite{kamishima2011fairness,kamishima2012enhancement,kamishima2013efficiency,kamishima2014correcting,kamishima2016model}. However, demographic parity is only appropriate when user preferences have no legitimate relationship to the protected attributes. In recommendation systems, user preferences are indeed often influenced by protected attributes such as gender, race, and age~\cite{chausson2010watches}. Therefore, enforcing demographic parity may significantly damage the quality of recommendations. Fair recommendation systems have also been proposed by penalizing disparate distributions of prediction error~\cite{yao2017beyond}, and by making recommended items independent from protected attributes such as gender, race, or age~\cite{kamishima2017considerations}. In addition, ~\cite{burke2017balanced,burke2017multisided} taxonomize fairness objectives and methods based on which set of stakeholders in the recommender system are being considered, since it may be meaningful to consider fairness among many different groups. Pareto efficiency-based fairness-aware group recommendation~\cite{xiao2017fairness} was also proposed, however this method is not effective in personalized fair recommendations. In a non-archival extended abstract~\cite{rashid}, we recently proposed a simple technique to improve fairness in social media-based CF models. Our approach was to learn an NCF model, then debias the user embeddings using a linear projection technique, and predict sensitive items using k-nearest neighbors or logistic regression. This method improves the fairness of CF, but substantially degrades the accuracy of recommendations. In this work, we improve on this approach by using the method in ~\cite{rashid} to debias a pre-trained neural model for non-sensitive items, then fine-tuning using a fairness penalty to learn to recommend sensitive items. Our results show improved fairness and accuracy versus~\cite{rashid}. \subsection{Fairness Metrics} We consider several existing fairness metrics which are applicable for collaborative filtering problems. \subsubsection{Differential Fairness} The differential fairness \cite{foulds2018intersectional,foulds2018bayesian} metric aims to ensure equitable treatment for all protected groups, and it provides a privacy interpretation of disparity. Let $M(x)$ be an algorithmic mechanism (e.g. a recommender system) which takes an individual's data $x$ and assigns them an outcome $y$ (e.g. a class label or whether a user-item interaction is present). The mechanism $M(x)$ is $\epsilon$-\emph{differentially fair (DF)} with respect to $(A, \Theta)$ if for all $\theta \in \Theta$ with $x \sim \theta$, and $y \in \mbox{Range}(M)$, \begin{equation} e^{-\epsilon} \leq \frac{P_{M, \theta}(M(x) = y|s_i, \theta)}{P_{M, \theta}(M(x) = y|s_j, \theta)}\leq e^\epsilon \mbox{ ,} \end{equation} for all $(s_i, s_j) \in A \times A$ where $P(s_i|\theta) > 0$, $P(s_j|\theta) > 0$. Here, $s_i$, $s_j \in A$ are tuples of all protected attribute values, e.g. male and female, and $\Theta$, the set of data generating distributions, is typically a point estimate of the data distribution. If all of the $P_{M, \theta}(M(x) = y|s, \theta)$ probabilities are equal for each group $s$, across all outcomes $y$ and distributions $\theta$, $\epsilon = 0$, otherwise $\epsilon > 0$. \cite{foulds2018intersectional} proved that a small $\epsilon$ guarantees similar utility per protected group, and ensures that protected attributes cannot be inferred based on outcomes. DF can be estimated using smoothed ``soft counts'' of the predicted outcomes based on a probabilistic model. For gender bias in our recommender (assuming a gender binary), we can estimate $\epsilon$-DF per sensitive item $i$ by verifying that: \begin{align} e^{-\epsilon} \leq \frac{\sum_{u: A = m} \hat{y}_{ui} + \alpha}{N_{m} + 2\alpha}\frac{N_{f} + 2\alpha}{\sum_{u: A = f} \hat{y}_{ui} + \alpha}\leq e^\epsilon \label{eqn:smoothedFairnessSoft} \mbox{ ,}\nonumber \\ e^{-\epsilon} \leq \frac{\sum_{u: A = m} (1-\hat{y}_{ui}) + \alpha}{N_{m} + 2\alpha}\frac{N_{f} + 2\alpha}{\sum_{u: A = f} (1-\hat{y}_{ui}) + \alpha}\leq e^\epsilon \mbox{ ,} \end{align} where scalar $\alpha$ is each entry of the parameter of a symmetric Dirichlet prior with concentration parameter $2\alpha$, $i$ is an item and $N_{A}$ is the number of users of gender $A$ ($m$ or $f$). \subsubsection{Absolute Unfairness} The absolute unfairness ($U_{abs}$) metric for recommender systems measures the discrepancy between the predicted behavior for disadvantaged and advantaged users~\cite{yao2017beyond}. It measures inconsistency in absolute estimation error across user types, defined as follows: \begin{equation} U_{abs} = \frac{1}{N}\sum_{j=1}^{N}||(E_{D}[\hat{y}_{ui}]_j-E_{D}[r]_j)|-|(E_{A}[\hat{y}_{ui}]_j-E_{A}[r]_j)|| \end{equation} where, for $N$ items, $E_{D}[\hat{y}_{ui}]_j$ is the average predicted score for the $j$-th item for disadvantaged users, $E_{A}[\hat{y}_{ui}]_j$ is the average predicted score for advantaged users, and$E_{D}[r]_j$ and $E_{A}[r]_j$ are the average score for the disadvantaged and advantaged users, respectively. $U_{abs}$ captures a single statistic representing the quality of prediction for each user group. If one protected group has small estimation error and the other group has large estimation error, then the former type of group has the unfair advantage of good recommendations, while the other user group has poor recommendations. \section{Neural Fair Collaborative Filtering} Due to biased data that encode harmful human stereotypes in our society, typical social media-based collaborative filtering (CF) models can encode gender bias and make unfair decisions. In this section, we propose a practical framework to mitigate gender bias in CF recommendations, which we refer to as \emph{neural fair collaborative filtering} (NFCF) as shown in Figure~\ref{fig:NFCF_block}. The main components in our NFCF framework are as follows: an \emph{NCF model}, \emph{pre-training user and non-sensitive item embeddings}, \emph{de-biasing pre-trained user embeddings}, and \emph{fine-tuning with a fairness penalty}. We use NCF as the CF model because of its flexible network structure for pre-training and fine-tuning. We will show the value of each component below with an \emph{\textbf{ablation study}} (Table \ref{tab:ablation_study}). Similarly to \cite{he2017neural}, the DNN under the NCF model can be defined as: \begin{align}\label{eq:NCF} {z}_1 = \phi_1({p}_u,{q}_i) = {\begin{bmatrix}{p}_u\\{q}_i \end{bmatrix}} \mbox{ , } \nonumber\\ {z}_2 = \phi_2(z_1) = a_2(W_{2}^{T}z_1 + b_2) \mbox{ , } \nonumber\\ \vdots \nonumber\\ \phi_L(z_{L-1}) = a_L(W_{L}^{T}z_{L-1} + b_L) \mbox{ , } \nonumber\\ \hat{y}_{ui} = \sigma(h^{T}\phi_L(z_{L-1})) \end{align} where $z_l$, $\phi_l$, $W_l$, $b_l$. and $a_l$ denote the neuron values, mapping functio , weight matrix, intercept term, and activation function for the $l$-th layer's perceptron, respectively. The DNN is applied to ${z}_1$ to learn the user-item latent interactions. \begin{figure*}[t] \centerline{\includegraphics[width=0.85\textwidth]{./figures/NFCF.pdf}} \caption{\small Schematic diagram of neural fair collaborative filtering (NFCF). Red arrows indicate back-propagation only. } \label{fig:NFCF_block} \end{figure*} \begin{algorithm}[t] \caption{Training NFCF for Gender De-biased Recommendations}\label{alg-nfcf} \small \begin{flushleft} \textbf{Input:} user and non-sensitive item pairs: $\mathcal{D}_n = (u,i_{n})$, user and sensitive item pairs: $\mathcal{D}_s = (u,i_{s})$, and gender attribute: $A$\\ \textbf{Output:} Fair CF model $M_\mathbf{W}$(x) for $i_{s}$ recommendations \\ \end{flushleft} \begin{flushleft} \emph{\textbf{Pre-training steps:}} \end{flushleft} \begin{itemize} \item Randomly initialize $M_\mathbf{W}$(x)'s parameters $\boldsymbol{W}$: $p_u$, $q_{i_n}$, $W_l$, and $b_l$ \item For each epoch of ${D}_n$ : \begin{itemize} \item For each mini-batch: \begin{itemize} \item Learn $M_\mathbf{W}$(x)'s parameters $\boldsymbol{W}$ by minimizing: \item[] $L = -\sum_{(u,i_n)\in \chi \cup \chi^{-}}[ y_{ui_{n}}\log\hat{y}_{ui_{n}} + (1-y_{ui_{n}})\log(1-\hat{y}_{ui_{n}})]$ \end{itemize} \end{itemize} \end{itemize} \begin{flushleft} \emph{\textbf{De-biasing embeddings steps:}} \end{flushleft} \begin{itemize} \item Compute gender bias vector $v_B$ using Equation ~\ref{eq:female} and ~\ref{eq:bias} \item De-bias each user embedding using: $p_{u} := p_{u} - (p_{u}\cdot v_{B})v_{B}$ \end{itemize} \begin{flushleft} \emph{\textbf{Fine-tuning steps:}} \end{flushleft} \begin{itemize} \item Initialize with pre-trained $M_\mathbf{W}$(x)'s parameters $\boldsymbol{W}$: $W_l$, $b_l$ and de-biased $p_{u}$ with randomly initialized $q_{i_s}$ \item For each epoch of ${D}_s$ : \begin{itemize} \item For each mini-batch: \begin{itemize} \item Fine-tune $M_\mathbf{W}$(x) by minimizing (while $p_{u}$ is kept fixed): \item[] \quad\quad $\underset{\textbf{W}}{\text{min}}[L_{\mathbf{\chi \cup \chi^{-}}}(\textbf{W}) + \lambda R_{\mathbf{\chi}}(\epsilon_{mean})]$ \end{itemize} \end{itemize} \end{itemize} \end{algorithm} In the first step of our NFCF method, \emph{pre-training user and item embeddings}, NCF is trained to predict users' interactions with \emph{non-sensitive} items (e.g. ``liked'' social media pages) via back-propagation. This leverages plentiful non-sensitive social media data to learn user embeddings and network weights, but may introduce \textbf{demographic bias due to correlations between non-sensitive items and demographics}. E.g., liking the \emph{Barbie doll} page typically correlates with user gender. These correlations are expected to result in systematic differences in the embeddings for different demographics, which in turn can lead to systematic differences in sensitive item recommendations. To address this, in step two the user embeddings from step one are \emph{de-biased}. Our method to de-bias user embeddings adapts a very recent work on attenuating bias in word vectors~\cite{dev2019attenuating} to the task of collaborative filtering. Specifically, ~\cite{dev2019attenuating} propose to debias word vectors using a linear projection of each word embedding $w$ orthogonally onto a \emph{bias vector} $v_{B}$, which identifies the ``bias component'' of $w$. The bias component is then removed via $w' = w - (w\cdot v_{B})v_B$. To adapt this method to CF, the main challenge is to find the proper bias direction $v_B$. ~\cite{dev2019attenuating} construct $v_B$ based on word embeddings for gender-specific first names, which are not applicable for CF. We instead use \emph{CF embeddings for users from each protected group}. We first compute a group-specific bias direction for female users as \begin{equation}\label{eq:female} v_{female} = \frac{1}{n_f}(f_1+f_2+\dots +f_n)\mbox{ ,} \end{equation} where $f_1,f_2,\dots$ are vectors for each female user, and $n_f$ is the total number of female users. We similarly compute a bias direction for men $v_{male}$. Finally, we compute the overall gender bias vector: \begin{equation}\label{eq:bias} v_{B} = \frac{v_{female}-v_{male}}{||v_{female}-v_{male}||}\mbox{ .} \end{equation} We then de-bias each user embedding $p_{u}$ by subtracting its component in the direction of the bias vector \begin{equation} p_{u}' = p_{u} - (p_{u}\cdot v_{B})v_{B} \mbox{ .} \end{equation} As we typically do not have demographic attributes for items, we only de-bias user embeddings and not item embeddings. In the third step, we \emph{transfer} the de-biased user embeddings and pre-trained DNN's parameters to a model for recommending \emph{sensitive items}, which we \emph{fine-tune} for this task. During fine-tuning, a \emph{fairness penalty} is added to the objective function to address a second source of bias: \textbf{demographic bias in the sensitive items}. E.g., more men than women choose computer science careers~\cite{broad2014recruiting}, and this should be corrected~\cite{beede2011women}. We penalize the mean of the \emph{per-item} $\epsilon$'s \begin{equation} \epsilon_{mean} = \frac{1}{n_s}\sum_{i=1}^{n_s}\epsilon_i \mbox{ ,} \end{equation} where $\epsilon_1, \epsilon_2, \dots \epsilon_{n_s}$ are the DF measures for sensitive items and $\epsilon_{mean}$ is the average across the $\epsilon$'s for each item. Following ~\cite{foulds2018intersectional}, our learning algorithm for fine-tuning uses the fairness cost as a regularizer to balance the trade-off between fairness and accuracy. Using back-propagation, we minimize the loss function $L_{\mathbf{\chi \cup \chi^{-}}}(\textbf{W})$ from Equation~\ref{eq:loss} for model parameters $\textbf{W}$ plus a penalty on $\epsilon_{mean}$, weighted by a tuning parameter $\lambda>0$ \begin{equation}\label{eq:objective} \underset{\textbf{W}}{\text{min}}[L_{\mathbf{\chi \cup \chi^{-}}}(\textbf{W}) + \lambda R_{\mathbf{\chi}}(\epsilon_{mean})] \end{equation} where $R_{\mathbf{\chi}}(\epsilon_{mean}) =max(0,\epsilon_{mean_{M_\mathbf{W}(\mathbf{\chi})}} - \epsilon_{mean_{0}})$ is the fairness penalty term, and $\epsilon_{mean_{M_\mathbf{W}(\mathbf{\chi})}}$ is the $\epsilon_{mean}$ for the CF model $M_\mathbf{W}(\mathbf{\chi})$ while $\chi$ and $\chi^{-}$ are the set of interacted and not-interacted user-item pairs, respectively. Setting the target $\epsilon_{mean_{0}}$ to 0 encourages demographic parity, while setting $\epsilon_{mean_{0}}$ to the dataset's empirical value penalizes any increase in the unfairness metric over ``societal bias'' in the data (which would in this case be presumed to be legitimate). In our experiments, we use $\epsilon_{mean_{0}}=0$. Pseudo-code for training the \emph{NFCF} algorithm is given in Algorithm~\ref{alg-nfcf}. We also consider an additional variant of the proposed framework, called \emph{NFCF\_embd}, which only de-biases the user embeddings to mitigate bias. In this algorithm, we compute the bias vector $v_B$ on the pre-trained user embeddings, fine-tune the model for sensitive item recommendations without any fairness penalty, and then de-bias the held-out user embeddings using the pre-computed bias vector. Since there is no additional fairness penalty with the objective, this algorithm converges faster. There is also no requirement to tune the $\lambda$ hyperparameter. \section{Experiments} In this section, we validate and compare our model with multiple baselines for recommending careers and academic concentrations using social media data. Our implementation's source code will be provided in the online. \subsection{Datasets} \begin{table}[t] \centering \small \resizebox{1.0\textwidth}{!}{ \begin{tabular}{llllllllllll} \toprule & \multicolumn{4}{c}{Non-sensitive Data} & \multicolumn{6}{c}{Sensitive Data} \\ \midrule & Users & Items & Pairs & Sparsity & & Users & Males & Females & Items & Pairs & Sparsity \\ \cline{2-5} \cline{7-12} \emph{MovieLens} Dataset & 6,040 & 3,416 & 999,611 & 95.16\% & & 4,920 & 3,558 & 1,362 & 17 & 4,920 & 94.12\% \\ \emph{Facebook} Dataset & 29,081 & 42,169 & 5,389,541 & 99.56\% & & 13,362 & 5,053 & 8,309 & 169 & 13,362 & 99.41\% \\ \bottomrule \end{tabular} } \caption{Statistics of the datasets. \label{tab:data}} \end{table} \begin{figure*}[t] \centerline{\includegraphics[width=0.98\textwidth]{./figures/gender_dist_all_update.pdf}} \caption{\small Gender distributions of example gender-biased careers and college majors for (a) \emph{MovieLens} and (b) \emph{Facebook} datasets. We report the distributions in the dataset (left columns), and corresponding top-$1$ recommendation by our NFCF model (right columns) } \label{fig:user_dist_all} \end{figure*} We evaluate our models on two datasets: \emph{MovieLens},\footnote{\url{http://grouplens.org/datasets/movielens/1m/}.} a public dataset which facilitates research reproducibility, and a \emph{Facebook} dataset which is larger and is a more realistic setting for a fair social media-based recommender system. \subsubsection{\textbf{MovieLens Data}} We analyzed the widely-used \emph{MovieLens} dataset which contains 1 million ratings of 3,900 movies by 6,040 users who joined MovieLens~\cite{harper2015movielens}, a noncommercial movie recommendation service operated by the University of Minnesota. We used \emph{gender} as the protected attribute, self-reported \emph{occupation} as the sensitive item (with one occupation per user), and \emph{movies} as the non-sensitive items. Since we focus on implicit feedback, which is common in a social media setting (e.g. page ``likes''), we converted explicit movie ratings to binary implicit feedback~\cite{koren2008factorization,he2017neural}, where a 1 indicates that the user has rated the item. We discarded movies that were rated less than 5 times, and users who declared their occupation as ``K-12 student,'' ``retired,'' ``unemployed,'' and ``unknown or not specified'' were discarded for career recommendation. A summary of the pre-processed dataset is shown in Table~\ref{tab:data}. \subsubsection{\textbf{Facebook Data}} The \emph{Facebook} dataset we analyzed was collected as part of the myPersonality project ~\cite{kosinski2015facebook}. The data for research were collected with opt-in consent. We used \emph{gender} as the protected attribute, \emph{college major} as the sensitive items (at most one per user), and \emph{user-page} interaction pairs as the non-sensitive items. A user-page interaction occurs when a user ``likes'' a Facebook page. We discarded pages that occurred in less than 5 user-page interactions. See Table~\ref{tab:data} for a summary of the dataset after pre-processing. \subsubsection{\textbf{Gender Distributions for Datasets}} In Figure~\ref{fig:user_dist_all}, we show disparities in the gender distributions of $10$ example careers and college majors for \emph{MovieLens} and \emph{Facebook} datasets, respectively. For example, 97\% of the associated users for the occupation \emph{homemaker} are women in the \emph{MovieLens} data, while there are only 27\% women among the users associated with the \emph{computer science} major in the \emph{Facebook} data. As a qualitative illustration, we also show the gender distribution of top-1 recommendations from our proposed NFCF model. NFCF mitigated gender bias for most of these sensitive items. In the above examples, NFCF decreased the percentage of women for \emph{homemaker} from 97\% to 50\%, while increasing the percentage of women for \emph{computer science} from 27\% to 48\%. \subsection{Baselines} \begin{table}[t] \centering \small \begin{tabular}{lcccc} \hline \multicolumn{5}{c}{\emph{MovieLens} Dataset}\\ \hline Models & HR@$10$ & NDCG@$10$ & HR@$25$ & NDCG@$25$ \\ \hline NCF & 0.543 & \textbf{0.306} & 0.825 & \textbf{0.377} \\ MF & \textbf{0.551} & 0.304 & \textbf{0.832} & 0.374 \\ \hline \end{tabular} \hspace{0.25 cm} \small \begin{tabular}{lcccc} \hline \multicolumn{5}{c}{\emph{Facebook} Dataset}\\ \hline Models & HR@$10$ & NDCG@$10$ & HR@$25$ & NDCG@$25$ \\ \hline NCF & \textbf{0.720} & \textbf{0.468} & \textbf{0.904} & \textbf{0.514} \\ MF & 0.609 & 0.382 & 0.812 & 0.434 \\ \hline \end{tabular} \caption{Performance of NCF and MF models for movie and Facebook page recommendations (the pre-training task) on the \emph{Movielens} and \emph{Facebook} datasets, respectively. \label{tab:preTrain_performance}} \end{table} \begin{figure*}[t] \centerline{\includegraphics[width=0.9\textwidth]{./figures/preTrain_benefit_both.pdf}} \caption{\small Comparison of proposed models with ``typical'' baselines that do not consider fairness. Evaluation of Top-$K$ career and college major recommendations on the (a) \emph{MovieLens} (among 17 unique careers) and (b) \emph{Facebook} (among 169 unique majors) datasets, where $K$ ranges from $1$ to $5$ and $1$ to $25$, respectively. \emph{NCF w/ Pre-train} outperforms all the baselines; NFCF performs similarly.} \label{fig:preTrain} \end{figure*} \begin{figure*}[t] \centerline{\includegraphics[width=0.95\textwidth]{./figures/debiasing_vectors_both.pdf}} \caption{\small De-biasing pre-trained user embeddings by removing the component along the bias direction $v_B$ (PCA projection) for the (a) \emph{MovieLens} and (b) \emph{Facebook} datasets. PCA was performed based on all embeddings.} \label{fig:debiasing_vectors} \end{figure*} We compare our proposed framework to the following ``typical'' baseline models without any fairness constraints: \begin{itemize} \item \textbf{MF w/o Pre-train}. Typical matrix factorization (MF) model which is trained with the user-item interactions for sensitive item recommendations, where the items contain both non-sensitive and sensitive items. \item \textbf{MF w Pre-train}. Typical MF model which is pre-trained with the interactions of user and non-sensitive items and fine-tuned with the interactions of users and sensitive items. Specifically, $q_{i}$, $b_i$, and $b_u$ from Equation~\ref{eq:MF} are fine-tuned while $p_{u}$ is kept fixed. \item \textbf{NCF w/o Pre-train}. Typical NCF model which is trained with the user-item interactions for sensitive item recommendations, where the items contain both non-sensitive and sensitive items. \item \textbf{NCF w Pre-train}. Typical NCF model which is pre-trained with the interactions of users and non-sensitive items and fine-tuned with the interactions of users and sensitive items. Specifically, $q_{i}$, ${W}_{l}$, and ${b}_{l}$ from Equation~\ref{eq:NCF} are fine-tuned while $p_{u}$ is kept fixed. \item \textbf{DNN Classifier}. A simple baseline where we train a DNN-based classifier to predict career labels given the interactions of users and non-sensitive items as features (i.e. binary features, one per user-page ``like'' or one per user-movie ``rating''). No user embeddings are learned. \item \textbf{BPMF}. We also used Bayesian probabilistic matrix factorization (BPMF) via MCMC~\cite{salakhutdinov2008bayesian} as a baseline, since it typically has good performance with small data. BPMF is trained on the user-item interactions for sensitive item recommendations, where the items contain both non-sensitive and sensitive items. \end{itemize} We also compared our proposed models with the following fair baseline models: \begin{itemize} \item \textbf{Projection-based CF}. This is our previous linear projection-based fair CF method~\cite{rashid}. First, NCF is trained using user and non-sensitive item data, followed by de-biasing user vectors by subtracting the component in the bias direction. Finally, a multi-class logistic regression model is trained on the de-biased user vectors to predict sensitive items. \item \textbf{MF-$U_{abs}$}. The learning objective of the MF model is augmented with a smoothed variation of $U_{abs}$~\cite{yao2017beyond} using the Huber loss~\cite{huber1992robust}, weighted by a tuning parameter $\lambda$. The MF-$U_{abs}$ model is trained with the user-item interactions for career recommendations, where the items include both non-sensitive and sensitive items. \item \textbf{Resampling for Balance}. This method~\cite{ekstrand2018all} involves pre-processing by resampling the training user-item data to produce a gender-balanced version of the data. First, we extract user-item data for users with known gender information and randomly sample the same number of male and female users without replacement. The items include both non-sensitive and sensitive items. Finally, NCF and MF are trained on the gender-balanced user-item data to perform sensitive item recommendation. \end{itemize} \begin{table*}[t] \centering \small \begin{tabular}{lcccccc} \toprule \multicolumn{7}{c}{\emph{MovieLens} Dataset}\\ \midrule Ablation study & HR@$5\uparrow$ & NDCG@$5\uparrow$ & HR@$7\uparrow$ & NDCG@$7\uparrow$ & $\epsilon_{mean}\downarrow$ & $U_{abs}\downarrow$ \\ \midrule NFCF & \textbf{0.670} & 0.480 & 0.822 & 0.536 & \textbf{0.083} & \textbf{0.009} \\ w/o pre-train & 0.493 & 0.323 & 0.731 & 0.446 & 0.112 & 0.017 \\ w/o de-biasing embeddings & 0.665 & \textbf{0.481} & \textbf{0.832} & \textbf{0.543} & 0.120 & 0.010 \\ w/o fairness penalty & 0.667 & 0.480 & 0.827 & 0.539 & 0.097 & 0.013 \\ replace NCF w/ MF & 0.514 & 0.350 & 0.707 & 0.423 & 0.122 & 0.021 \\ \bottomrule &&&&&&\\ \toprule \multicolumn{7}{c}{\emph{Facebook} Dataset}\\ \midrule Ablation study & HR@$10\uparrow$ & NDCG@$10\uparrow$ & HR@$25\uparrow$ & NDCG@$25\uparrow$ & $\epsilon_{mean}\downarrow$ & $U_{abs}\downarrow$ \\ \midrule NFCF & 0.551 & 0.326 & 0.848 & \textbf{0.401} & \textbf{0.302} & \textbf{0.024} \\ w/o pre-train & 0.339 & 0.127 & 0.587 & 0.224 & 0.613 & 0.038 \\ w/o de-biasing embeddings & 0.556 & \textbf{0.328} & 0.847 & 0.400 & 0.314 & \textbf{0.024} \\ w/o fairness penalty & \textbf{0.557} & 0.327 & \textbf{0.849} & \textbf{0.401} & 0.363 & 0.026 \\ replace NCF w/ MF & 0.297 & 0.112 & 0.427 & 0.194 & 0.880 & 0.071 \\ \bottomrule \end{tabular} \caption{Ablation study of \emph{NFCF} for career and college major recommendations on the \emph{MovieLens} and \emph{Facebook} datasets. Higher is better for HR and NDCG; lower is better for $\epsilon_{mean}$ and $U_{abs}$. Removing each model component harms performance and/or fairness. \label{tab:ablation_study}} \end{table*} \begin{figure*}[t] \centerline{\includegraphics[width=0.90\textwidth]{./figures/compare_fair_model.pdf}} \caption{\small Comparison of proposed models with fair baselines. Evaluation of Top-$K$ career and college major recommendations on the (a) \emph{MovieLens} (among 17 unique careers) and (b) \emph{Facebook} (among 169 unique majors) datasets, where $K$ ranges from $1$ to $5$ and $1$ to $25$, respectively. \emph{NFCF} outperforms all the baselines; \emph{NFCF\_embd} performs similarly.} \label{fig:compare_fair_model} \end{figure*} \begin{table*}[t] \centering \small \resizebox{1.0\textwidth}{!}{ \begin{tabular}{llcccccc} \toprule \multicolumn{8}{c}{\emph{MovieLens} Dataset}\\ \midrule & Models & HR@$5\uparrow$ & NDCG@$5\uparrow$ & HR@$7\uparrow$ & NDCG@$7\uparrow$ & $\epsilon_{mean}\downarrow$ & $U_{abs}\downarrow$ \\ \midrule \multirow{2}{*}{Proposed Models} & NFCF & \textbf{0.670} & 0.480 & 0.822 & 0.536 & \textbf{0.083} & \textbf{0.009} \\ & NFCF\_embd & 0.661 & 0.470 & \textbf{0.825} & 0.531 & 0.091 & 0.016 \\ \midrule \multirow{5}{*}{Typical Baselines} & NCF w Pre-train & 0.667 & \textbf{0.484} & \textbf{0.825} & \textbf{0.542} & 0.188 & 0.022 \\ & NCF w/o Pre-train & 0.570 & 0.360 & 0.762 & 0.432 & 0.244 & 0.026 \\ & MF w Pre-train & 0.548 & 0.362 & 0.747 & 0.436 & 0.285 & 0.060 \\ & MF w/o Pre-train & 0.622 & 0.397 & 0.820 & 0.471 & 0.130 & 0.020 \\ & DNN Classifier & 0.428 & 0.311 & 0.546 & 0.355 & 0.453 & 0.035 \\ & BPMF & 0.225 & 0.138 & 0.338 & 0.180 & 0.852 & 0.063 \\ \midrule \multirow{4}{*}{Fair Baselines} & Projection-based CF ~\cite{rashid} & 0.514 & 0.355 & 0.655 & 0.408 & 0.229 & 0.012 \\ & MF-$U_{abs}$ ~\cite{yao2017beyond} & 0.588 & 0.356 & 0.776 & 0.426 & 0.096 & 0.017 \\ & NCF via Resampling ~\cite{ekstrand2018all} & 0.443 & 0.295 & 0.622 & 0.362 & 0.144 & 0.022 \\ & MF via Resampling ~\cite{ekstrand2018all} & 0.542 & 0.332 & 0.759 & 0.413 & 0.103 & 0.029 \\ \bottomrule &&&&&&&\\ \toprule \multicolumn{8}{c}{\emph{Facebook} Dataset}\\ \midrule & Models & HR@$10\uparrow$ & NDCG@$10\uparrow$ & HR@$25\uparrow$ & NDCG@$25\uparrow$ & $\epsilon_{mean}\downarrow$ & $U_{abs}\downarrow$ \\ \midrule \multirow{2}{*}{Proposed Models} & NFCF & 0.551 & 0.326 & 0.848 & 0.401 & \textbf{0.302} & 0.024 \\ & NFCF\_embd & 0.557 & \textbf{0.333} & 0.850 & 0.397 & 0.359 & \textbf{0.022} \\ \midrule \multirow{5}{*}{Typical Baselines} & NCF w Pre-train & \textbf{0.559} & 0.329 & \textbf{0.851} & \textbf{0.403} & 0.376 & 0.027 \\ & NCF w/o Pre-train & 0.402 & 0.187 & 0.762 & 0.278 & 0.785 & 0.039 \\ & MF w Pre-train & 0.372 & 0.200 & 0.717 & 0.286 & 0.875 & 0.077 \\ & MF w/o Pre-train & 0.267 & 0.119 & 0.625 & 0.210 & 0.661 & 0.029 \\ & DNN Classifier & 0.379 & 0.212 & 0.630 & 0.274 & 0.633 & 0.070 \\ & BPMF & 0.131 & 0.066 & 0.339 & 0.117 & 1.173 & 0.084 \\ \midrule \multirow{4}{*}{Fair Baselines} & Projection-based CF ~\cite{rashid} & 0.419 & 0.244 & 0.674 & 0.307 & 0.407 & 0.030 \\ & MF-$U_{abs}$ ~\cite{yao2017beyond} & 0.163 & 0.007 & 0.627 & 0.184 & 0.629 & 0.026 \\ & NCF via Resampling ~\cite{ekstrand2018all} & 0.315 & 0.153 & 0.586 & 0.222 & 0.442 & 0.025 \\ & MF via Resampling ~\cite{ekstrand2018all} & 0.103 & 0.041 & 0.314 & 0.094 & 0.756 & 0.039 \\ \bottomrule \end{tabular} } \caption{Comparison of proposed models with the baselines in career and college major recommendations on \emph{MovieLens} (17 \emph{careers}) and \emph{Facebook} (169 \emph{majors}). Higher is better for HR and NDCG; lower is better for $\epsilon_{mean}$ and $U_{abs}$. NFCF greatly improves fairness metrics and beats all baselines at recommendation except for NCF w Pre-train, a variant of NFCF without its fairness correction. \label{tab:quantitative_results}} \end{table*} \begin{table*}[t] \centering \small \resizebox{0.8\textwidth}{!} { \begin{tabular}{llll} \toprule \multicolumn{4}{c}{\emph{MovieLens} Dataset}\\ \midrule \multicolumn{2}{c}{NFCF} & \multicolumn{2}{c}{NCF w/o Pre-train} \\ \midrule Male & Female & Male & Female \\ \midrule college/grad student & college/grad student & sales/marketing & customer service \\ executive/managerial & executive/managerial & academic/educator & academic/educator \\ academic/educator & technician/engineer & executive/managerial & artist \\ technician/engineer & academic/educator & doctor/health care & writer \\ programmer & programmer & college/grad student & college/grad student \\ \bottomrule &&&\\ \toprule \multicolumn{4}{c}{\emph{Facebook} Dataset}\\ \midrule \multicolumn{2}{c}{NFCF} & \multicolumn{2}{c}{NCF w/o Pre-train} \\ \midrule Male & Female & Male & Female \\ \midrule psychology & psychology & philosophy & psychology \\ english literature & english literature & psychology & nursing \\ graphic design & music & computer science & sociology \\ music & theatre & biochemistry & graphic design \\ nursing & nursing & business admin. & business marketing \\ liberal arts & history & political science & elementary education \\ business admin. & sociology & business management & cosmetology \\ biology & liberal arts & medicine & accounting \\ history & business admin. & law & physical therapy \\ criminal justice & biology & finance & music \\ \bottomrule \end{tabular} } \caption{Top 5 (among 17 unique careers) and 10 (among 169 unique majors) most frequent career and college major recommendations on the \emph{MovieLens} and \emph{Facebook} datasets, respectively, to the overall male and female users using \emph{NFCF} and \emph{NCF w/o Pre-train} models . \label{tab:qualitative}} \end{table*} \subsection{Experimental Settings} All the models were trained via adaptive gradient descent optimization (Adam) with learning rate = $0.001$ using pyTorch where we sampled $5$ negative instances per positive instance. The mini-batch size for all models was set to $2048$ and $256$ for user-page and user-career data, respectively, while the embedding size for users and items was set to $128$. The configuration of the DNN under \emph{NFCF} and \emph{NFCF\_embd} was $4$ hidden layers with $256$, $64$, $32$, $16$ neurons in each successive layer, ``relu'' and ``sigmoid'' activations for the hidden and output layers, respectively. We used the same DNN architecture for the \emph{NCF} and \emph{DNN Classifier} models. For the Facebook dataset, we held-out $1\%$ and $40\%$ from the user-page and user-college major data, respectively, as the test set, using the remainder for training. Since there are fewer users in the Movielens dataset, we held-out $1\%$ and $30\%$ from the user-movie and user-career data, respectively, as the test set, using the remainder for training. We further held-out $1\%$ and $20\%$ from the training user-nonsensitive item and user-sensitive item data, respectively, as the development set for each dataset. The tuning parameter $\lambda$ needs to be chosen as a trade-off between accuracy and fairness~\cite{foulds2018intersectional}. We chose $\lambda$ as $0.1$ for \emph{NFCF} and \emph{MF-$U_{abs}$} via a grid search on the development set according to similar criteria to ~\cite{foulds2018intersectional}, i.e. optimizing fairness while allowing up to $2\%$ degradation in accuracy from the typical model. To evaluate the performance of item recommendation on the test data, since it is too time-consuming to rank all items for every user during evaluation~\cite{he2017neural}, we followed a common strategy in the literature ~\cite{elkahky2015multi}. For non-sensitive items, we randomly sampled $100$ items which are not interacted by the user for each test instance, and ranked the test instance among the 100 items. For sensitive item recommendations, in the case of Facebook data we similarly randomly sampled $100$ college majors. For the MovieLens data, there are only $17$ unique careers, so we used the remaining $16$ careers when ranking the test instance. The performance of a ranked list is measured by the average Hit Ratio (HR) and Normalized Discounted Cumulative Gain (NDCG) ~\cite{he2015trirank}. The HR measures whether the test item is present in the top-$K$ list, while the NDCG accounts for the position of the hit by assigning higher scores to hits at top ranks. We calculated both metrics for each test user-item pair and reported the average score. Finally, we computed $\epsilon_{mean}$ and $U_{abs}$ on the test data for user-sensitive item to measure the fairness of the models in career and college major recommendations. \subsection{Validation of NFCF Model Design} Before comparing to fair recommendation baseline models, we systematically validate our modeling choices for NFCF. \textbf{Pre-training Task Performance:} We first study the performance for NCF and MF model at the pre-training task, \emph{Facebook page} and \emph{movie} recommendations (Table~\ref{tab:preTrain_performance}). NCF had substantially and consistently better performance compared to MF on the larger \emph{Facebook} dataset, and similar overall performance on \emph{MovieLens} (better in 2 of 4 metrics). \textbf{Fine-Tuning Performance:} We fine-tuned these models on the interaction of users with the sensitive items for \emph{career} and \emph{college major} recommendations on \emph{MovieLens} and \emph{Facebook} dataset, respectively. Figure~\ref{fig:preTrain} shows top-$K$ recommendations from $17$ and $169$ unique \emph{careers} and \emph{college majors} using several ``typical'' baseline models that do not involve any fairness constraints, where $K$ ranges from $1$ to $5$ and $1$ to $25$ for MovieLens and Facebook dataset, respectively. \emph{NCF w/ Pre-train} had the best performance in HR and NDCG versus other baselines while our proposed \emph{NFCF} and \emph{NFCF\_embd} performed approximately similarly to \emph{NCF w/ Pre-train} for both datasets. Of the typical baselines, \emph{MF w/o Pre-train} and \emph{NCF w/o Pre-train} performed the second best for \emph{MovieLens} and \emph{Facebook} dataset, respectively. For the \emph{MovieLens} dataset, \emph{MF w/o Pre-train} performed better than \emph{MF w/ Pre-train}, presumably due to the relatively small dataset and having relatively few parameters to fine-tune, unlike for the DNN-based NCF model. \emph{BPMF} performed poorly despite using Bayesian inference for scarce data, perhaps due to \cite{salakhutdinov2008bayesian}'s initialization via older MF methods. \textbf{Visualization of Embedding De-biasing:} We visualized the PCA projections of the male and female vectors (Equation~\ref{eq:female}) before and after the linear projection-based de-biasing embeddings method, where PCA was performed based on all the embeddings. Figure~\ref{fig:debiasing_vectors} shows that the male and female vectors have very different directions and magnitudes. After de-biasing, the male and female vectors had a more similar direction and magnitude to each other. \textbf{Ablation Study:} Finally, we conducted an ablation study in which the components of the method were removed one at a time. As shown in Table~\ref{tab:ablation_study}, there was a large degradation of the performance of \emph{NFCF} when pre-training was removed (de-biasing embeddings step was also removed, since there was no pre-trained user vector), or when NCF was replaced by MF. Removing the de-biased embedding method lead to better HR and NDCG scores, but with an increase in the gender bias metrics. Similarly, learning without the fairness penalty lead to similar performance in HR and NDCG, but greatly increased gender bias. Therefore, \emph{\textbf{both} of the bias correction methods in the NFCF model are necessary to achieve the best level of fairness while maintaining a high recommendation accuracy}. \subsection{Performance for Mitigating Gender Bias in Sensitive Item Recommendations} We evaluated performance for career and college major recommendations in terms of accuracy (HR and NDCG) and fairness ($\epsilon_{mean}$ and $U_{abs}$). In Figure~\ref{fig:compare_fair_model}, we show that our proposed \emph{NFCF} and \emph{NFCF\_embd} models clearly outperformed all the fair baseline models in terms of HR and NDCG, regardless of the cut-off $K$. \emph{Projection-based CF} performed the second best on both datasets out of all the fair models. In Table~\ref{tab:quantitative_results}, we show detailed results for the top $5$ and top $7$ recommendations on \emph{MovieLens} and for the top $10$ and top $25$ recommendations on the \emph{Facebook} dataset. Our proposed \emph{NFCF} model was the most fair career and college major recommender in terms of $\epsilon_{mean}$, while our \emph{NFCF\_embd} was the most fair in terms of $U_{abs}$ on the \emph{Facebook} dataset. In the case of the \emph{MovieLens} dataset, our \emph{NFCF} model was the most fair recommender model in terms of both fairness metrics. \emph{NCF w/ Pre-train} performed best in the HR and NDCG metrics on both datasets. \emph{NFCF} and \emph{NFCF\_embd} had nearly as good HR and NDCG performance as \emph{NCF w/ Pre-train}, while also mitigating gender bias. We also found that the pre-training and fine-tuning approach reduced overfitting for \emph{NCF w/ Pre-train}, and thus improved the fairness metrics by reducing bias amplification. This was not the case for \emph{MF w/ Pre-train}, presumably due to the limited number of pre-trained parameters to fine-tune. \emph{Projection-based CF} and \emph{MF-$U_{abs}$} also showed relatively good performance in mitigating bias in terms of $U_{abs}$ compared to the typical models, but with a huge sacrifice in the accuracy. Similarly, \emph{NCF via Resampling} and \emph{MF via Resampling} had poor performance in accuracy, but improved fairness to some extent over their corresponding ``typical'' models, \emph{NCF w/o Pre-train} and \emph{MF w/o Pre-train}, respectively. As a further qualitative experiment, we recommended the top-$1$ career and college major to each test male and female user via the \emph{NFCF} and \emph{NCF w/o Pre-train} models. In Table~\ref{tab:qualitative}, we show top $5$ and $10$ most frequent recommendations to the overall male and female users among the $17$ and $169$ unique careers and majors for \emph{MovieLens} and \emph{Facebook} dataset, respectively. \emph{NFCF} was found to recommend similar careers to both male and female users on average for both datasets, while \emph{NCF w/o Pre-train} encoded societal stereotypes in its recommendations. For example, \emph{NCF w/o Pre-train} recommends \emph{computer science} to male users and \emph{nursing} to female users on the \emph{Facebook} dataset while it recommends \emph{executive/managerial} to male users and \emph{customer service} to female users on the \emph{MovieLens} dataset. \section{Conclusion} We investigated gender bias in social-media based collaborative filtering. To address this problem, we introduced Neural Fair Collaborative Filtering (NFCF), a pre-training and fine-tuning method which corrects gender bias for recommending sensitive items such as careers or college majors with little loss in performance. On the \emph{MovieLens} and \emph{Facebook} datasets, we achieved better performance and fairness compared to an array of state-of-the-art models. \bibliographystyle{coling}
{'timestamp': '2020-09-21T02:18:11', 'yymm': '2009', 'arxiv_id': '2009.08955', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08955'}
arxiv
\section{Introduction} XX is an important problem in machine learning and healthcare. (Make sure that the clinicians can see the relevance! \emph{Unclear clinical relevance is a major reason that otherwise strong-looking papers are scored low/rejected.}) Addressing this problem is challenging because XX. (Make sure that you connect to the machine learning here.) Others have tried, but XX remains tough. (Acknowledge related work.) In this work, we... As you write, keep in mind that MLHC papers are meant to be read by computer scientists and clinicians. In the later sections, you might have to use some medical terminology that a computer scientist may not be familiar with, and you might have to use some math that a clinician might not be familiar with. That's okay, as long as you've done your best to make sure that the core ideas can be understood by an informed reader in either community. \subsection*{Generalizable Insights about Machine Learning in the Context of Healthcare} This section is \emph{required}, must keep the above title, and should be the final part of your introduction. In about one paragraph, or 2-4 bullet points, explain what we should \emph{learn} from reading this paper that might be relevant to other machine learning in health endeavors. For example, a work that simply applies a bunch of existing algorithms to a new domain may be useful clinically but doesn't increase our understanding of the machine learning and healthcare; if that study also investigates \emph{why} different approaches have different performance, that might get us excited! A more theoretical machine learning work may be in how it enables a new kind of clinical study. \emph{Reviewers and readers will look to evaluate (a) the significance of your claimed insights and (b) evidence you provide later in the work of you achieving that contribution} \section{Related Work} Make sure you also put your awesomeness in the context of related work. Who else has worked on this problem, and how did they approach it? What makes your direction interesting or distinct? \section{Methods} Tell us your techniques! If your paper is develops a novel machine learning method or extension, then be sure to give the technical details---as you would for a machine learning publication---here and, as needed, in appendices. If your paper is developing new methods and/or theory, this section might be several pages. If you are combining existing methods, feel free to cite other packages and papers and tell us how you put them together; that said, the work should stand alone for someone in that general machine learning area. \emph{Lack of technical details, such that the soundness of the methods can be verified, is a major reason that otherwise strong-looking papers are scored low/rejected.} \section{Cohort} \emph{This section is optional, more theoretical work may not need this section. However, if you are using health data, then you need to describe it carefully so that the clinicians can validate the soundness of your choices.} Describe the cohort. Give us the details of any inclusion/exclusion criteria, what data were extracted, how features were processed, etc. Recommended headings include: \subsection{Cohort Selection} with choice of criteria and basic numbers, as well as any relevant information about the study design (such how cases and controls were identified, if appropriate), \subsection{Data Extraction} with what raw information you extracted or collected, including any assumptions and imputation that may have been used, and \subsection{Feature Choices} with how you might have converted the raw data into features that were used in your algorithm. Cohort descriptions are just as important as methods details and code to replicate a study. For more clinical application papers, each of the sections above might be several paragraphs because we really want to understand the setting. For the submission, please do \emph{not} include the name of the institutions for any private data sources. However, in the camera-ready, you may include identifying information about the institution as well as should include any relevant IRB approval statements. \subsection{Results on Synthetic Experiments} \emph{Depending on the claim you make in the paper, this section may not be relevant.} Especially if you are developing a new method, you will want to demonstrate its properties on synthetic or semi-synthetic experiments. Include experiments that will help us understand the contribution of the work to machine learning and healthcare. \section{Results on Real Data} \emph{Depending on the claim you make in the paper, different components may be important for this section.} \subsection{Evaluation Approach/Study Design} Before jumping into the results: what exactly are you evaluating? Tell us (or remind us) about your study design and evaluation criteria. \subsection{Results on Application A} Present your numbers and baselines. You should provide a summary of the results in the text, as well as in tables (such as table~\ref{tab:example}) and figures (such as figure~\ref{fig:example}). You may use subfigures/wrapfigures so that figures don't have to span the whole page or multiple figures are side by side. \begin{table}[htbp] \centering \caption{Description with the main take-away point.} \begin{tabular}{|l|l|}\hline Us & Score \\ \hline Baseline & Score \\ \hline \end{tabular} \label{tab:example} \end{table} \begin{figure}[htbp] \centering \includegraphics[width=1.5in]{smile.jpeg} \caption{Description with the main take-away point.} \label{fig:example} \end{figure} \subsection{Results on Application/Follow-up Study B} \section{Required: Discussion} \emph{This is probably the most important section of your paper! This is where you tell us how your work advances our understanding of machine learning and healthcare.} Discuss both technical and clinical implications, as appropriate. \paragraph{Limitations} Explain when your approach may not apply, or things you could not check. \emph{Discussing limitations is essential. Both ACs and reviewers have been coached to be skeptical of any work that does not consider limitations.} \section{Introduction} Type 1 diabetes (T1D) is a chronic disease affecting 20-40 million people worldwide \citep{you_type_2016}, and its incidence is increasing \citep{tuomilehto_emerging_2013}. People with T1D cannot produce insulin, a hormone that controls blood glucose levels, and must monitor their blood glucose levels and manually administer insulin doses as needed. Administering too little insulin can lead to hyperglycemia (high blood glucose levels), which results in chronic health complications \citep{control_resource_1995}, while administering too much insulin results in hypoglycemia (low blood glucose levels), leading to coma or death. Getting the correct dose requires careful measurement of glucose levels and carbohydrate intake, resulting in at least 15-17 data points a day. When using a continuous glucose monitor (CGM), this can increase to over 300 data points, or a blood glucose reading every 5 minutes \citep{coffen_magnitude_2009}. CGMs with an insulin pump, a device that delivers insulin, can be used with a closed-loop controller as an `artificial pancreas' (AP). Though the technology behind CGMs and insulin pumps has advanced, there remains significant room for improvement when it comes to the control algorithms \citep{bothe_use_2013, pinsker_randomized_2016}. Current hybrid closed-loop approaches require accurate meal announcements to maintain glucose control. In this work, we investigate deep reinforcement learning (RL) for blood glucose control. RL is a promising solution, as it is well-suited to learning complex behavior and readily adapts to changing domains \citep{clavera2018learning}. We hypothesize that deep RL, the combination of RL with a deep neural network, will be able to accurately infer latent meals to control insulin. Furthermore, as RL is a learning-based approach, we hypothesize that RL will adapt to predictable meal schedules better than baseline approaches. The fact that RL is learning-based means it requires data to work effectively. Unlike many other health settings, there are credible simulators for blood glucose management \citep{visentin_university_2014}. Having a simulator alleviates many concerns of applying RL to health problems \citep{gottesman2018evaluating, gottesman_guidelines_2019}. However, that does not mean RL for blood glucose control is straightforward, and, in this paper, we identify and address several challenges. To the best of our knowledge, we present the first deep RL approach that achieves human-level performance in controlling blood glucose without requiring meal announcements. \subsection*{Generalizable Insights about Machine Learning in the Context of Healthcare} Applying deep RL to blood glucose management, we encountered challenges broadly relevant for RL in healthcare. As such, we believe our solutions and insights, outlined below, are broadly relevant as well. \begin{itemize} \item The range of insulin and carbohydrate requirements across patients makes it difficult to find a single action space that balances the needs of rapid insulin administration and safety. Indeed, many health problems involve changes in action distributions across patients (\textit{e.g.} in anesthesia dosing \citep{bouillon_size}). To solve this problem, we present a robust patient-specific action space that naturally encourages safer policies. \item We found several pitfalls in evaluating our proposed approach that led to unrealistic performance estimates. To address this issue, we used validation data to perform careful model selection, and used extensive test data to evaluate the quality of our models. In RL, it is typical to report performance on the final trained model (without model selection) over a handful of rollouts. Our experiments demonstrate the danger of this approach. \item Deep RL has been shown to be unstable \citep{rlblogpost, henderson_deep_2018}, often achieving poor worst-case performance. This is unacceptable for safety-critical tasks, such as those in healthcare. We found that a combination of simple and widely applicable approaches stabilized performance. In particular, we used a safety-augmented reward function, realistic randomness in training data, and random restarts to train models that behaved safely over thousands of days of evaluation. \item Finally, unlike game settings where one has ability to learn from hundreds of thousands of hours of interaction, any patient-specific model must be able to achieve strong performance using a limited amount of data. We show that a simple transfer learning approach can be remarkably sample efficient and can even surpass the performance of models trained from scratch. \end{itemize} \section{Background and Related Work} This work develops and applies techniques in reinforcement learning to the problem of blood glucose management. To frame this work, we first provide a brief introduction to RL, both in general and specifically applied to problems in healthcare. We then discuss how RL and other approaches have been used for blood glucose control and present an overview on blood glucose simulation. \subsection{Reinforcement Learning}\label{sec:rl} RL is an approach to optimize sequential decision making in an environment, which is typically assumed to follow a Markov Decision Process (MDP). An MDP is characterized by a 5-tuple $(S, A, P, R, \gamma)$, where $s \in S$ are the states of the environment, $a \in A$ are actions that can be taken in the environment, the transition function $P: (s, a) \rightarrow s'$ defines the dynamics of the environment, the reward function $R: (s, a) \rightarrow r \in \mathbb{R}$ defines the desirability of state-action pairs, and the discount factor $\gamma \in [0, 1]$ determines the tradeoff between the value of immediate and delayed rewards. The goal in RL is to learn a policy $\pi: s \rightarrow a$, or function mapping states to actions, that maximizes the expected cumulative reward, or: \begin{equation} \arg\max_{\pi \in \Pi} \sum_{t=1}^{\infty} E_{s_t \sim P(s_{t-1}, a_{t-1})}[\gamma^t R(s_t, \pi(s_t))], \end{equation} where $\Pi$ is the space of possible policies and $s_0 \in S$ is the starting state. The state value function, $V(s)$, is the expected cumulative reward where $s_0 = s$. The state-action value function $Q(s,a) = R(s,a) + E_{s' \sim P(s, a)}[\gamma V(s')]$ extends the notion of value to state-action pairs. \subsection{Reinforcement Learning in Healthcare} In recent years, researchers have started to explore RL in healthcare. Examples include matching patients to treatment in the management of sepsis \citep{weng_representation_2017, komorowski_artificial_2018} and mechanical ventilation \citep{prasad_reinforcement_2017}. In addition, RL has been explored to provide contextual suggestions for behavioral modifications \citep{klasnja_efficacy_2019}. Despite its successes, RL has yet to be fully explored as a solution for a closed-loop AP system \citep{bothe_use_2013}. \subsection{Algorithms for Blood Glucose Control} Among recent commercial AP products, proportional-integral-derivative (PID) control is the most common backbone \citep{trevitt_artificial_2015}. The simplicity of PID controllers make them easy to use, and in practice they achieve strong results \citep{steil2013algorithms}. The Medtronic Hybrid Closed-Loop system, one of the few commercially available, is built on a PID controller \citep{garg_glucose_2017, ruiz_effect_2012}. A hybrid closed-loop controller adjusts baseline insulin rates but requires human intervention to control for the effect of meals. The main weakness of PID controllers is their reactivity. As a result, they often cannot react fast enough to meals, and thus rely on meal announcements \citep{garg_glucose_2017}. Additionally, without safety modifications, PID controllers can deliver too much insulin, triggering hypoglycemia \citep{ruiz_effect_2012}. In contrast, we hypothesize that an RL approach will be able to leverage patterns associated with meal times, resulting in more responsive and safer policies. Previous works have examined RL for different aspects of blood glucose control. See \cite{tejedor_reinforcement_2020} for a recent survey. Many of these works investigated the use of RL to adapt existing insulin treatment regimens to learn a ‘human-in-the-loop’ policy \citep{ngo_reinforcement-learning_2018, oroojeni_mohammad_javad_reinforcement_2015, sun_dual_2018}. This contrasts with our setting, where we aim to learn a fully closed-loop policy. Like our work, \cite{daskalaki_preliminary_2010} and \cite{de_paula_-line_2015} focus on the task of closed-loop glucose control. \cite{daskalaki_preliminary_2010} use direct future prediction to aid PID-style control, substituting the problem of RL with prediction. \cite{de_paula_-line_2015} use a policy-iteration framework with Gaussian process approximation and Bayesian active learning. While they tackle a similar problem, these works use a simple simulator and a fully deterministic meal routine for training and testing. In our experiments, we use an FDA-approved glucose simulator and a realistic non-deterministic meal schedule, significantly increasing the challenge. \subsection{Glucose Models and Simulation} Models of the glucoregulatory system are important for the development and testing of an AP \citep{cobelli_integrated_1982}. In our experiments, we use the UVA/Padova model \citep{kovatchev_silico_2009}. This simulator models the glucoregulatory system as a nonlinear multi-compartment system, where glucose is generated in the liver, absorbed through the gut, and controlled by external insulin. A more detailed explanation can be found in \cite{kovatchev_silico_2009}. For reproducibility, we use an open-source version of the simulator that comes with 30 virtual patients \citep{xie_simglucose_2018}. The parameter distribution of the patient population is determined by age, and the simulator comes with 10 children, adolescents, and adults each \cite{kovatchev_silico_2009}. We combine the simulator with a non-deterministic meal schedule (\textbf{Appendix \ref{app:meal}}) to realistically simulate patient behavior. \section{Methods} We present a deep RL approach well suited for blood glucose control. In framing our problem, we pay special attention to the concerns of partial observability and safety. The issue of partial observability motivates us to use a maximum entropy control algorithm, soft actor-critic, combined with a recurrent neural network. Safety concerns inspire many aspects of our experimental setup, including our choice of action space, reward function, and evaluation metrics. We also introduce several strong baselines, both with and without meal announcements, to which we compare. \subsection{Problem Setup}\label{ssec:setup} We frame the problem of closed-loop blood glucose control as a partially-observable Markov decision process (POMDP) consisting of the 7-tuple $(S^*, O, S, A, P, R, \gamma)$. A POMDP generalizes the MDP setting described in \textbf{Section \ref{sec:rl}} by assuming we do not have access to the true environment states, here denoted $s^* \in S^*$, but instead observe noisy states $s \in S$ according to the (potentially stochastic) observation function: $O: s^* \rightarrow s$. This setting applies given the noise inherent in CGM sensors \citep{vettoretti2019modeling} and our assumption of unobserved meals. In our setting, the true states $\mathbf{s}^*_t \in S^*$ are the 13-dimensional simulator states, as described in \cite{kovatchev_silico_2009}. The stochastic observation function $O: \mathbf{s}^*_t \rightarrow b_t, i_t$ maps from the simulator state to the CGM observation $b_t$ and insulin $i_t$ administered. To provide temporal context, we augment our observed state space $\mathbf{s}_t \in S$ to include the previous 4 hours of CGM $\mathbf{b}^t$ and insulin data $\mathbf{i}^t$ at 5-minute resolution: $\mathbf{s}_t = [\mathbf{b}^t, \mathbf{i}^t]$ where: $$ \mathbf{b}^t = [b_{t-47}, b_{t-46}, \dots, b_{t}], \mathbf{i}^t = [i_{t-47}, i_{t-46}, \dots, i_{t}], $$ $b_{t} \in \mathbb{N}_{40:400}$, $i_{t} \in \mathbb{R}_{+}$, and $t \in \mathbb{N}_{1:288}$ represents a time index for a day at 5-minute resolution. Note that in our augmented formulation, the observation function no longer directly maps to observed states, as observed states incorporate significant amounts of historical data. We chose a 4-hour window, as we empirically found it led strong performance. We use a time resolution of 5 minutes to mimic the sampling frequency of many common CGMs. Actions $a_t \in \mathbb{R}_{\ge 0}$ are real positive numbers, denoting the size of the insulin bolus in medication units. The transition function $P$, our simulator, consists of two elements: i) $M: t \rightarrow c_t$ is the meal schedule, and is defined in \textbf{Appendix \ref{app:meal}}, and ii) $G: (a_t, c_t, \mathbf{s}^*_t) \rightarrow (b_{t+1}, i_{t+1}, \mathbf{s}^*_{t+1})$, where $c_t \in \mathbb{R}_{\ge 0}$ is the amount of carbohydrates input at time $t$ and $G$ is the UVA/Padova simulator \citep{kovatchev_silico_2009}. Note that our meal schedule is patient-specific, and includes randomness in the daily number, size, and timing of meals. The reward function $R: (\mathbf{s}_t, a_t) \rightarrow \mathbb{R}$ is defined as negative $-risk(b_t)$ where $risk$ is the Magni risk function: \begin{equation} risk(b) = 10*(c_0 * \log(b)^{c_1}-c_2)^2, \end{equation} $c_0=3.35506$, $c_1=0.8353$, and $c_2=3.7932$ \citep{magni_model_2007}. These values are set such that $risk(70)=risk(280)=25$, see \textbf{Figure \ref{fig:risk}}. Finally, we set $\gamma=0.99$ for our experiments, a value we determined empirically on validation data in combination with the early termination penalty. Considered in isolation, our reward could lead to dangerous behavior. As it is always negative, cumulative reward is maximized by ending the episode as quickly as possible, which occurs when glucose reaches unsafe levels. To avoid this, we add a termination penalty of $-1e5$ to trajectories that enter dangerous blood glucose regimes (blood glucose levels less than 10 or more than 1,000 mg/dL), countering the advantage of early termination. We investigated other reward functions, such as time in range or distance from a target blood glucose value, but found this reward worked best. It led to control schemes with less hypoglycemia, as low blood glucose is penalized more heavily than high glucose. Low glucose can occur quickly when large amounts of insulin are given without an accompanying meal. Given the lack of meal announcements and sensor noise in our setting, avoiding hypoglycemia was a significant challenge. \begin{figure} \centering \includegraphics[width=0.45\linewidth]{figures/magni_risk_post.pdf} \caption{The risk function proposed in \citep{magni_model_2007}. The mapping between blood glucose values (in mg/dL, x-axis) and risk values (y-axis). Blood glucose levels corresponding to hypoglycemia are shown in the blue shaded region, the glucose range corresponding to hyperglycemia is shown in the red shaded region. This function identifies low blood glucose values as higher risk than high blood glucose values, which is sensible given the rapidity of hypoglycemia.} \label{fig:risk} \end{figure} \subsection{Soft Actor-Critic} We chose to use the soft actor-critic (SAC) algorithm to learn glucose control policies. We initially experimented with a Deep-Q Network approach \citep{mnih_human-level_2015}. However, choosing a discretized action space (as is required by Q-learning) that accounted for the range of insulin values across a day and allowed exploration proved impractical, as large doses of inappropriately timed insulin can be dangerous. Among continuous control algorithms, we selected SAC as it has been shown to be sample efficient and competitive \citep{haarnoja_soft_2018}. Additionally, maximum entropy policies like the ones produced by SAC can do well in partially observed settings like our own \citep{eysenbach2019if}. SAC produces a stochastic policy $\pi: \mathbf{s}_t \rightarrow p(a)$ $\forall a \in A$, which maps a state to a distribution over possible actions. Under SAC, the policy (or actor) is represented by a neural network with parameters $\phi$. Our network generates outputs $\mu, \log(\sigma)$ which parameterize a normal distribution $\mathcal{N}(\mu, \sigma)$. The actions are distributed according to a TanhNormal distribution, or $tanh(z), z \sim \mathcal{N}(\mu, \sigma)$. $\pi_\phi$ is trained to maximize the maximum entropy RL objective function: \vspace{-1pt} \begin{equation}\label{eqn:policy_return} J(\pi) = \sum_{t=0}^T \mathbb{E}_{(\mathbf{s}_t, a_t) \sim P(\mathbf{s}_{t-1}, \pi_\phi(\mathbf{s}_{t-1}))} [R(\mathbf{s}_t, a_t) + \alpha H(\pi_\phi(\cdot|\mathbf{s}_t))], \end{equation} \vspace{-1pt} where entropy, $H$, is added to the expected cumulative reward to improve exploration and robustness \citep{haarnoja_soft_2018}. Intuitively, the return in \textbf{Equation \ref{eqn:policy_return}} encourages a policy that can obtain a high reward under a variety of potential actions. The temperature hyperparameter $\alpha$ controls the tradeoff between reward and entropy. In our work, we set this using automatic temperature tuning \citep{haarnoja_soft_2018a}. \textbf{Equation \ref{eqn:policy_return}} is optimized by minimizing the KL divergence between the action distribution and the distribution induced by the state-action values: \vspace{-1pt} \begin{equation}\label{eqn:pi} J_{\pi}(\phi)=\mathbb{E}_{\mathbf{s}_{t} \sim \mathcal{D}}\left[\mathrm{D}_{\mathrm{KL}}\left(\pi_{\phi}\left(\cdot | \mathbf{s}_{t}\right) \| \frac{\exp \left(Q_{\theta}\left(\mathbf{s}_{t}, \cdot\right)\right)}{Z_{\theta}\left(\mathbf{s}_{t}\right)}\right)\right] \end{equation} \vspace{-1pt} where $\mathcal{D}$ is a replay buffer containing previously seen $(\mathbf{s}_t, \mathbf{a}_t, r_t, \mathbf{s}_{t+1})$ tuples, $Z_\theta$ is a partition function, and $Q_\theta$ is the state-action value function parameterized by a neural network (also called a critic). This means that our learned policy engages in probability matching, selecting an action with probability proportional to its expected value. This requires an accurate value function. To achieve this, $Q_\theta$ is trained by minimizing the temporal difference loss: \begin{gather}\label{eqn:q} J_{Q}(\theta)=\mathbb{E}_{\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right) \sim \mathcal{D}}\left[\frac{1}{2}\left(Q_{\theta}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)-\hat{Q}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)\right)^{2}\right], \\ \hat{Q}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)=r\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)+\gamma \mathbb{E}_{\mathbf{s}_{t+1} \sim p}\left[V_{\overline{\psi}}\left(\mathbf{s}_{t+1}\right)\right]. \end{gather} \vspace{-1pt} $V_\psi$ is the soft value function parameterized by a third neural network, and $V_{\overline{\psi}}$ is the running exponential average of the weights of $V_\psi$ over training. This is a continuous variant of the hard target network replication in \citep{mnih_human-level_2015}. $V_\psi$ is trained to minimize: \begin{equation}\label{eqn:v} J_{V}(\psi)=\mathbb{E}_{\mathbf{s}_{t} \sim \mathcal{D}}\left[\frac{1}{2}\left(V_{\psi}\left(\mathbf{s}_{t}\right)-\mathbb{E}_{\mathbf{a}_{t} \sim \pi_{\rho}}\left[Q_{\theta}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)-\log \pi_{\phi}\left(\mathbf{a}_{t} | \mathbf{s}_{t}\right)\right]\right)^{2}\right]. \end{equation} In summary: we learn a policy that maps from states to a probability distribution over actions, the policy is parameterized by a neural network $\pi_\phi$. Optimizing this network (\textbf{Equation \ref{eqn:pi}}) requires an estimation of the soft state-action value function, we learn such an estimate $Q_\theta$ (\textbf{Equation \ref{eqn:q}}) together with a soft value function $V_\psi$ (\textbf{Equation \ref{eqn:v}}). Additional details of this approach, including the gradient calculations, are given in \citep{haarnoja_soft_2018}. In keeping with previous work, when testing our policy we remove the sampling component, instead selecting the mean action $tanh(\mu)$. We replace the MSE temporal difference loss in \textbf{Equation} \ref{eqn:q} with the Huber loss, as we found this improved convergence. \subsubsection{Recurrent Architecture}\label{sec:architecture} Our network $\pi_\phi$ takes as input the past 4 hours of CGM and insulin data, requiring no human input (\textit{i.e.}, no meal announcements). To approximate the true state $\mathbf{s}^*_t$ from the augmented state $s$ we parameterize $Q_\theta$, $V_\psi$, and $\pi_\phi$ using gated-recurrent unit (GRU) networks \citep{cho_learning_2014}, as GRUs have been successfully used for glucose modeling previously \citep{fox_deep_2018, zhu_deep_nodate}. \subsubsection{Patient-Specific Action Space} After the network output layer, actions are squashed using a \textit{tanh} function. Note that this results in half the action space corresponding to negative values, which we interpret as administering no insulin. This encourages sparse insulin utilization and makes it easier for the network to learn to safely control baseline glucose levels. To ensure that the maximum amount of insulin delivered over a 5-minute interval is roughly equal to a normal meal bolus for each individual, we use the average ratio of basal to bolus insulin in a day \citep{kuroda_basal_2011} to calculate a scale parameter for the action space, $\omega_{b}=43.2*bas$, where $bas$ is the default patient-specific basal insulin rate provided by \cite{xie_simglucose_2018}. \subsection{Efficient Policy Transfer} One of the main disadvantages of deep RL is sample efficiency. Thus, we explored transfer learning techniques to efficiently transfer existing models to new patients. We refer to our method trained from scratch as RL-Scratch, and the transfer approach as RL-Trans. For RL-Trans, we initialize $Q_\theta, V_\psi$ and $\pi_\phi$ for each class of patients (children, adolescents, and adults) using fully trained networks from one patient of that source population (see \textbf{Appendix \ref{app:patient}}). We then fine-tune these networks on data collected from the target patient. When fine-tuning, we modify the reward function by removing the termination penalty and adding a constant positive value (100) to all rewards. This avoids the negative reward issue discussed in \textbf{Section \ref{ssec:setup}}. Removing the termination penalty increased the consistency of returns over training, allowing for a more consistent policy gradient. The additional safety provided by a termination penalty is not required as we begin with policies that are already stable. We found this simple approach for training patient-specific policies attains good performance while using far less patient-specific data. \subsection{Baselines} We examine three baseline methods for control: basal-bolus (\textbf{BB}), \textbf{PID} control, and PID with meal announcements (\textbf{PID-MA}). BB reflects an idealized human-in-the-loop control strategy, and PID reflects a common closed-loop AP algorithm. PID with meal announcements is based on current AP technology, and is a combination of the two, requiring regular human intervention. Finally, we consider an 'oracle' approach that has access to the true state $s^*_t$. This decouples the task of learning a policy from state inference, serving as a pseudo-upper bound on performance for our proposed approach. \subsubsection{Basal-Bolus Baseline} This baseline is designed to mimic human control and is an ideal depiction of how an individual with T1D controls their blood glucose. In this setting, we modify the state representation $\mathbf{s}_t$ to include a carbohydrate signal and a cooldown signal (explained below), and to remove the historical data, $\mathbf{s}_t = [b_t, i_t, c_t, cooldown]$. Note that the inclusion of a carbohydrate signal, or meal announcement, places the burden of providing accurate and timely estimates of meals on the person with diabetes. Each virtual patient in the simulator comes with the parameters necessary to calculate a reasonable basal insulin rate $bas$ (the same value used in our action space definition), correction factor $CF$, and carbohydrate ratio $CR$. These three parameters, together with a glucose target $b_g$, define a clinician-recommended policy $\pi(s_t) = bas + (c_t > 0) * (\frac{c_t}{CR} + cooldown * \frac{b_t - b_g}{CF})$ where $cooldown$ is 1 if there have been no meals in the past three hours, otherwise it is 0. The cooldown ensures that each meal is only corrected for once. Appropriate settings for these parameters can be estimated by endocrinologists, using previous glucose and insulin information \citep{walsh_guidelines_2011}. The parameters for our virtual patient population, which are derived from a distribution validated by clinical trials \citep{kovatchev_silico_2009}, are given in \textbf{Appendix \ref{app:bb}}. \subsubsection{PID Baseline} PID controllers are a common and robust closed-loop baseline \citep{steil2013algorithms}. A PID controller operates by setting the control variable, $a_t$, to the weighted combination of three terms $a_t = k_P P(b_t) + k_I I(b_t) + k_D D(b_t)$ such that the process variable $b_t$ ($t$ is the time index) remains close to a specified setpoint $b_g$. The terms are calculated as follows: i) the proportional term $P(b_t)=\max(0, b_t - b_g)$ increases the control variable proportionally to the distance from the setpoint, ii) the integral term $I(b_t) = \sum_{j=0}^t (b_j - b_g)$ corrects long-term deviations from the setpoint, and iii) the derivative term $D(b_t) = |b_{t} - b_{t-1}|$ uses the rate of change as a basic estimate of the future. The set point and the weights (also called gains) $k_P, k_I, k_D$ are hyperparameters. To compare against the strongest PID controller possible, we tuned these hyperparameters using multiple iterations of grid-search with exponential refinement per-patient, minimizing risk. Our final settings are presented in \textbf{Appendix \ref{app:pid_param}}. \subsubsection{PID with Meal Announcements.} This baseline, which is similar to available hybrid closed loop AP systems \citep{garg_glucose_2017, ruiz_effect_2012}, combines BB and PID into a control algorithm we call PID-MA. During meals, insulin boluses are calculated and applied as in the BB approach. The basal rate, instead of being fixed, is controlled by a PID algorithm, allowing for adaptation between meals. As above, we tune the gain parameters for the PID algorithm using sequential grid search to minimize risk. \subsubsection{Oracle Architecture} A deep RL approach to learning AP algorithms requires that the representation learned by the network contain sufficient information to control the system. As we are working with a simulator, we can explore the difficulty of this task in isolation, by replacing the observed state $\mathbf{s}_t$ with the ground-truth state $\mathbf{s}^*_t$. Though unavailable in real-world settings, this representation decouples the problem of learning a policy from that of inferring the state. Here, $Q_\theta$, $V_\psi$, and $\pi_\phi$ are fully connected with two hidden layers, each with 256 units. The network uses ReLU nonlinearities and BatchNorm \citep{ioffe2015batch}. \subsection{Experimental Setup \& Evaluation} To measure the utility of deep RL for the task of blood glucose control, we trained and tested our policies on data with different random seeds across 30 different simulated individuals. \paragraph{Training and Hyperparameters.} We trained our models separately for each patient. They were trained from scratch for 300 epochs for RL-Scratch, and fine-tuned for 50 epochs for RL-Trans. They were trained with batch size 256 and an epoch length of 20 days. We used an experience replay buffer of size 1e6 and a discount factor of 0.99. We found that extensive training from-scratch was required to obtain consistent performance across test runs. We also found that too small of an epoch length could lead to dangerous control policies. We optimized the parameters of $Q_\theta$, $V_\psi$ and $\pi_\phi$ using Adam with a learning rate of $3E-4$. All deep networks were composed of two layers of GRU cells with a hidden state size of 128, followed by a fully-connected output layer. All network hyperparameters, including number and size of layers, were optimized on training seeds on a subset of the simulated patients for computational efficiency. Our networks were initialized using PyTorch defaults. \paragraph{Evaluation.} We measured the performance of $\pi_\phi$ on 10 days of validation data after each training epoch. After training, we evaluated on test data using the model parameters from the best epoch as determined by the validation data. While this form of model selection is not typical for RL, we found it led to significant changes in performance (see \textbf{Section \ref{sec:val_selection}}). Our model selection procedure first filters out runs that could not control blood glucose within safe levels over the validation run (glucose between 30-1000 mg/dL), then selects the epoch that achieved the lowest risk. We tested each patient-specific model on 1000 days of test data, broken into 100 independent 10 day rollouts. We trained and evaluated each approach 3 times, resulting in 3000 days of evaluation per method per person. We evaluated approaches using i) risk, the average Magni risk calculated over the 10-day test rollout, ii) \% time spent euglycemic (blood glucose levels between 70-180 mg/dL), iii) \% time hypo/hyperglycemic (blood glucose lower than 70 mg/dL or higher than 180 mg/dL respectively), and iv) \% of rollouts that resulted in a catastrophic failure, which we define as a run that achieves a minimal blood glucose level below 5 mg/dL (at which point recovery becomes highly unlikely). Note that while catastrophic failures are a major concern, our simulation process does not consider consuming carbohydrates in reaction to low blood glucose levels. This is a common strategy to avoid dangerous hypoglycemia in real life, and thus catastrophic failures, while serious, are manageable. The random seeds controlling noise, meals, and all other forms of randomness, were different between training, validation, and test runs. We test the statistical significance of differences between methods using Mood's median test for all metrics except for catastrophic failure rate, for which we use a binomial test. \section{Experiments and Results} Our experiments are divided into two broad categories: i) experiments showing the benefits of deep RL for blood glucose control relative to baseline approaches and ii) the challenges of using deep RL in this setting, and how to overcome them. Throughout our experiments, we consider 3 variants of RL methods: i) RL-Scratch, our approach trained from scratch on every individual, ii) RL-Trans, which fine-tunes an RL-Scratch model from an arbitrary child/adolescent/adult, and iii) RL-MA, which uses RL-Scratch trained using the automated meal boluses from BB or PID-MA. We also report results on an Oracle approach, which is trained and evaluated using the ground truth simulator state. \begin{figure*}[!htbp] \centering \includegraphics[width=\linewidth]{figures/noma_risk.png} \caption{The risk over 10 days for different simulated patients using methods that do not require meal announcements. Each point corresponds to a different random test seed that controls the meal schedule and sensor noise, and the line indicates the median performance for each method on each patient. Results are presented across 3 random training seeds, controlling model initialization and randomness in training. We observe that, although there is a wide range in performance across and within individuals, The RL approaches tend to outperform PID.} \label{fig:full_risk_noma} \end{figure*} \begin{figure*}[!htbp] \centering \includegraphics[width=\linewidth]{figures/ma_risk.png} \caption{The risk over 10 days using methods that require meal announcements. PID-MA tends to outperform BB, and RL-MA outperforms PID-MA.} \label{fig:full_risk_ma} \end{figure*} \subsection{Advantages of Deep RL}\label{sec:advantages} We compare our deep RL approaches to baselines with and without meal announcements across several metrics (\textbf{Section \ref{ssec:baseline}}). We then investigate two hypotheses for why deep RL is well suited to the problem of glucose management without meal announcements: \begin{itemize} \item the high-capacity neural network, integral to the RL approaches, is able to quickly infer when meals occur (\textbf{Section \ref{ssec:meals}}), and \item the learning-based approach is able to adapt to predictable meal schedules better than a PID controller (\textbf{Section \ref{ssec:behavior}}). \end{itemize} \subsubsection{Deep RL vs. Baseline Approaches}\label{ssec:baseline} A comparison between the PID baseline to the RL approaches is presented in \textbf{Figure \ref{fig:full_risk_noma}}. Each point represents a different test rollout by a policy. For the RL approaches, the performance of each method is reported as the combination of 3 random training restarts. Among the 3 methods that do not require meal announcements, RL-Scratch performs best across patients (average rank 1.33), followed by RL-Trans (average rank 1.7), then PID (average rank 2.97). For each individual, we rank the 3 approaches in terms of median risk. We calculate average rank by taking the mean of each approach's rankings across all 30 individuals. Note that RL-Scratch, while achieving strong performance overall, reliably performs poorly on adolescent\#002. We discuss this issue in \textbf{Appendix \ref{app:ao2}}. One major advantage of our proposed approach is its ability to achieve strong performance without meal announcements. This does not mean that it does not benefit from meal announcements, as shown in \textbf{Figure \ref{fig:full_risk_ma}}. Among the 3 methods that require meal announcements, RL-MA performs best (average rank 1.07), followed by PID-MA (average rank 2.13) then BB (average rank 2.8). We examine additional metrics in the results presented in \textbf{Table \ref{tab:risk}}. The difference between results that are bold, or bold and underlined, and the next best non-bold result (excluding RL-Oracle) are statistically significant with $p<0.001$. We observe that RL-MA equals or surpasses the performance of all non-oracle methods on all metrics, except for \% time spent hyperglycemia. Interestingly, all RL variants achieve lower median risk than PID-MA, which requires meal announcements. This is because the RL approaches achieve low levels of hypoglycemia, which the risk metric heavily penalizes (see \textbf{Figure \ref{fig:risk}}). Note that all methods, including PID-MA, were optimized to minimize this metric. Across patients, the RL methods achieve approximately 60-80\% time euglycemic, compared with $52\% \pm 19.6$\% observed in real human control \citep{ayanotakahara_carbohydrate_2015}. These results suggest that deep RL could be a valuable tool for closed-loop or hybrid closed-loop AP control. \begin{table*}[!htbp] \centering \caption{Median risk, percent of time Eu/Hypo/Hyperglycemic, and failure rate calculated using 1000 days of simulation broken into 100 independent 10-day rollouts for each of 3 training seeds for 30 patients, totaling 90k days of evaluation (with interquartile range). Lower Magni Risk, Hypoglycemia, and Hyperglycemia are better, higher Euglycemia is better. Hybrid and Non-closed loop approaches (requiring meal announcements) are indicated with *. Approaches requiring a fully observed simulator state are indicated with $\dagger$. The non-oracle approach with the best average score is in bold and underlined, the best approach that does not require meal announcements is in bold.} \scalebox{0.83}{ \begin{tabular}{lcccccc} \toprule & & Risk & Euglycemia & Hypoglycemia & Hyperglycemia & Failure \\ & & $\downarrow$ & (\%) $\uparrow$ & (\%) $\downarrow$ & (\%) $\downarrow$ & (\%) $\downarrow$ \\ \midrule \multirow[c]{3}{*}{\rotatebox[origin=c]{90}{No MA}} & PID & 8.86 (6.8-14.3) & 71.68 (65.9-75.9) & 1.98 (0.3-5.5) & \textbf{24.71 (21.1-28.6)} & 0.12 \\ & RL-Scratch & \textbf{6.50 (4.8-9.3)} & \textbf{72.68 (67.7-76.2)} & \textbf{0.73 (0.0-1.8)} & 26.17 (23.1-30.6) & \textbf{0.07} \\ & RL-Trans & 6.83 (5.1-9.7) & 71.91 (66.6-76.2) & 1.04 (0.0-2.5) & 26.60 (22.7-31.0) & 0.22 \\ \hline \multirow[c]{3}{*}{\rotatebox[origin=c]{90}{MA}} & BB$^*$ & 8.34 (5.3-12.5) & 71.09 (62.2-77.9) & 2.60 (0.0-7.2) & 23.85 (17.0-32.2) & 0.26 \\ & PID-MA$^*$ & 8.31 (4.7-10.4) & 76.54 (70.5-82.0) & 3.23 (0.0-8.8) & \bf{\underline{18.74 (12.9-23.2)}} & \bf{\underline{0.00}} \\ & RL-MA$^*$ & \bf{\underline{4.24 (3.0-6.5)}} & \bf{\underline{77.12 (71.8-83.0)}} & \bf{\underline{0.00 (0.0-0.9)}} & 22.36 (16.6-27.7) & \bf{\underline{0.00}} \\ \midrule & RL-Oracle$^\dagger$ & 3.58 (1.9-5.4) & 78.78 (73.9-84.9) & 0.00 (0.0-0.0) & 21.22 (15.1-26.1) & 0.01 \\ \bottomrule \end{tabular} } \label{tab:risk} \end{table*} \subsubsection{Detecting Latent Meals}\label{ssec:meals} Our approach achieves strong blood glucose control without meal announcements, but how much of this is due to the ability to react to meals? To investigate this, we looked at the total proportion of insulin delivered on average after meals for PID and RL-Scratch, shown in \textbf{Figure \ref{fig:rl_advantage}a}. A method able to infer meals should use insulin rapidly after meals, as the sooner insulin is administered the faster glycemic spikes can be controlled while avoiding hypoglycemia. We observe that RL-Scratch administers the majority of its post-meal bolus within one hour of a meal, whereas PID requires over 90 minutes, suggesting RL-Scratch can indeed better infer meals. Interestingly, when considering the percentage of total daily insulin administered in the hour after meals, RL-Scratch responds even more aggressively than BB or PID-MA (54.7\% \textit{vs.} 48.5\% and 47.3\% respectively). This demonstrates that our RL approach is able to readily react to latent meals shortly after they have occurred. \subsubsection{Ability to Adapt to Predictable Meal Schedules}\label{ssec:behavior} We hypothesize that one advantage of RL is its ability to compensate for predictable variations (such as meals) in the environment, improving control as the environment becomes more predictable. To test this benefit, we changed the meal schedule generation procedure outlined in \textbf{Algorithm \ref{alg:schedule}} (\textbf{Appendix \ref{app:meal}}) for Adult 1. We removed the small `snack' meals, set all meal occurrence probabilities to 1, and made meal amounts constant (\textit{i.e.}, each day Adult 1 consumes an identical set of meals). We then evaluated both the PID model and RL-Scratch on 3 variations of this environment, characterized by the standard deviation of the meal times (either 0.1, 1, or 10 hours). This tests the ability of each method to take advantage of patterns in the environment. As the standard deviation decreases, the task becomes easier for two reasons: i) there are fewer instances where two meals occur in quick succession, and ii) the meals become more predictable. The results are presented in \textbf{Figure \ref{fig:rl_advantage}b}. We observe that both methods improve in performance as the standard deviation decreases, likely due to (i). However, while RL-Scratch outperforms PID under all settings, the difference increases as the standard deviation of meal times decreases, suggesting RL is better able to leverage the predictability of meals. Specifically, mean risk decreases by roughly 12\% for the PID approach (from 9.65 to 8.54), whereas it decreases nearly 24\% for the RL approach (from 8.40 to 6.42). This supports our hypothesis that RL is better able to take advantage of predictable meal schedules. \vspace{-3pt} \begin{figure} \centering \begin{subfigure}{} \includegraphics[width=.4\linewidth]{figures/percent_tdi.pdf} \end{subfigure} \begin{subfigure}{} \includegraphics[width=.4\linewidth]{figures/time_std_euglycemic.pdf} \end{subfigure} \caption{a) The average amount of insulin (in percent of total daily insulin) provided after meals for PID and RL-Scratch (note: RL-Trans, unshown, is very similar to RL-Scratch). RL-Scratch is able respond to meals more quickly than PID, with insulin peaking 30 minutes post-meal as opposed to roughly 60 minutes for PID. Additionally, the RL approach finishes delivering most post-meal insulin after 1hr, PID takes over 90 minutes. b) The distribution of average risk scores over 300 10-day rollouts for Adult 1 using meal schedules with varying amounts of predictability (meal time standard deviation). While PID performs better with more regularly spaced meals (median risk lowers from 9.66 at std=10 to 8.53 at std=0.1, a 12\% decrease), RL-Scratch sees a larger proportional and absolute improvement (median risk lowers from 8.33 at std=10 to 6.36 at std=0.1, a 24\% decrease).}\label{fig:rl_advantage} \end{figure} \subsection{Challenges for Deep RL} While in the previous section we demonstrated several advantages of using deep RL for blood glucose control, here we emphasize that the application of deep RL to this task and its evaluation are non-trivial. Specifically, in this section we: \begin{itemize} \item demonstrate the importance of our action space formulation for performance (\textbf{Section \ref{ssec:actionspace}}), \item illustrate the critical need for careful and extensive validation, both for model selection and evaluation (\textbf{Section \ref{sec:val_selection}}). \item show that, applied naively, deep RL leads to an unacceptable catastrophic failure rate, and present three simple approaches to improve this (\textbf{Section \ref{ssec:failures}}), \item address the issue of sample complexity with simple policy transfer (\textbf{Section \ref{ssec:transfer}}). \end{itemize} \subsubsection{Developing an Effective Action Space}\label{ssec:actionspace} One challenging element of blood glucose control in an RL setting is defining the action space. Insulin requirements vary significantly by person (from 16 to 60 daily units in the simulator population we use), and throughout most of the day, insulin requirements are much lower than after meals. To account for these challenges, we used a patient-specific action space, where much of the space corresponds to delivering no insulin (discussed in \textbf{Section \ref{sec:architecture}}). We perform an ablation study to test the impact of these decisions. On an arbitrarily chosen patient (child\#001), we shifted the $tanh$ output to remove the negative insulin space. This increased the catastrophic failure rate from 0\% (on this patient) to 6.6\%. On a challenging subset of 4 patients (indicated in \textbf{Appendix \ref{app:bb}}), we looked at the effect of removing the patient-specific action scaling $\omega_b$. This resulted in a 13\% increase in median risk from 9.92 to 11.23. These results demonstrate that a patient-specific action space that encourages conservative behavior can improve performance. \subsubsection{Potential Pitfalls in Evaluation}\label{sec:val_selection} In our experiments, we observed two key points for model evaluation: i) while often overlooked in RL, using validation data for model selection during training was key to achieving good performance, and ii) without evaluating on far more data than is typical, it was easy to underestimate the catastrophic failure rate. \paragraph{Performance instability necessitates careful model selection.} Off-policy RL with function approximation, particularly deep neural networks, is known to be unstable \citep{sutton_reinforcement_2018, gottesman2018evaluating}. As a result, we found it was extremely important to be careful in selecting which network (and therefore policy) to evaluate. In \textbf{Figure \ref{fig:validation_selection}a}, we show the fluctuation in validation performance over training for Adult\#009. While performance increases on average over the course of training (at least initially), there are several points where performance degrades considerably. \textbf{Figure \ref{fig:validation_selection}b} shows how performance averaged over all patients changes depending on the approach used to select the policy for evaluation. When we simply evaluate using the final epoch, almost half of test rollouts end in a catastrophic failure. Surprisingly, even when we select the model that minimized risk on the validation set, nearly a fifth of rollouts fail. However, by first limiting our pool of models to those that achieve a minimum blood glucose level of at least 30 mg/dL over the validation data, we reduce the catastrophic failure rate to $0.07\%$. As performance instability has been noted in other RL domains \citep{islam_reproducibility_2017, henderson_deep_2018}, this observation is likely relevant to other applications of deep RL in healthcare. \begin{figure}[!htbp] \centering \begin{subfigure} \centering \includegraphics[width=0.45\linewidth]{figures/unstable_training.pdf} \label{fig:validation_curve} \end{subfigure} \begin{subfigure}{} \includegraphics[width=0.4\linewidth]{figures/validation_selection.pdf} \label{fig:validation_perf} \end{subfigure} \caption{a) The training and validation curve (average reward) for adult\#009. Note the periods of instability affect both training and validation performance. b) Catastrophic failure rate over all patients for 3 methods of model selection: i) selecting the final training epoch, ii) selecting the epoch that achieved minimal risk, and iii) selecting the minimal risk epoch that maintained blood glucose above 30 mg/dL. We see large differences in performance depending on the model selection strategy.}\label{fig:validation_selection} \end{figure} \paragraph{Extensive evaluation is necessary.} Health applications are often safety critical. Thus, the susceptibility of deep RL to unexpected or unsafe behavior can pose a significant risk \citep{leike2017ai, futoma_identifying_2020}. While ongoing work seeks to provide safety guarantees in control applications using deep learning \citep{achiam_constrained_2017, futoma_identifying_2020}, it is important that practitioners take every step to evaluate the safety of their approaches. While it is typical to evaluate RL algorithms on a small number of rollouts \citep{henderson_deep_2018}, in our work we saw how easy it can be to miss unsafe behavior, even with significant testing. We examined the number of catastrophic failures that occurred using RL-Trans using different evaluation sets. Over our full evaluation set of 9,000 10-day rollouts, we observed 20 catastrophic failures (a rate of 0.22\%). However, when we only evaluated using the first 5 test seeds, which is still over 12 years of data, we observed 0 catastrophic failures. Additionally, when we evaluated using 3-day test rollouts instead of 10, we only observed only 5 catastrophic failures (a rate of .05\%), suggesting that longer rollouts result in a higher catastrophic failure rate. These results demonstrate that, particularly when dealing with noisy observations, it is critical to evaluate potential policies using a large number of different, lengthy rollouts. \subsubsection{Reducing Catastrophic Failures}\label{ssec:failures} Due to their potential danger, avoiding catastrophic failures was a significant goal of this work. The most direct approach we used was to modify the reward function, using a large termination penalty to discourage dangerous behavior. While unnecessary for fine-tuning policies, when training from scratch this technique was crucial. On a subset of 6 patients (see \textbf{Appendix \ref{app:patient}}), including the termination penalty reduced the catastrophic failure rate from $4.2\%$ to $0.2\%$. We found varying the training data also had a major impact on the catastrophic failure rate. During training, every time we reset the environment we used a different random seed (which controls meal schedule and sensor noise). Note that the pool of training, validation, and test seeds were non-overlapping. On a challenging subset of 7 patients (described in \textbf{Appendix \ref{app:patient}}), we ran RL-Scratch with and without this strategy. The run that varied the training seeds had a catastrophic failure rate of $0.15\%$, the run that didn't had a $2.05\%$ rate (largely driven by adult\#009, who reliably had the highest catastrophic failure rate across experiments). Other approaches can further improve stability. In \textbf{Table \ref{tab:risk}}, our RL results are averaged over three random restarts in training. This was done to demonstrate that our learning framework is robust to randomness in training data and model initialization. However, in a real application it would make more sense to select (using validation data) one model for use out of the random restarts. We apply this approach in \textbf{Table \ref{tab:ss_risk}}, choosing the seed that obtained the best performance according to our model selection criteria. This improves all the RL methods. Most notably, it further reduces the catastrophic failure rate for the approaches without meal announcements (0.07\% to 0\% for RL-Scratch, and 0.22\% to 0.13\% for RL-Trans). \begin{table*}[t!] \centering \caption{Risk and percent of time Eu/Hypo/Hyperglycemic calculated for the RL approaches treating the 3 training seeds as different random restarts. The stability of the Scratch and Trans approaches improves relative to performance in Table \ref{tab:risk}.} \scalebox{0.89}{ \begin{tabular}{lccccc} \toprule & Risk & Euglycemia & Hypoglycemia & Hyperglycemia & Failure Rate \\ & $\downarrow$ & (\%) $\uparrow$ & (\%) $\downarrow$ & (\%) $\downarrow$ & (\%) $\downarrow$ \\ \midrule RL-Scratch & 6.39 (4.7-8.9) & 72.96 (69.1-76.6) & 0.62 (0.0-1.7) & 25.96 (22.7-29.6) & 0.00 \\ RL-Trans & 6.57 (5.0-9.3) & 71.56 (67.0-75.7) & 0.80 (0.0-1.9) & 27.19 (23.4-31.2) & 0.13 \\ RL-MA & 3.71 (2.7-6.3) & 77.36 (72.7-83.2) & 0.00 (0.0-0.5) & 22.45 (16.7-26.9) & 0.00 \\ \bottomrule \end{tabular} } \label{tab:ss_risk} \end{table*} \subsubsection{Sample Efficiency and Policy Transfer}\label{ssec:transfer} While RL-Scratch achieves strong performance on average, it requires a large amount of patient-specific data: 16.5 years per patient. While RL-Trans reduced this amount, it still required over 2 years of patient-specific data, which for most health applications would be infeasible. Thus, we investigated how performance degrades as less data is used. In \textbf{Figure \ref{fig:finetune}}, we show the average policy performance by epoch for both RL-Scratch and RL-Trans relative to the PID controller. Note the epoch determines the maximum possible epoch for our model selection, not the actual chosen epoch. We see that far less training is required to achieve good performance with RL-Trans. In over 40\% of rollouts, RL-Trans outperforms PID with no patient-specific data (median risk 10.31), and with 10 epochs of training (roughly half a year of data) RL-Trans outperforms PID in the majority of rollouts (59.6\%; median risk 7.95). Interestingly, the lack of patient-specific data does not appear to cause excessive catastrophic failures. With no patient-specific data the failure rate is 0\%, after 5 epochs of training it has risen to .5\%, and then declines over training to the final value of .22\%. This implies two things: i) patient-specific training can increase the catastrophic failure rate, possibly by learning overly aggressive treatment policies, and ii) our current model selection procedure does not minimize the catastrophic failure rate. We do not observe this for RL-Scratch, where all epochs under 50 achieve a catastrophic error rate of over 17\%. These results suggest that our simple transfer approach can be effective even with limited amounts of patient-specific data. \begin{figure} \centering \includegraphics[width=.5\linewidth]{figures/finetuning_per_epoch.pdf} \caption{The proportion of test rollouts where RL-Scratch and RL-Trans outperform the median PID risk with different amounts of patient-specific training. We see that without any patient-specific data RL-Trans performs better than PID in 40\% of rollouts. RL-Scratch requires a significant amount of patient-specific data before achieving comparable performance.}\label{fig:finetune} \end{figure} \section{Conclusion} In this work, we demonstrated how deep RL can lead to significant improvements over alternative approaches to blood glucose control, with and without meal announcements (\textbf{Section \ref{ssec:baseline}}). We provide insight into why (\textbf{Section \ref{ssec:meals}}) and when (\textbf{Section \ref{ssec:behavior}}) we would expect to see RL perform better. We demonstrated the importance of a robust action space in patient-specific tasks (\textbf{Section \ref{ssec:actionspace}}), showed how careful and extensive validation is necessary for realistic evaluation of performance(\textbf{Section \ref{sec:val_selection}}), investigated several simple and general approaches to improving the stability of deep RL (\textbf{Section \ref{ssec:failures}}), and developed a simple approach to reduce the requirements of patient-specific data (\textbf{Section \ref{ssec:transfer}}). While the main goal of this paper was to advance a clinical application, the challenges we encountered and the solutions they inspired are likely to be of interest to researchers applying RL to healthcare more broadly. While our results in applying deep RL to blood glucose control are encouraging, they come with several limitations. First, our results are based on simulation. The simulator may not adequately capture variation across patients or changes in the glucoregulatory system over time. In particular, the virtual patient population the simulator comes equipped with does not differentiate individuals based on demographic information, such as gender and ethnicity. Thus, the applicability of our proposed techniques to all relevant patient populations cannot be assessed. However, as an FDA-approved substitute for animal trials \citep{kovatchev_silico_2009}, success in using this simulator is a nontrivial accomplishment. Second, we define a reward function based on risk. Though optimizing this risk function should lead to tight glucose control, it could lead to excess insulin utilization (as its use is unpenalized). Future work could consider resource-aware variants of this reward. Third, our choice of a 4-hour state space discourages learning long-term patterns or trends. In our environment, this did not reduce performance relative to a longer input history, but this could be important for managing blood glucose levels in more realistic simulators or real-world cases \cite{visentin_uva/padova_2018}. Finally, we emphasize that blood glucose control is a safety-critical application. An incorrect dose of insulin could lead to life-threatening situations. Many of the methods we examined, even those that achieve good average performance, are susceptible to catastrophic failures. We have investigated several ways to minimize such failures, including modifying the reward function and selecting models across multiple random restarts. While the results from \textbf{Table \ref{tab:ss_risk}} suggest these approaches mitigate catastrophic failures, the results of \textbf{Section \ref{sec:val_selection}} show such empirical evaluations can miss failure cases. To enable researchers to better explore and correct these limitations, we evaluated on an open-source simulator and made all the code required to reproduce our experiments publicly available. \acks{This work was supported by JDRF. The views and conclusions in this document are those of the authors and should not be interpreted as necessarily representing the official policies, either expressed or implied of JDRF.} \section{Introduction} Type 1 diabetes (T1D) is a chronic disease affecting 20-40 million people worldwide \citep{you_type_2016}, and its incidence is increasing \citep{tuomilehto_emerging_2013}. People with T1D cannot produce insulin, a hormone that signals cells to uptake glucose in the bloodstream and must continually make decisions about how much insulin to self-administer. Administering too little insulin can lead to hyperglycemia (high blood glucose levels), which results in chronic health complications \citep{control_resource_1995}, while administering too much insulin results in hypoglycemia (low blood glucose levels), which can lead to coma or death. Getting the correct dose requires careful measurement of glucose levels and carbohydrate intake, resulting in at least 15-17 data points a day. When using a continuous glucose monitor (CGM), this can increase to over 300 data points, or a blood glucose reading every 5 minutes \citep{coffen_magnitude_2009}. Combined with an insulin pump, a wearable device that delivers insulin, CGMs present an opportunity for closed-loop control, called an `artificial pancreas' (AP). Though the technology behind CGMs and insulin pumps has advanced, there remains significant room for improvement when it comes to the control algorithms \citep{bothe_use_2013, pinsker_randomized_2016}. In particular, current hybrid closed-loop approaches require accurate and timely meal announcements to maintain tight glucose control and are not readily able to adapt to latent behavioral patterns. In this work, we investigate the utility of a deep reinforcement learning (RL) based approach for blood glucose control. RL is a promising solution to this problem, as it is well-suited to learning complex behavior that readily adapts to changing domains \citep{clavera2018learning}. When combined with a deep neural network for state inference, we hypothesize that RL will be able to infer the presence of latent meals efficiently, and adapt well to existing behavioral patterns. Moreover, unlike many other disease settings, there exist credible simulators for blood glucose management \citep{visentin_university_2014}. The presence of a credible simulator alleviates many common concerns of RL applied to problems in health \citep{gottesman_guidelines_2019}. However, that does not mean applying deep RL to this problem is straightforward. In this paper, we identify several challenges in this application, and make significant progress in addressing them. As a result of our proposed solutions, we present the first deep RL approach that surpasses human-level performance in controlling blood glucose without requiring meal announcements. \subsection*{Generalizable Insights about Machine Learning in the Context of Healthcare} Throughout our work in applying deep RL to blood glucose management, we encountered several challenges that extend beyond our particular application to problems more generally in applying RL in a healthcare setting. As such, we believe the solutions to these problems and the insights that inspired them will be of more general interest as well. Specifically: \begin{enumerate} \item Due to large differences between individuals insulin responsiveness and meal patterns, it is difficult to find a single action space that allows for rapid insulin administration while ensuring safety. To solve this problem, we developed a robust action space that encompass a range of different individuals and naturally encourages safe policies. Robust action spaces are relevant to any RL problem in healthcare where action distributions are likely to change across patients. \item We found several potential pitfalls in evaluating our proposed approach that could lead to unrealistically pessimistic or optimistic performance assessments. To address this issue, we used validation data to perform careful model selection, and extensive test data to evaluate the quality of our selected models. In RL, it is typical to report performance on the final trained model (without model selection) over a handful of rollouts. Our experiments demonstrate the danger of this approach. \item While deep RL has been shown to perform well in several tasks, it has also been shown to be brittle and unstable \citep{rlblogpost}, characteristics that are unacceptable in a safety-critical task. We found that to stabilize the test performance of our approaches, a combination of simple and widely applicable approaches was sufficient. In particular, we used a safety-augmented reward function, realistic randomness in training data, and model selection over random restarts to train an approach that behaved safely over thousands of days of evaluation data for each patient. \item Finally, unlike game settings where one has ability to learn from hundreds of thousands of hours of interaction, any learning approach to blood glucose control must be able to achieve strong performance using only a limited number of days of patient-specific data. While a great deal of work has been done on learning policies that generalize well across multiple tasks \cite{teh2017distral}, we show that a simple transfer learning approach can be remarkably sample efficient and can even surpass the performance of models trained from scratch. This insight in encouraging to RL applications in healthcare, as it suggests patient-specific policies can be learned without large amounts of patient-specific data. \end{enumerate} \section{Background and Related Works} In recent years, researchers have started to explore RL in healthcare. Examples include matching patients to treatment in the management of sepsis \citep{weng_representation_2017, komorowski_artificial_2018} and mechanical ventilation \citep{prasad_reinforcement_2017}. In addition, RL has been explored to provide contextual suggestions for behavioral modifications \citep{klasnja_efficacy_2019}. Despite its success in other problem settings, RL has yet to be fully explored as a solution for a closed-loop AP system \citep{bothe_use_2013}. \subsection{Current AP algorithms and RL for Blood Glucose Control} Among recent commercial AP products, proportional-integral-derivative (PID) control is one of the most common backbones \citep{trevitt_artificial_2015}. The simplicity of PID controllers make them easy to use, and in practice they achieve strong results \citep{steil2013algorithms}. For example, the Medtronic Hybrid Closed-Loop system, one of the few commercially available, is built on a PID controller \citep{garg_glucose_2017, ruiz_effect_2012}. In this setting, a hybrid closed-loop controller automatically adjusts basal insulin rates, but still requires human-directed insulin boluses to adjust for meals. The main weakness of PID controllers, in the setting of blood glucose control, is their reactivity. As they only respond to current glucose values (including a derivative), often they cannot react fast enough to meals to satisfactorily control glucose excursions without meal announcements \citep{garg_glucose_2017}. And, without additional safety modifications, PID controllers can overcorrect for meal spikes, triggering hypoglycemia \citep{ruiz_effect_2012}. In contrast, we hypothesize that an RL approach will be able to leverage patterns associated with meal times, resulting in better policies that do not require meal announcements. Several previous works have examined the use of RL for different aspects of blood glucose control. See \cite{tejedor_reinforcement_2020} for a recent survey. Several recent works have investigated the use RL to adapt existing insulin treatment regimes \citep{ngo_reinforcement-learning_2018, oroojeni_mohammad_javad_reinforcement_2015, sun_dual_2018}. In contrast to our setting, in which we aim to learn a closed-loop control policy, these works have focused on a ‘human-in-the-loop’ setting, in which the goal is to learn optimal correction factors and carbohydrate ratios that can be used in the calculation of boluses, which rely on humans consistently providing accurate and timely meal announcmeents. Similar to our own work, \cite{daskalaki_preliminary_2010} and \cite{de_paula_-line_2015} focus on the task of closed-loop glucose control. \cite{daskalaki_preliminary_2010} uses a model-based actor-critic formulation. Their critic directly predicts future glucose values from which state values are derived. The actor is an unlearned PID-style controller that uses current glucose value and state value to control glucose. While their work focuses on closed loop control, it substitutes the problem of RL with future prediction. In \cite{de_paula_-line_2015}, a kernelized Q-learning framework is used for closed loop glucose control. They make use of Bayesian active learning for on-the-fly personalization. \cite{de_paula_-line_2015} tackles a similar problem to our own, but uses a simple two-compartment model for the glucoregulatory system and a fully deterministic meal routine for testing. In our simulation environment, we found that Q-learning did not lead to satisfactory closed-loop performance and instead we examine deep actor-critic algorithms for continuous control. \subsection{Glucose Models and Simulation} Models of the glucoregulatory system have long been important to the development and testing of an AP \citep{cobelli_integrated_1982}. Current models are based on a combination of rigorous experimentation and expert knowledge of the underlying physiological phenomena. Typical models consist of a multi-compartment model, with various sources and sinks corresponding to physiological phenomena, involving often dozens of patient-specific parameters. One such simulator, the one we use in our experiments, is the UVA/Padova model \citep{kovatchev_silico_2009}. Briefly, this simulator models the glucoregulatory system as a nonlinear multi-compartment system, where glucose is generated through the liver and absorbed through the gut and controlled by externally administered insulin. A more detailed explanation can be found in \cite{kovatchev_silico_2009}. For reproducibility, we use an open-source version of the UVA/Padova simulator that comes with 30 virtual patients, each of which consists of several dozen parameters fully specifying the glucoregulatory system \citep{xie_simglucose_2018}. The patients are divided into three classes: children, adolescents, and adults, each with 10 patients. While the simulator we use includes only 10 patients per class, there is a wide range of patient types among each class, with ages ranging from 7-68 years and recommended daily insulin from 16 units to over 60. At each time step the simulator takes as input the amount of insulin and carbohydrates consumed and produces a 13-dimensional state vector describing levels of glucose and insulin in various compartments of the body. We combine the simulator with a meal schedule which simulates patient behavior, so the control policy only effects the insulin doses. \section{Methods} The use of deep RL for blood glucose control presents several challenges. Through extensive experimentation, we found that the choice of action space, reward function, and training data have significant impact on training and validation performance. Additionally, the high sample complexity of standard RL approaches for continuous control tasks can make the application of these methods in real-world settings infeasible. We address these challenges in turn, settling on a state, action, and reward formulation and learning/validation pipelines that result in policies that achieve strong performance across 30 different simulated patients with the same architecture and hyperparameters, without requiring meal announcements. Finally, we demonstrate how such policies can be transferred across patients in a data-efficient manner. We begin by formalizing the problem. We then describe deep RL approaches that vary in terms of architecture and state representation, and present several baselines: an analogue to human-control in the form of a basal-bolus controller and variants on a PID controller. \subsection{Problem Setup} We frame the problem of blood glucose control as a Partially-Observable Markov decision process (POMDP) consisting of the 6-tuple $(S^*, O, S, A, P, R)$. Our precise formulation of this problem varies depending on the method and setting. Here, we describe the standard formulation, and explain further differences as they arise. The true states $\mathbf{s}^*_t \in S^*$ consist of ground truth levels of insulin, glucose, and carbohydrates in different compartments of the body, as described in \cite{kovatchev_silico_2009}. The observation function $O: \mathbf{s}^*_t \rightarrow b_t$ maps from the true state value to the CGM observation $b_t$. Observed states $\mathbf{s}_t \in S$ consist of the previous 4 hours of CGM $\mathbf{b}^t$ and insulin data $\mathbf{i}^t$ at the resolution of 5-minute intervals: $\mathbf{s}_t = [\mathbf{b}^t, \mathbf{i}^t]$ where: $$ \mathbf{b}^t = [b_{t-47}, b_{t-46}, \dots, b_{t}], \mathbf{i}^t = [i_{t-47}, i_{t-46}, \dots, i_{t}] $$ and $b_{t} \in \mathbb{N}_{40:400}$, $i_{t} \in \mathbb{R}_{\ge 0}$, $t \in \mathbb{N}_{1:288}$ and represents a time index for a day at 5-minute resolution. Note that in our formulation, the observation function \textit{does not} map to observed states, as observed states incorporate significant amounts of historical data. We systematically explored history lengths between 1 and 24 hours as input. After tuning on the validation data, we found that 4 hours struck a good balance between time to convergence and strong performance. We use an update resolution of every 5 minutes to mimic the sampling frequency of many common continuous glucose monitors. Actions $a_t \in \mathbb{R}_{\ge 0}$ are real positive numbers, denoting the size of the insulin bolus in medication units. We experimented with numerous discritized action spaces (as is required by Q-learning approaches), but given the extreme range of insulin values required to achieve good performance (\textit{e.g.} total daily insulin requirements vary between 16 and 60 units), designing an action space where exploration was feasible proved impractical (as an inappropriately timed bolus can be dangerous). The transition function $P$, our simulator, consists of two elements: i) $M: t \rightarrow c_t$ is the meal schedule, and is defined in \textbf{Appendix \ref{app:meal}}, and ii) $G: (a_t, c_t, \mathbf{s}^*_t) \rightarrow (b_{t+1}, i_{t+1}, \mathbf{s}^*_{t+1})$, where $c_t \in \mathbb{R}_{\ge 0}$ is the amount of carbohydrates input at time $t$ and $G$ is a model of the glucoregulatory system, its behavior is defined in accordance with the UVA/Padova simulator \citep{kovatchev_silico_2009}. The reward function $R: (\mathbf{s}_t, a_t) \rightarrow \mathbb{R}$ is defined as negative risk $-risk(b_t)$ where $risk$ is the asymmetric blood glucose risk function defined as: \begin{equation} risk(b) = 10*(3.5506 * \log(b)^{0.8353}-3.7932)^2 \end{equation} shown in \textbf{Figure \ref{fig:risk}}, and is an established tool for computing glucose risk \citep{magni_model_2007}. Considered in isolation, this reward could lead to dangerous behavior. As it is entirely negative, cumulative reward can be maximized by ending the episode as quickly as possible (corresponding to a catastrophic failure). To mitigate this, we add an additional termination penalty to this reward function, where trajectories that enter dangerous blood glucose regimes (blood glucose levels less than 10 or more than 1,000 mg/dL) receive a negative reward that outbalances the advantage of early termination. We found a value $-1e5$ worked empirically. We investigated other reward functions, such as time in range or distance from a target blood glucose value, or risk without a termination penalty, but found that optimizing for the proposed reward function consistently led to better control. In particular, it led to control schemes that were less prone to hypoglycemia, as these trajectories were penalized more heavily than occasional high glucose levels. This decision was important for our problem setting as extreme hypoglycemia can be rapidly triggered by a large dose of insulin without an accompanying meal. Given the lack of meal announcements and sensor noise which can look like the beginnings of a meal spike, avoiding extreme hypoglycemia was one of the major challenges we encountered in applying deep RL to blood glucose control \begin{figure} \centering \includegraphics[width=0.45\linewidth]{figures/magni_risk_post.pdf} \caption{The risk function proposed in \citep{magni_model_2007}. The mapping between blood glucose values (in mg/dL, x-axis) and risk values (y-axis). The hypo- and hyperglycemic thresholds are shown as shaded regions. The risk at the hyperglycemic threshold (180 mg/dL) is roughly 3.5, the risk at the hypoglycemic threshold (70 mg/dL) is approximately 25.} \label{fig:risk} \end{figure} \subsection{Soft Actor Critic} We learn a stochastic policy $\pi: \mathbf{s}_t \rightarrow p(a_t)$, or a policy that given an observed state produces a distribution of possible actions, using the Soft Actor Critic (SAC) algorithm \citep{haarnoja_soft_2018}. In particular, our policy network generates outputs $\mu, \log(\sigma)$ which parameterize a normal distribution $\mathcal{N}(\mu, \sigma)$. The actions are distributed according to $tanh(z), z \sim \mathcal{N}(\mu, \sigma)$. This algorithm has been shown to be a reasonably sample efficient and well-performing algorithm when learning continuous control policies. Additionally, the fact that our problem setting is partially observed suggests potential benefits from a stochastic formulation \citep{eysenbach2019if}. SAC, a member of the Actor-Critic family, trains a stochastic policy network (or actor) parameterized by $\phi$ to maximize the maximum entropy RL objective function: \vspace{-1pt} \begin{equation}\label{eqn:policy_return} J(\pi) = \sum_{t=0}^T \mathbb{E}_{(\mathbf{s}_t, a_t) \sim P(\mathbf{s}_{t-1}, \pi_\phi(\mathbf{s}_{t-1}))} [R(\mathbf{s}_t, a_t) + \alpha H(\pi_\phi(\cdot|\mathbf{s}_t))], \end{equation} \vspace{-1pt} where the entropy regularization term, $H$, is added to the expected cumulative reward to improve exploration and robustness \citep{haarnoja_soft_2018}. Intuitively, the return in \textbf{Equation \ref{eqn:policy_return}} encourages a policy that maximizes expected reward while also maximizing the entropy of the learned policy. The temperature hyperparameter $\alpha$ controls the tradeoff between these two objectives. While it can be set manually, in our work we use the automatic temperature tuning derived by \cite{haarnoja_soft_2018a}. The overall objective function is optimized by minimizing the KL divergence between the action distribution $\pi_\phi(\cdot|\mathbf{s}_t))$ and the distribution induced by state-action values $Q_{\theta}(\mathbf{s}_{t}, \cdot)$: \vspace{-1pt} \begin{equation}\label{eqn:pi} J_{\pi}(\phi)=\mathbb{E}_{\mathbf{s}_{t} \sim \mathcal{D}}\left[\mathrm{D}_{\mathrm{KL}}\left(\pi_{\phi}\left(\cdot | \mathbf{s}_{t}\right) \| \frac{\exp \left(Q_{\theta}\left(\mathbf{s}_{t}, \cdot\right)\right)}{Z_{\theta}\left(\mathbf{s}_{t}\right)}\right)\right] \end{equation} \vspace{-1pt} where $\mathcal{D}$ is a replay buffer containing previously seen $(\mathbf{s}_t, \mathbf{a}_t, r_t, \mathbf{s}_{t+1})$ tuples, $Z_\theta$ is a partition function, and $Q_\theta$ is the state-action value function parameterized by a neural network (also called a critic). This means that our learned policy engages in probability matching, or selecting an action with probability proportional to its expected value. $Q_\theta$ is trained by minimizing the temporal difference loss: \begin{gather}\label{eqn:q} J_{Q}(\theta)=\mathbb{E}_{\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right) \sim \mathcal{D}}\left[\frac{1}{2}\left(Q_{\theta}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)-\hat{Q}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)\right)^{2}\right], \\ \hat{Q}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)=r\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)+\gamma \mathbb{E}_{\mathbf{s}_{t+1} \sim p}\left[V_{\overline{\psi}}\left(\mathbf{s}_{t+1}\right)\right]. \end{gather} \vspace{-1pt} $V_{\overline{\psi}}$ is the running exponential average of the weights of $V_\psi$ (the soft value function parameterized by a third neural network) over training. This is a continuous variant of the hard target network replication in \citep{mnih_human-level_2015}. $V_\psi$ is trained to minimize: \begin{equation}\label{eqn:v} J_{V}(\psi)=\mathbb{E}_{\mathbf{s}_{t} \sim \mathcal{D}}\left[\frac{1}{2}\left(V_{\psi}\left(\mathbf{s}_{t}\right)-\mathbb{E}_{\mathbf{a}_{t} \sim \pi_{\rho}}\left[Q_{\theta}\left(\mathbf{s}_{t}, \mathbf{a}_{t}\right)-\log \pi_{\phi}\left(\mathbf{a}_{t} | \mathbf{s}_{t}\right)\right]\right)^{2}\right]. \end{equation} In summary: we train a policy which maps from states to a probability distribution over actions and parameterized using a neural network $\pi_\phi$. Training this network (\textbf{Equation \ref{eqn:pi}}) requires an estimation of the soft state-action value function, we learn such an estimate $Q_\theta$ (\textbf{Equation \ref{eqn:q}}) together with the soft value function $V_\psi$ (\textbf{Equation \ref{eqn:v}}). Additional details of this approach, including the gradient calculations, are given in \citep{haarnoja_soft_2018}. Note that we replace the MSE temporal difference loss with Huber loss, as we empirically found this improved convergence. \subsubsection{Recurrent Architecture}\label{sec:architecture} Our proposed approach takes as input only the past 4 hours of CGM and insulin data, mimicking real-world applications without human input (\textit{i.e.}, no meal announcements). To extract useful state information from the noisy CGM and insulin history, we parameterize $Q_\theta$, $V_\psi$, and $\pi_\phi$ using gated-recurrent unit (GRU) networks \citep{cho_learning_2014}, as these types of architectures have successfully been used to model to blood glucose data in the past \citep{fox_deep_2018, zhu_deep_nodate}. The GRU in $\pi_\phi$ maps states to scalar values $\mu$ and $\log(\sigma)$. Our GRU networks are composed of two layers and have a hidden state size of 128, followed by a fully-connected output layer. We tuned this architecture using validation data on a limited subset of patients. \subsection{Baselines} We examine three baseline methods for control: basal-bolus (BB), PID control, and PID with meal announcements (PID-MA). BB reflects typical human-in-the-loop control strategies, PID reflects a common control strategy used in preliminary fully closed loop AP applications, PID with meal announcements is based on current AP technology, and requires regular human intervention.Finally, we consider an 'oracle' approach that has access to the true state $s^*_t$. This decouples the task of learning a policy from learning a representation, serving as an upper bound on performance for our proposed approach. \subsubsection{Basal-Bolus Baseline} This baseline is designed to mimic human control and is an ideal depiction of how an individual with T1D currently controls their blood glucose. In this setting, we modify the standard state representation $\mathbf{s}_t$ to include a carbohydrate signal and a cooldown signal (explained below), and to remove all measurements occurring before $t$, $\mathbf{s}_t = [b_t, i_t, c_t, cooldown]$. Note that the inclusion of a carbohydrate signal, or meal announcement, places the burden of providing accurate and timely estimates of meals on the person with diabetes. Each virtual patient in the simulator comes with the parameters necessary to calculate a reasonable basal insulin rate $bas$ (the same value used in our action space definition), correction factor $CF$, and carbohydrate ratio $CR$. These three parameters, together with a glucose target $b_g$ define a clinician-recommended policy $\pi(s_t) = bas + (c_t > 0) * (\frac{c_t}{CR} + cooldown * \frac{b_t - b_g}{CF})$ where $cooldown$ is 1 if there have been no meals in the past three hours, otherwise it is 0. This ensures that each meal is only corrected for once, otherwise meals close in time could lead to over-correction and hypoglycemia. Appropriate settings for these parameters can be estimated by endocrinologists, using previous glucose and insulin information \citep{walsh_guidelines_2011}. The parameters for our virtual patient population are given in \textbf{Appendix \ref{app:bb}}. \subsubsection{PID Baseline} Variants of PID controllers are already used in commercial AP applications \citep{garg_glucose_2017}. A PID controller operates by setting the control variable, here $a_t$, to the weighted combination of three terms $a_t = k_P P(b_t) + k_I I(b_t) + k_D D(b_t)$ such that the process variable $b_t$ (where $t$ is again the time index) remains close to a specified setpoint $b_g$. The terms are calculated as follows: i) the proportional term $P(b_t)=\max(0, b_t - b_g)$ increases the control variable proportionally to the distance from the setpoint, ii) the integral term $I(b_t) = \sum_{j=0}^t (b_j - b_g)$ acts to correct long-term deviations from the setpoint, and iii) the derivative term $D(b_t) = |b_{t} - b_{t-1}|$ acts to control a basic estimate of the future, here approximated by the rate of change. The set point and the weights (also called gains) $k_P, k_D, k_I$ are hyperparameters. To compare against the strongest PID controller possible, we tuned these hyperparameters extensively using multiple iterations of grid-search with exponential refinement per-patient, optimizing to minimize risk. Our final settings are presented in \textbf{Appendix \ref{app:pid_param}}. \subsubsection{PID with Meal Announcements.} This baseline, which is designed to be similar to commercially available hybrid closed loop systems \citep{garg_glucose_2017, ruiz_effect_2012}, combines the BB with the PID algorithm into a control algorithm that we call "PID with meal announcements" (PID-MA). During meals, insulin boluses are calculated and applied as in the BB approach, but instead of using a predetermined fixed basal insulin rate, the PID algorithm controls the basal rate, allowing for adaptation between meals. As above, we tune the gain parameters for the PID algorithm using sequential grid search with exponential refinement to minimize risk. \subsubsection{Oracle Architecture} A deep RL approach to learning AP algorithms requires that: i) the representation learned by the network contain sufficient information to control the system, and ii) an appropriate control algorithm be learned through interaction with the glucoregulatory system. As we are working with a simulator, we can explore the difficulty of task (ii) in isolation, by replacing the state $\mathbf{s}_t$ with the ground-truth state of the simulator $\mathbf{s}^*_t$. Though unavailable in real-world settings, this representation decouples the problem of learning a policy from that of learning a good state representation. Here, $Q_\theta$, $V_\psi$, and $\pi_\phi$ are fully-connected with two hidden layers, each with 256 units. The network uses ReLU nonlinearities and BatchNorm \citep{ioffe2015batch}. \subsection{Experimental Setup \& Evaluation} To measure the utility of deep RL for the task of blood glucose control, we learned policies using the approaches described above, and tested these policies on data with different random seeds across 30 different simulated individuals. \textbf{Training and Model Selection. }We trained our models (from scratch) for 300 epochs (batch size 256, epoch length 20 days) with an experience replay buffer of size 1e6 and a discount factor of 0.99. We examined different choices of discount factor on a subset of patients, and while our selection performed best, the effect was minor. While our RL algorithms often achieved reasonable performance within the first 20-50 epochs of training, we found that additional training was required for stable performance. We also found that a sufficient epoch length was critical for learning a stable controller. Too small of an epoch length can lead to dangerous control policies. We optimized the parameters of $Q$, $V$ and $\pi$ using Adam with a learning rate of $3E-4$. All network hyperparameters, including number and size of layers, were optimized on training seeds on a subset of the simulated patients. Our networks were initialized using PyTorch defaults. When fine-tuning models transferred across patients, we train them for 50 epochs with a learning rate of $10^{-4}$. All of our code will be made publicly available to allow for replication. For the purpose of anonymous peer-review, we have made our code available on an anonymous google drive account \footnote{\url{https://tinyurl.com/y6e2m68b}}. \textbf{Evaluation. }We measured the performance (risk) of the policy networks on 10 days of validation data after each epoch. After training over all epochs, we evaluated on test data using the model parameters from the best epoch as determined by the validation data. Our method of choosing the best validation run led to significant changes in performance (see \textbf{Section \ref{sec:val_selection}}). To optimize our validation selection method, we generated a separate set of tuning seeds for a patient, and chose the selection approach that resulted in best performance on this pseudo-test data. Our validation procedure selects the epoch to test by first filtering out runs that could not control blood glucose within safe levels over the validation run (glucose between 30-1000 mg/dL), then it selects the remaining epoch that achieved the lowest mean risk. We evaluated each patient-specific model on 1000 days of test data, broken into 100 independent 10 day rollouts. We trained and evaluated each approach 3 times, resulting in 3000 days of evaluation per method per person. We evaluated approaches using i) risk, the average magni risk calculated over the 10-day rollout, ii) \% time spent euglycemic (blood glucose levels between 70-180 mg/dL), iii) \% time hypo/hyperglycemic (blood glucose lower than 70 mg/dL or higher than 180 mg/dL respectively), and iv) \% of runs that resulted in a catastrophic failure, which we denote as a run that achieves a minimal blood glucose level below 5 mg/dL (at which point recovery becomes highly unlikely). Note that while these catastrophic failures are a major concern, our simulation process does not consider consuming carbs to correct for low blood glucose levels. This is a common strategy to avoid dangerous hypoglycemia in the real world. The random seeds controlling noise, meals in the environment, and all other forms of stochasticity were different between training, validation, and test runs. We test the statistical significance of differences between methods using Mood's median test for all metrics except for catastrophic failure rate, for which we use a binomial test. \textbf{Patient-Specific Action Space.} After the network output layer, actions are squashed using a \textit{tanh} function. Note that this results in half the action space corresponding to negative values, which we interpret as administering no insulin. This encourages sparse insulin utilization, and makes it easier for the network to learn to safely control baseline glucose levels. To ensure that the maximum amount of insulin delivered over a 5-minute interval is roughly equal to a normal meal bolus, we use the average ratio of basal to bolus insulin in a day \citep{kuroda_basal_2011} to calculate a scale parameter for the action space. We use $\omega_{b}=43.2*bas$ as the scale, where $bas$ is the default basal insulin rate provided by \cite{xie_simglucose_2018} (which varies per-person). This scaling was an important addition to improving performance with a continuous action space. \textbf{Efficient Policy Transfer.} Given that one of the main disadvantages of deep RL approaches is their sample efficiency, we sought to explore transfer learning techniques that could allow networks trained from scratch to be efficiently transferred to new patients. We refer to our method trained from scratch as RL-Scratch, and the transfer approach as RL-Trans. For RL-Trans, we initialize $Q_\theta, V_\psi, \pi_\phi$ for each class of patients (children, adolescents, and adults) using fully trained networks from one randomly selected member of that source population (\textit{e.g.}, Child/Adolescent/Adult 1). We then fine-tune these networks on data collected from the target patient. When fine-tuning, we modify the reward function, removing the termination penalty and adding a large positive constant value (100) to all rewards. Removing the termination penalty led to more consistent returns over training, as it reduces the range of possible episode returns allowing for a more consistent policy gradient. As we begin with policies that are approximately correct, the additional safety provided by training with a termination penalty is no longer required. This provides a simple approach for training policies using far less data per-patient. \section{Experiments and Results} We investigate the performance of several different classes of policies for blood glucose management with and without meal announcements. We compare the performance of the BB controller, the PID with and without meal announcements, and our RL approaches. We consider 3 variants of RL methods: i) RL-Scratch, the standard SAC trained from scratch on every individual, ii) RL-Trans, which fine-tunes a trained RL-Scratch model from an arbitrary child/adolescent/adult, and iii) RL-MA, which uses RL-Scratch trained using the same automated meal boluses used for PID-MA. We also report results on an Oracle approach, which is a SAC method trained and evaluated using the ground truth simulator state. To begin, we demonstrate the potential of deep RL for learning AP algorithms relative to other approaches. Then, we address the challenges we faced in applying deep RL to this task and present how we overcame them. \begin{figure*}[htb!] \centering \includegraphics[width=\linewidth]{figures/noma_risk.png} \caption{The risk over 10 days achieved by the methods that do not require meal announcements when applied to different simulated patients. Each point corresponds to a different random test seed that controls the meal schedule and sensor noise. The line indicates median performance across all test seeds for each method on each patient. Results for each method are presented across 3 random training seeds, controlling model initialization and randomness in training. We observe that, although there is a wide range in performance across and within individuals, The RL approaches tend to outperform the PID.} \label{fig:full_risk_noma} \end{figure*} \begin{figure*}[htb!] \centering \includegraphics[width=\linewidth]{figures/ma_risk.png} \caption{The risk over 10 days achieved by the methods that require meal announcements. We observe that PID-MA tends to outperform BB, and RL-MA similarly outperforms PID-MA.} \label{fig:full_risk_ma} \end{figure*} \begin{table*}[t!] \centering \caption{Median risk, percent of time Eu/Hypo/Hyperglycemic, and failure rate calculated using 1000 days of simulation broken into 100 independent 10-day rollouts for each of 3 training seeds for 30 patients, totaling 90k days of evaluation (with interquartile range). Lower Magni Risk, Hypoglycemia, and Hyperglycemia are better, higher Euglycemia is better. Hybrid and Non-closed loop approaches (requiring meal announcements) are indicated with *. Approaches requiring a fully observed simulator state are indicated with $\dagger$. The non-oracle approach with the best average score is bolded and underlined, the best approach that does not require meal announcements is bolded.} \scalebox{0.9}{ \begin{tabular}{lcccccc} \toprule & & Risk & Euglycemia & Hypoglycemia & Hyperglycemia & Failure \\ & & \downarrow & (\%) \uparrow & (\%) \downarrow & (\%) \downarrow & (\%) \downarrow \\ \midrule \multirow{3}{}{\rotatebox[origin=c]{90}{No MA}} & PID & 8.86 (6.8-14.3) & 71.68 (65.9-75.9) & 1.98 (0.3-5.5) & \textbf{24.71 (21.1-28.6)} & 0.12 \\ & RL-Scratch & \textbf{6.50 (4.8-9.3)} & \textbf{72.68 (67.7-76.2)} & \textbf{0.73 (0.0-1.8)} & 26.17 (23.1-30.6) & \textbf{0.07} \\ & RL-Trans & 6.83 (5.1-9.7) & 71.91 (66.6-76.2) & 1.04 (0.0-2.5) & 26.60 (22.7-31.0) & 0.22 \\ \hline \multirow{4}{}{\rotatebox[origin=c]{90}{MA}} & BB* & 8.34 (5.3-12.5) & 71.09 (62.2-77.9) & 2.60 (0.0-7.2) & 23.85 (17.0-32.2) & 0.26 \\ & PID-MA* & 8.31 (4.7-10.4) & 76.54 (70.5-82.0) & 3.23 (0.0-8.8) & \bf{\underline{18.74 (12.9-23.2)}} & \bf{\underline{0.00}} \\ & RL-MA* & \bf{\underline{4.24 (3.0-6.5)}} & \bf{\underline{77.12 (71.8-83.0)}} & \bf{\underline{0.00 (0.0-0.9)}} & 22.36 (16.6-27.7) & \bf{\underline{0.00}} \\ & RL-Oracle^\dagger & 3.58 (1.9-5.4) & 78.78 (73.9-84.9) & 0.00 (0.0-0.0) & 21.22 (15.1-26.1) & 0.01 \\ \bottomrule \end{tabular} } \label{tab:risk} \end{table*} \subsection{Advantages of Deep RL}\label{sec:advantages} We begin by comparing our deep RL approaches to baselines with and without meal announcements. We then investigate two hypotheses for why deep RL is well suited to the problem of glucose management without meal announcements: i) that the high capacity neural network is able to quickly infer when meals occur, and ii) the approach is able to adapt to behavioral patterns. \subsubsection{Deep RL vs. Baseline Approaches} Results comparing the PID baseline to the RL approaches are presented in \textbf{Figure \ref{fig:full_risk_noma}}. Each point represents a different test rollout by a policy. For the RL approaches, the performance of each method is reported as the combination of 3 random restarts. For each individual we rank the 3 approaches in terms of median risk. We calculate average rank by taking the mean of each approaches rankings across all 30 patients. Among the 3 methods that do not require meal announcements, RL-Scratch performs best across patients (average rank 1.33), followed by RL-Trans (average rank 1.7), then PID (average rank 2.97). \textbf{Figure \ref{fig:full_risk_ma}} shows the performance for approaches requiring meal announcements. The mean risk for almost all individuals is above the risk threshold for hyperglycemia of 3.5. This is far from the optimal level of control. However, it is not the case that all time is spent hypo/hyperglycemic. Across patients, approximately 60-80\% of time is spent euglycemic, compared with $52\% \pm 19.6$\% observed in real human control \citep{ayanotakahara_carbohydrate_2015}. Note that RL-Scratch, while achieving strong performance overall, reliably performs quite poorly on adolescent\#002. We discuss this issue in \textbf{Appendix \ref{app:ao2}}. One of the major advantages of our proposed approach is its ability to achieve strong performance without meal announcements. This does not mean that our approach does not benefit from meal announcements. Among the 3 methods that require meal announcements, RL-MA performs best (average rank 1.07), followed by PID-MA (average rank 2.13) then BB (average rank 2.8). These results suggest that deep RL could be a valuable addition to current hybrid closed loop systems. We examine additional models and metrics in the results presented in \textbf{Table \ref{tab:risk}}. We observe that RL-MA equals or surpasses the performance of all non-oracle methods with the exception of hyperglycemia. Interestingly, all the RL variants achieve lower median risk than PID-MA, which requires meal announcements. This is primarily driven by low levels of hypoglycemia, which the risk metric heavily penalizes (see \textbf{Figure \ref{fig:risk}}). Note that all methods, including PID-MA, were optimized to minimize this metric. The difference between results that are bolded, or bolded and underlined, and the next best non-bolded result (excluding RL-Oracle) are statistically significant with $p<0.001$. \subsubsection{Detecting Latent Meals} Our RL approaches achieves overall strong blood glucose control without meal announcements, but how much of this is the deep networks ability to detect meals? To investigate this, we looked at the total proportion of insulin delivered on average after meals for PID and RL-Scratch, shown in \textbf{Figure \ref{fig:rl_advantage}a}. If our RL approach was better able to infer meals, we would expect sharper increase in insulin administered after meals, as the sooner insulin is administered the faster glycemic spikes can be controlled without risking hypoglycemia. This is precisely what we observe, RL-Scratch administers the majority of its post-meal bolus within one hour of a meal, whereas PID requires two hours. Interestingly, when considering the percentage of total daily insulin administered in the hour after meals, RL-Scratch responds even more aggressively than BB or PID-MA (54.7\% \textit{vs.} 48.5\% and 47.3\% respectively). This demonstrates that our RL approach is able to readily react to latent meals shortly after they have occurred. \subsubsection{Ability to Adapt to Behavioral Schedules} We hypothesize that one of the potential advantages of RL is its ability to exploit underlying behavioral patterns, improving control as the environment becomes more predictable. To investigate this potential benefit, we explored changing the meal schedule generation procedure outlined in \textbf{Algorithm \ref{alg:schedule}} for Adult 1. We removed the `snack' meals (those with occurrence probabilities of 0.3) and set all meal occurrence probabilities to 1 and meal amount standard deviations to 0 (\textit{i.e.}, each day Adult 1 consumes an identical set of meals). We then evaluated both the PID model and the RL-Scratch model on 3 variations of this environment, characterized by the standard deviation of the meal times (either 0.1, 1, or 10 hours). This tests the ability of each method to take advantage of patterns in the environment. The results are presented in \textbf{Figure \ref{fig:rl_advantage}b}. We observe that, while RL-Scratch achieves lower risk than PID under all settings, the difference becomes more pronounced as the standard deviation of meal times becomes smaller (and thus meal timing becomes more predictable). Specifically, mean risk decreases by roughly 12\% for the PID approach (form 9.65 to 8.54), whereas it decreases nearly 24\% for the RL approach (from 8.40 to 6.42). This supports our hypothesis that RL is better able to take advantage of behavioral patterns. \vspace{-3pt} \begin{figure} \centering \begin{subfigure}{} \includegraphics[width=.4\linewidth]{figures/percent_tdi.pdf} \end{subfigure} \begin{subfigure}{} \includegraphics[width=.4\linewidth]{figures/time_std_euglycemic.pdf} \end{subfigure} \caption{a) The average amount of insulin (in percent of total daily insulin) provided after meals for PID and RL-Scratch (note: RL-Trans, unshown, is very similar to RL-Scratch). We see RL-Scratch is able to more quickly respond to meals, with insulin peaking 30 minutes post-meal opposed to roughly 60 minutes for PID. Additionally, the RL approach finishes delivering most post-meal insulin after 1 hour, PID takes approximately 90 minutes. b) The distribution of average risk scores over 300 10-day rollouts for Adult 1 using different meal schedules. As meal times become more predictable (lower standard deviation). While PID performs better with more regularly spaced meals (median risk lowers from 9.66 at std=10 to 8.53 at std=0.1, a 12\% decrease), RL-Scratch sees a larger proportional and absolute improvement (median risk lowers from 8.33 at std=10 to 6.36 at std=0.1, a 24\% decrease).}\label{fig:rl_advantage} \end{figure} \subsection{Challenges for Deep RL} While \textbf{Section \ref{sec:advantages}} demonstrates several advantages from using deep RL for blood glucose control, the application of deep RL to this task and its evaluation is non-trivial. In this section, we begin by discussing the key design decisions made to achieve the successes described above. We pay particular attention to the issue of catastrophic failures, as overcoming these were a major hurdle for the deep RL approaches. We conclude by addressing the issue of sample complexity with patient-specific data. \subsubsection{Developing an Effective Action Space} One challenging element of blood glucose control in an RL setting is the action space. Insulin requirements vary significantly by person (from 16 to 60 daily units in the simulator population we use), and throughout most of the day, insulin requirements are much lower than near meals. To account for these challenges, we used a patient-specific action-space where much of the space corresponds to delivering no insulin as discussed in \textbf{Section \ref{sec:architecture}}. We perform an ablation study to test the impact of these decisions. On an arbitrarily chosen patient (child\#001), we experimented with removing the negative insulin space by adding 1 to the tanh output. We found this increased the catastrophic failure rate from 0\% (on this one patient) to 6.6\%. On a challenging subset of 4 patients (indicated in \textbf{Appendix \ref{app:bb}}), we looked at the effect of removing the patient-specific action scaling $\omega_b$. We found this increased median risk from 9.92 to 11.23, a 13\% increase. These results demonstrate that an action space that encourages safe behavior and that naturally accommodates variation across patients can improve performance. \subsubsection{Potential Pitfalls in Evaluation} \label{sec:val_selection} In our experiments, we observed two key points for model evaluation: i) while often overlooked in RL, using validation data for model selection during training was key to achieving good performance, and ii) without evaluating on far more data than is typical, it was easy to underestimate the catastrophic failure rate. \textbf{Performance instability necessitates careful model selection. } Off-policy RL with function approximation is known to be unstable, and these effects can be multiplied when using deep neural networks \citep{sutton_reinforcement_2018}. As a result, we found it was extremely important to be careful in selecting which network to evaluate. In \textbf{Figure \ref{fig:validation_selection}a}, we show the fluctuation in validation performance over training for Adult\#009. While performance increases on average over the course of training, there are several points where performance degrades considerably. \textbf{Figure \ref{fig:validation_selection}b} shows how average performance over all patients changes depending on the approach we use to select the training epoch and corresponding policy. When we simply test on the final epoch, almost half of test rollouts end in a catastrophic failure. Surprisingly, even when we select the model that performed best on the validation set in terms of average reward, nearly a fifth of rollouts can fail. However, by first limiting our model selection to those that achieve a minimum blood glucose level of at least 30 mg/dL over the validation data, we reduce the catastrophic failure rate to only $0.07\%$. As others have noted this instability over a range of domains \citep{islam_reproducibility_2017, henderson_deep_2018}, we believe this observation is relevant to future applications of deep RL to healthcare problems. \begin{figure}[hbtp] \centering \begin{subfigure} \centering \includegraphics[width=0.45\linewidth]{figures/unstable_training.pdf} \label{fig:validation_curve} \end{subfigure} \begin{subfigure}{} \includegraphics[width=0.4\linewidth]{figures/validation_selection.pdf} \label{fig:validation_perf} \end{subfigure} \caption{a) The training and validation curve for adult\#009 in terms of average reward. Note the periods of instability affect both training and validation performance. b) Catastrophic failure rate averaged over all patients for 3 methods of validation selection: i) selecting the final training epoch, ii) selecting the epoch that achieved maximal average reward over the validation rollout, iii) selecting the maximal reward epoch that also maintained blood glucose above a certain limit (30 mg/dL).}\label{fig:validation_selection} \end{figure} \textbf{Extensive evaluation is necessary.} While health applications vary widely, by and large they are safety critical. While we have shown that deep learning can improve performance significantly in the average case, the susceptibility of such approaches to unexpected or unsafe behavior poses a significant risk. While ongoing work seeks to provide safety guarantees in control applications using deep learning \citep{achiam_constrained_2017, futoma_identifying_2020}, it is important that practitioners take every step to thoroughly evaluate the safety of their proposed approaches. In our own work, we saw how easy it can be to incorrectly assume an approach is safe, even with significant testing. We examined the number of catastrophic failures that occurred using our RL-Trans method when evaluating with different criteria. Over our full evaluation set of 9000 10-day rollouts, we observed 20 catastrophic failures (a rate of 0.22\%). However, when we only evaluated using the first 5 test seeds, we observed 0 catastrophic failures. Additionally, when we evaluated using 3-day test rollouts instead of 10, we only observed 5 catastrophic failures (a rate of .05\%) across the full test set, suggesting that longer rollouts result in a higher catastrophic failure rate. Without evaluating on a large pool of possible scenarios, it is difficult to judge possible performance. \subsubsection{Reducing Catastrophic Failures} We found varying the training data had a major impact on the catastrophic failure rate. During training, every time we reset the environment we incremented the random seed (which controls meal schedule and sensor noise) by one. Note that the pool of training, validation, and test seeds were set so there was no chance of overlap resulting from these seed increments. On a challenging subset of 7 patients (described in \textbf{Appendix \ref{app:patient}}), we ran RL-Scratch with and without this seed increment strategy. The run with the seed increment had a catastrophic failure rate of $0.15\%$, the method without the seed increment had a $2.05\%$ rate (largely driven by adult\#009, who was reliably the person with the highest catastrophic failure rate across experiments). Other approaches can further improve stability. In \textbf{Table \ref{tab:risk}}, our RL results are averaged over three random restarts. This was done to demonstrate that our learning framework is fairly robust to randomness in training data and model initialization. However, in a real application it would make more sense to select one model for use out of the random restarts using validation data. We apply this approach in \textbf{Table \ref{tab:ss_risk}}. It results in an improvement for all RL methods. Most notably, it drastically reduces the rate of catastrophic failures for the approaches without meal announcements (0.07\% to 0\% for RL-Scratch, and 0.22\% to 0.13\% for RL-Trans). \begin{table*}[t!] \centering \caption{Risk and percent of time Eu/Hypo/Hyperglycemic calculated for the RL approaches treating the 3 training seeds as different random restarts. We see a notable improvement in the stability of the Scratch and Trans approaches.} \scalebox{0.9}{ \begin{tabular}{lccccc} \toprule & Risk & Euglycemia & Hypoglycemia & Hyperglycemia & Failure Rate \\ & \downarrow & (\%) \uparrow & (\%) \downarrow & (\%) \downarrow & (\%) \downarrow \\ \midrule RL-Scratch & 6.39 (4.7-8.9) & 72.96 (69.1-76.6) & 0.62 (0.0-1.7) & 25.96 (22.7-29.6) & 0.00 \\ RL-Trans & 6.57 (5.0-9.3) & 71.56 (67.0-75.7) & 0.80 (0.0-1.9) & 27.19 (23.4-31.2) & 0.13 \\ RL-MA & 3.71 (2.7-6.3) & 77.36 (72.7-83.2) & 0.00 (0.0-0.5) & 22.45 (16.7-26.9) & 0.00 \\ \bottomrule \end{tabular} } \label{tab:ss_risk} \end{table*} \subsubsection{Sample Efficiency and Policy Transfer} While RL-Scratch achieves strong performance on average, it requires a large amount of patient specific data: 16.5 years per patient. While RL-Trans reduced this amount, it still required over 2 years of patient specific data, which for most health applications would be infeasible. Thus, we investigated how performance degrades as less data is used. In \textbf{Figure \ref{fig:finetune}}, we show the average policy performance by epoch of target training for both RL-Scratch and RL-Trans relative to the PID controller to see how low patient-specific data requirements can go. Note the epoch determines the maximum possible epoch for our validation selection, not the actual chosen epoch. We see that far less training is required to achieve good performance with RL-Trans. In over 40\% of rollouts, RL-Trans outperforms PID with no patient-specific data (median risk 10.31), and with 10 epochs of training (roughly half a year of data) RL-Trans outperforms PID in the majority of rollouts (59.6\%; median risk 7.95). Interestingly, the lack of patient-specific data does not appear to cause excessive catastrophic failures. With no patient-specific data the failure rate is 0\%, after 5 epochs of training it has risen to .5\%, and then declines over training to the final value of .22\%. This means two things: i) patient-specific training can increase the catastrophic failure rate, possibly by learning overly aggressive treatment policies, and ii) our current validation selection procedure does not select the epoch that minimizes catastrophic failure rates. Note we do not observe this for RL-Scratch, where all epochs under 50 achieve a catastrophic error rate of over 17\%. These results suggest that our simple transfer approach can be reasonably effective even with limited amounts of patient-specific data. \begin{figure} \centering \includegraphics[width=.5\linewidth]{figures/finetuning_per_epoch.pdf} \caption{The proportion of times RL-Scratch and RL-Trans outperform the average risk of PID over training. We see that without any patient-specific data RL-Trans performs better than PID in 40\% of cases. RL-Scratch requires a significant amount of patient-specific data before achieving comparable performance.}\label{fig:finetune} \end{figure} \section{Conclusion} In this work, we demonstrated how deep RL can significantly improve over alternative approaches to blood glucose control, both with and without meal announcements. While our results applying deep RL to blood glucose control are encouraging, they come with several limitations. First, our results are based on simulation. While the simulator in question is a highly credible one, it may not adequately capture variation across patients or changes in the glucoregulatory system over time. However, as an FDA-approved substitute for animal trials \citep{kovatchev_silico_2009}, success in this simulator is a nontrivial accomplishment. Second, we define a reward function based on risk. Though optimizing this risk function should lead to tight glucose control, it could lead to excess insulin utilization (as its use is unpenalized). Future work could consider resource-aware variants of this reward. Finally, we emphasize that blood glucose control is a safety-critical application. An incorrect dose of insulin could lead to life-threatening situations. Many of the methods we examined, even those which achieve good average performance, are susceptible to catastrophic failures. We have investigated several ways to minimize such failures, including modifying the reward function and selecting models across multiple random restarts. While the results from \textbf{Table \ref{tab:ss_risk}} suggest these approaches are successful, the results of \textbf{Section \ref{sec:val_selection}} show such empirical evaluations can miss failure cases. Despite these limitations, our results clearly demonstrate that deep RL is a promising approach for learning hybrid and fully closed-loop for blood glucose control.
{'timestamp': '2020-09-22T02:02:36', 'yymm': '2009', 'arxiv_id': '2009.09051', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09051'}
arxiv
\section{Introduction} Game developers, publishers, and platforms are all interested to know why certain players play certain games and whether a game would be successful in the market place. Many game marketplaces also have the practical problem of recommending new games to players from a large catalog of possible games. Businesses are interested in these methods, because good recommendations can increase sales and user engagement. The academic field of recommender systems has investigated methods that can be trained on data sets of historical game and user interactions to predict new interactions. Recommender systems therefore seem like a natural solution to the game recommendation problem: gaming facilitates large data sets of past interactions and often additional information is available about game content and user profiles. Recommender systems have been investigated in different contexts, but the most popular algorithms can be divided into collaborative filtering (CF) and content based (CB) \cite{ref1}. Collaborative filtering is based on a data set of past player and game interactions, and it does not use player or game features because the predictions are made possible by observed correlations. For example, if players often play two games together, the games are probably similar and we can recommend one game when a player has played the other. In content based predictions, available information about games and/or players is used in enabling the predictions. In a game database, games typically have tags, genres, reviews, textual information, gameplay videos, etc. that can be used to create features. Creating player features is very flexible, because one can directly ask the players to answer questions about their preferences, motivations, and gaming habits. Predictions are then based on learning how game features or player features, or both together, result in the observed game likes. So called hybrid recommenders combine the content information (i.e. game features and player features) with collaborative filtering. Academic research is often motivated by improving the accuracy of the methods, since this is an objective and easily evaluated task. However, the recommender system literature has started to recognize that accuracy may not always correlate with perceived utility \cite{ref2}. Collaborative filtering has been found to produce more accurate predictions, unless the methods are tasked to predict for players or games with few or no interactions \cite{ref3}. The setting with no interactions is known as the cold start problem, because collaborative filtering cannot predict in this setting. Research on game recommendation has evaluated methods by their predicted ability in historical player and game interactions, but in reality the problem of predicting for new games and new players is common. We therefore define four evaluation settings \cite{ref4}\cite{ref5}: predicting for past games and past players that have interactions (Setting 1), predicting for new games without players (Setting 2), predicting for new players without games (Setting 3), and predicting for new games and new players simultaneously (Setting 4). In this study, we apply new methods to game recommendation that generalize better than collaborative filtering to the different settings. The resulting methods are simple, fast and easily interpretable. We therefore also interpret the model parameters, and find that they provide useful game market information about player traits such as gaming motivations and gameplay preferences. The development of the methods can be motivated by the standard approach to collaborative filtering, the Singular Value Decomposition (SVD), where one or both of the latent vectors is given. The task is then to learn the response of players or games, or their interactions, to the given features. The number of possible game and player pairs makes learning the interactions infeasible with the standard approach, so we utilize a mathematical result known as the vec-trick \cite{ref6} to train an identical model very fast. \section{Related Work} Our recommendation models produce a list of game recommendations to a player. This is known as Top-N recommendation, where the methods are evaluated on the accuracy of the predicted list of recommendations, in contrast to how well the methods would predict missing rating or playtime values for example. The objective of predicting an accurate list of game recommendations is probably the most relevant real world task of these systems, since this task has been adopted by many commercial companies. Top-N recommendation differs from the traditional task of predicting missing values. The evaluation is based on ranking accuracy metrics such as precision or recall, not on error metrics like the root mean squared error (RMSE). There is no guarantee that algorithms optimized for the RMSE are also optimal for ranking because the task is different. Furthermore, item popularity has been found to have a large effect on the error metrics \cite{ref8}. The k Nearest Neighbour (kNN) and the Singular Value Decomposition (SVD) based matrix factorization have become standard methods in predicting missing values, but they also work for the top-N recommendation task \cite{ref3}. In the task of producing game recommendations, one should also take into account whether information about the player-game interactions is implicit or explicit. Implicit signals about liking a game are for example owned or played games, whereas explicit data is the ratings and opinions provided about the games. Implicit data is often complete, which means that every player and game pair has a value and the task is to rank the games by the probability of liking them. In explicit data, there are typically many missing values because a player has not rated every possible game, and the task is to predict the values of the missing ratings. For our models we technically use explicit data, because the player and game interactions are based on the favourite games mentioned in a survey. Similar data sets to our explicit survey based data on favorite games and player preferences could be obtained without using surveys, i.e. implicitly by crawling gaming platforms for the games that users own or play. In either case, these data sets are understood as complete data for our task. This means that there are no missing values because all player and game pairs have a value that denotes whether the player mentioned, owned or played the game. In this study, also we utilize player traits and preferences to construct player features. In game research, player preferences can be divided into four main categories: 1) player motivations \cite{x1, x2}, 2) preferred play styles \cite{x3, x4}, 3) gaming mentalities \cite{x5, x6}, and 4) gameplay type preferences \cite{x7, x8}. Player motivations measure general reasons why players play games, whereas models that investigate play styles are typically based on player behavior data rather than survey data. Gaming mentalities refer to the psychometric data on players' typical and preferred gaming intensity type (e.g. casual or hardcore gaming). \cite{x9} Of the four approaches on player preferences, gameplay type preference data is arguably the most promising for producing personalized game recommendations, because it is closely related to game features. Furthermore, it has been been shown that gameplay type preferences such as preference in exploration, management or aggression predicts habit to play games of specific genres \cite{x7}. Because of these reasons, we make use of gameplay type preference survey data in this study. Comparing recommender systems is difficult for several reasons. The performance may depend on the data set, the prediction task, and the chosen metric \cite{ref2}. In addition, many methods are sensitive to the choice of hyperparameters and the optimization method, which means that authors of new methods may have not always used the best baselines \cite{ref10}. There can also be performance differences between different software implementations of otherwise identical methods \cite{ref11}. However, the simple baseline methods tend to produce competitive results when the hyperparameters are carefully tuned \cite{ref10}. High accuracy if often assumed to correlate with an useful recommender system, but subjective utility recommender system has also become an important research goal in itself \cite{ref2}. Optimizing accuracy can lead to recommending popular items at the cost of personalized results \cite{ref8}. There are studies that have investigated the development of new recommender systems to games. The first study \cite{ref12} used probabilistic matrix factorization based collaborative filtering for the Xbox platform. The second study \cite{ref13} presented a recommender based on archetypes, where their formula (5) is a constrained case of the SVD. The study included comparisons to kNN (cosine) trained on the latent SVD factors, the standard kNN with somewhat small neighbourhood sizes, and random or most popular recommendations. The third study \cite{ref14} investigated a new case-based disability rehabilitation recommender, which is a type of content recommender. The content was based on game descriptions combined with social network information and questionnaire answers of the users. The fourth study \cite{ref15} presented a graph based approach with a biased random walk model inspired by ItemRank, which is a type of a hybrid recommender. The fifth study \cite{ref16} is a kNN (cosine) recommender based on content created by the latent semantic analysis of wikipedia article. The sixth study \cite{ref17} defined a content based recommender to find similar games through the cosine similarity of feature vectors based on Gamespot game reviews. The bag-of words representation was outperformed by information theoretic co-clustering of adjective-context word pairs to reduce the dimensionality. The seventh study evaluated the quantitative and qualitative performance of game recommenders on the Steam data set \cite{ref18}. They used BPR++, grouped BPR, kNN (cosine) on game tag content, kNN combined with grouped BPR, a simulation of Steam's recommender, SVD, Factorization Machine (FM), and popularity ranking. They found significant quantitative differences but no qualitative differences between the methods. \section{Data Set} \subsection{Survey data set} The survey data (N=15,894) was collected by using a total of 10 standalone web-based surveys. Each of the surveys focused on different aspects of player preferences but all surveys included open-ended questions about respondents favorite games. Most of the samples were collected by using a UK-based crowd sourcing platform, market companies providing large online panels, or by recruiting respondents from social media platforms such as Facebook or Reddit. The survey data includes representative samples from Finland, Denmark, USA, Canada, and Japan. A typical survey took up to 20 minutes to complete with a computer or a mobile phone, and was targeted to everyone between the ages of 18 and 60. Another type of survey data was collected by using a short online player type test. The short test was open to everyone regardless of their prior experience in playing games, or the possible lack of it. Before analyzing survey data of the individual survey data sets, the data was cleaned of participants who implied content non-responsivity by responding similarly to every question. The survey data analyzed in this study consists of 15894 observations, 6465 unique games, and 80916 favorite game mentions. There are 1 to 37 favorite game mentions per player, and on average a player mentioned 5 games as his or her favorites. Every game that is mentioned as a favorite game has from 1 to 1108 individual favorite game mentions i.e. players. The data set is very sparse, since only 0.08\% of possible (player, game)-pairs are favorite game mentions. The answers tended to be more novel and personal than data sets based on played or owned games. Content for the games was obtained by crawling game tags from publicly available sources, such as the Steam platform and the Internet Games DataBase (IGDB), the latter of which provided an API for this purpose. The presence or absence of every tag in each game was stored as a binary indicator. Content for the players was obtained by asking the survey participants' preferences using the Gameplay Activity Inventory (GAIN) which has been validated with cross-cultural data. The GAIN consists of 52 questions (5-Likert scale, 1=very unpleasant, 5=very pleasant) about gameplay preferences, and the inventory measures five dimensions of gameplay appreciation: aggression, management, caretaking, exploration, and coordination. These questions consists of items such as 'Exploding and Destroying' (factor: aggression), 'Searching for and collecting rare treasures' (factor: exploration), 'Flirting, seducing and romantic dating' (factor: caretaking), 'Matching tiles together' (factor: coordination), 'Generating resources such as energy or money' (factor: management) etc. (Vahlo et al. 2018). In addition to the GAIN model, we utilized also a 9-item inventory on players' game challenge preferences. These items measure how pleasurable players consider e.g. 'logical problem-solving', 'strategic thinking', 'puzzle solving', 'racing against time', etc. A typical survey included the full 52 plus 9 questions whereas the online player type test consisted of a partly randomized sample of these questions. \section{Models} \subsection{Data set and validation} Assume we have $n$ players and $m$ games. Denote player $i\in\{1,2,...,n\}$ and game $j\in\{1,2,...,m\}$. The player and game interactions are stored in a $n \times m$ binary game like matrix $R_{i,j}=\mathbb{I}(\text{player }i\text{ likes game }j)$. The matrix does not have missing entries, because the game like status is known for every player. For example, the player $i$ may have answered the first and the third game as their favourites: \begin{equation} \begin{array}{c} R_{i,:} = (1, 0, 1, 0, ..., 0) \end{array} \end{equation} The task is to predict the ranking of games that the player has not answered as their favourite but might like. These predictions are the matrix $R_{i,j}^{*}\in\mathbb{R}$, where only the order of the values in each row matters for ranking. For example, the predictions for player $i$ over all the $m$ games could be: \begin{equation} \begin{array}{c} R_{i,:}^{*} = (1.41, 0.10, 0.82, 0.04, ..., 0.21) \end{array} \end{equation} The recommendation list for a player is obtained by taking the indices of games with $k$ largest predicted values in $R_{i,:}^{*}$, where the games that the player has already liked are excluded. In addition to game likes, we also have player and game features that we can use for content based prediction. Denote the $m \times r$ matrix of game features as $X_{\text{tags}}$, where the feature vectors for the $m$ games are stored as rows. In our case these features are indicators of presence or absence of each of the $r$ game tags. Denote the $n \times s$ matrix of player features as $X_{\text{questions}}$, where the feature vectors for the $n$ players are stored as rows. In our case these features are the responses to the $s$ questions on a Likert scale of -2,-1,0,1,2. To test model performance, we split the data set into training and validation sets as follows. First, we randomly sampled 25\% of games into 'test games' an 25\% of players into 'test players' that the models do not see during training. These games and players test the performance of the model for new games and players. The other games and players belong to the training set. In Setting 1, the models are tested on the task of recommending known games for a known player who has mentioned 3 favourite games. We therefore further selected 20 \% of the training set players by randomly sampling amongst those who have liked more than 3 games. Randomly chosen 3 games of each player are the 'seed' which belongs to the training set, and the remaining games for these players belong to the validation set for Setting 1. The Setting 2 (new games) validation set consists of the unseen 'test games' for the known players. In Setting 3 (new players), the validations set consists of unseen 'test players' for the known games. In setting 4, the validation set is the game likes for the unseen 'test games' and 'test players'. We have illustrated the game like matrix $R$, the game features $X_{\text{tags}}$, the player features $X_{\text{questions}}$, and the different validation settings in Figure~\ref{figure:data}. \begin{figure}[htbp] \centerline{\includegraphics[width=\columnwidth]{illustration_validation.eps}} \caption{Illustration of the data set and validation settings.} \label{figure:data} \end{figure} \subsection{Metrics} We use Precision@20 and nDCG@m to measure accuracy in the validation sets. They are defined as follows. \subsubsection{Precision@20} The Precision@k metric counts the number of games the player has liked in the validation set, as a fraction of all games in a recommendation list of length $k$. Assume the model predicts $R_{i,:}^{*}$ for player $i$, and denote $r^{(i)}$ as the vector of indices that sorts the predictions. The element $r^{(i)}_{j}$ is the $j$'th game in the recommendation list, i.e. the index of $j$'th largest predicted value in $R_{i,:}^{*}$. The metric for the data set is the average precision over the players: \begin{equation} \begin{array}{c} \frac{1}{n}\sum_{i=1}^{n}\frac{1}{k}\sum_{j=1}^{k} \mathbb{I}(\text{player } i \text{ likes game } r^{(i)}_{j}) \end{array} \end{equation} Precision is a realistic measure of the real-world accuracy of a recommendation list, where $k$ is typically small and the position of a game in the list does not matter. \subsubsection{nDCG@k} The normalized Discounted Cumulative Gain (nDCG@k) metric measures the position of liked games in the recommendation list. When a player liked a game, its position in the player's recommendation list is rewarded by the inverse of its logarithmic rank. These are called the discounted cumulative gains. In the optimal ranking, we have ranked liked games on the top of the recommendation list, of the total $k_i=|\{j : R_{i,j}^{\text{validation}} = 1\}|$ liked games, and the discounted cumulative gain has the value $\text{IDCG}_i=\sum_{j=1}^{\text{min}(k_i,k)}1/\text{log}_2(j+1)$. The nDCG@k is the discounted cumulative gain in the recommendation list $r^{(i)}$ of length $k$, normalized by the maximum attainable value $\text{IDCG}_i$. The metric for the data set is the average over the players: \begin{equation} \begin{array}{c} \frac{1}{n}\sum_{i=1}^{n}\frac{1}{\text{IDCG}_i}\sum_{j=1}^{k} \frac{\mathbb{I}(\text{player } i \text{ likes game } r^{(i)}_{j})}{\text{log}_2(j+1)} \end{array} \end{equation} Because Precision@20 measures the top recommendations, we used used nDCG@m to measure the overall ranking. \subsection{Models} \subsubsection{Multivariate Normal Distribution (MVN)} First we present a simple new collaborative filtering model which has a competitive accuracy but simpler interpretation. This model allows us to explain the recommendations through explicit correlation matrix between games. The model also allows us to completely remove the influence of game popularity to investigate its effect. Assume that every row of the player like matrix is a sample from a multivariate normal distribution: $R_{i,:} \sim\mathcal{N}(\mu,\Sigma)$ with mean vector $\mu\in\mathbb{R}^{m}$ and covariance matrix $\Sigma\in\mathbb{R}^{m \times m}$. This model has a closed form solution for the distribution parameters, because the maximum likelihood estimate of these is the sample mean vector $\mu_j = \frac{1}{n}\sum_{i} R_{i,j}$ and the sample covariance matrix $\Sigma_{i,j} = \frac{1}{n}\sum_{s}(R_{s,i}-\mu_i)(R_{s,j}-\mu_j)$. In prediction time, we assume that the values of liked games are known to be one but the values for other games are missing. Denote the indices of liked games as $\mathcal{I}$ and the indices of other games as $\mathcal{J}$ so that $\mathcal{I}\cup\mathcal{J}=\{1,2,...m\}$. We use indexing $X_{\mathcal{J},\mathcal{I}}$ to denote the submatrix with rows from $\mathcal{J}$ and columns from $\mathcal{I}$, for example. The predictions for the missing game likes are then given by the expectation of the conditional distribution $R_{i,\mathcal{J}}^{*} = \mathrm{E}(R_{i,\mathcal{J}}|(R_{i,j}=1)_{j\in\mathcal{I}})$. This can be shown to equal the solution: \begin{equation} \begin{array}{c} R_{i,\mathcal{J}}^{*} = \mu_{\mathcal{J}} + \Sigma_{\mathcal{J},\mathcal{I}}(\Sigma_{\mathcal{I},\mathcal{I}})^{-1}(\overline{1}-\mu_{\mathcal{I}}) \end{array} \end{equation} To predict without game popularity, we remove the mean vectors from the formula and substitute the sample covariance matrix with the sample correlation matrix. This is equivalent mean centering and then normalizing the game like matrix column wise before applying the model. \subsubsection{k Nearest Neighbour (kNN)} The kNN is a simple recommendation method. Assume we have calculated the similarity between any two games in a $m \times m$ matrix $S_{ij}$. The rating prediction for game $j$ considers the $k$ most similar games in the game like matrix for player $i$. Denote this set of most similar games $D^{k}(i,j)$. The prediction for a player is the similarity weighted average to the player's like status of $k$ most similar games: $R_{i,j}^{*} = \sum_{s\in D^{k}(i,j)} S_{j,s} R_{i,s}/\sum_{s\in D^{k}(i,j)} S_{j,s}$. We evaluated the kNN on neigbhourhood sizes of $k=1,2,4,8,...,m$, but we always obtained the best results with the maximum neighbourhood size of $k=m$. As others have pointed out \cite{ref8}, the normalizing denominator is not necessary for the ranking task and we in fact obtained better predictions without it. We therefore predict simply by: \begin{equation} \label{similarity} \begin{array}{c} R_{i,j}^{*} = \sum_{s\in D^{k}(i,j)} S_{j,s} R_{i,s} \end{array} \end{equation} We define the similarity function as either the cosine (cos) or the Pearson correlation (phi), where $\mu_j=\sum_{i} R_{i,j}/n$ is the column mean of the game like matrix: \begin{equation} \begin{array}{c} S_{i,j}^{\text{cos}}=\frac{\sum_{s}R_{s,i}R_{s,j}}{\sqrt{\sum_{s}R_{s,i}^2}\sqrt{\sum_{s}R_{s,j}^2}} \end{array} \end{equation} \begin{equation} \begin{array}{c} S_{i,j}^{\text{phi}}=\frac{\sum_{s}(R_{s,i}-\mu_i)(R_{s,j}-\mu_j)}{\sqrt{\sum_{s}(R_{s,i}-\mu_i)^2}\sqrt{\sum_{s}(R_{s,j}-\mu_j)^2}} \end{array} \end{equation} \begin{figure*} \includegraphics[width=\textwidth]{illustration_models.eps} \caption{Illustration of the SVD and content models. Models can only generalize to settings (light green) for which they learn representations (light blue).} \label{fig:models} \end{figure*} \subsubsection{Singular Value Decomposition (SVD)} The SVD of dimension $k$ is defined in terms of $n \times k$ matrix $P$ of latent player factors as rows and $m \times k$ matrix $G$ of latent game factors as rows. It is a type of regularized matrix factorization because the predicted game like matrix is the product $R^{*}=PG^T$ of the factor matrices. A prediction for player $i$ and game $j$ is simply the product of the latent user vector $P_{i,:}\in\mathbb{R}^k$ and the latent game vector $G_{j,:}\in\mathbb{R}^k$. These latent vectors are initially unknown. We evaluated different choices of dimension $k=4,8,16,32,64,128$ and regularization parameter $\lambda$. For the SVD implementation in the Suprise library, a python package for implicit recommendations, we found that a grid of $\lambda=1,2,4,8,16,32,64,128,256,512$ produced a concave maximum between the values. We call the choice of $\lambda=0$ as PureSVD, because it is possible to use a standard singular value decomposition. The SVD was sensitive to regularization, but if the regularization choice was optimal we obtained almost identical results for dimensions $k\geq32$. The model parameters are found by minimizing the RMSE between observed game likes and predicted game likes: \begin{equation} \begin{array}{c} P, G = \text{argmin}_{P,G} \|R-PG^T\|^2_F + \lambda \|P\|^2_F + \lambda \|G\|^2_F \end{array} \end{equation} Where the matrix norm $\|X\|^2_F$ denotes the Frobenius norm, or the root mean square of every element in the matrix $X$. To find the parameters, one approach is to use Alternating Least Squares (ALS) optimization \cite{ref3}. In this method, either the latent game vectors $G$ or the latent player vectors $P$ are assumed to be fixed and the optimal solution for the other is found. Because in this case every row independently minimizes the squared error associated with that row, we can solve for each row with standard ridge regression either: \begin{equation} \begin{array}{c} P_{i,:} = (G^T G + \lambda I)^{-1} G^T R_{i,:}^T \end{array} \end{equation} \begin{equation} \begin{array}{c} G_{j,:} = (P^T P + \lambda I)^{-1} P^T R_{:,j} \end{array} \end{equation} The optimization starts by initializing $P$ and $G$ with random values. We iterate between fixing $G$ to find optimal values for $P$, and then fix the resulting $P$ to find optimal values for $G$. This is repeated until convergence. \subsubsection{Tags} The first content model is based on game features, which we call the 'Tags' model because our game features are based on game tags. We assume that each player has some interaction strength with each game feature. These interaction strengths are described by a player specific vector of length $r$. Collect these vectors as rows of the $n \times r$ model parameter matrix $T$, which needs to be learned from data. A given player may for example answer that they like 'Candy Crush' and 'Tetris', which implies that the player interacts positively with game tags 'puzzle' and 'tile-matching'. We predict the game likes as a product of the game features $X_{\text{tags}}$ and the player interaction strengths $T$: $R^{*}=TX_{\text{tags}}^T$. To find the parameters, we minimize the RMSE between observed game likes and predicted game likes: \begin{equation} \begin{array}{c} T = \text{argmin}_{T} \|R- TX_{\text{tags}}^T\|^2_F + \lambda \|T\|^2_F \end{array} \end{equation} Every row $T_{i,:}$ in fact independently minimizes the squared error associated with that row, so the model can be fitted separately for every row with standard ridge regression: \begin{equation} \begin{array}{c} T_{i,:} = (X_{\text{tags}}^T X_{\text{tags}} + \lambda I)^{-1} X_{\text{tags}}^T R_{i,:}^T \end{array} \end{equation} \subsubsection{Questions} The second content model is based on player features, which we call the 'Questions' model because our player features are based on questionnaire about gaming preferences. We assume that each game has an interaction strength with each player feature. These interaction strengths are described by a game specific vector of length $s$. Collect these vectors as rows of the $n \times s$ model parameter matrix $Q$, which needs to be learned from data. A given game 'Candy Crush' may for example be liked by players that have stated a preference for 'logical challenges' and 'racing against time'. We predict the game likes as a product of the player features $X_{\text{questions}}$ and the game interaction strengths $Q$: $R^{*}=X_{\text{questions}} Q^T$. To find the parameters, we minimize the RMSE between observed game likes and predicted game likes: \begin{equation} \begin{array}{c} Q = \text{argmin}_{Q} \|R- X_{\text{questions}} Q^T\|^2_F + \lambda \|Q\|^2_F \end{array} \end{equation} Again, every row $Q_{i,:}$ independently minimizes the squared error associated with that row, so the model can be fitted separately for every row of $Q$ with standard ridge regression: \begin{equation} \begin{array}{c} Q_{j,:} = (X_{\text{questions}}^T X_{\text{questions}} + \lambda I)^{-1} X_{\text{questions}}^T R_{:,j} \end{array} \end{equation} \subsubsection{Tags X Questions} The final content model is based on both game and player features, which we call the 'Tags x Questions' model because it is based on interactions between the game tags and the questionnaire answers. To model the game likes between every player $i$ and every game $j$, we assume that each (player, game)-pair is described by a feature vector. The feature vector for the pair is the tensor product of the player's features and the game's features. Given the $n \times s$ player feature matrix $X_{\text{questions}}$ and the $m \times r$ game feature matrix $X_{\text{tags}}$, the pair feature matrix can be represented as a $nm \times sr$ feature matrix $X_{\text{questions}} \otimes X_{\text{tags}}$. The logic behind this representation implies that the game likes are simply the sum of interaction strengths between player and game features, where the $r \times s$ interaction strength matrix as $A$ needs to be learned from data. A given player may for example answer that they like 'logical challenges' and 'racing against time', and the data implies that these answers interact positively with game tags 'puzzle' and 'tile-matching'. Denote the columnwise stacking of the interaction strength matrix as $\text{vec}(A)$, and the columnwise stacking of the $n \times m$ game like matrix as $\text{vec}(R^{*})$. Further denote the feature matrix as $X_{\text{interactions}}=X_{\text{questions}} \otimes X_{\text{tags}}$. The response is predicted as the sum of the player feature and game feature interactions: $\text{vec}(R^{*})=X_{\text{interactions}}\text{vec}(A)$. To find the model parameters, we minimize the RMSE between observed game likes and predicted game likes: \begin{equation} \begin{array}{c} A = \text{argmin}_{A} \|\text{vec}(R^{*})-X_{\text{interactions}} \text{vec}(A)\|^2_F + \lambda \|A\|^2_F \end{array} \end{equation} There is a mathematical optimization shortcut known as the vec-trick \cite{ref6}, which makes the minimization problem computationally tractable in the special case that the feature matrix is a Kronecker product. We use the python software package RLScore\footnote{http://staff.cs.utu.fi/~aatapa/software/RLScore} which implements this short cut to obtain an exact closed form solution to the ridge regression problem: \begin{equation} \begin{array}{c} \text{vec}(A) = (X_{\text{interactions}}^T X_{\text{interactions}} + \lambda I)^{-1} X_{\text{interactions}}^T \text{vec}(R^{*}) \end{array} \end{equation} \section{Results} \subsection{Model accuracy} \begin{table}[htbp] \caption{Ranking Accuracy by nDCG@m (\%)} \label{nDCG} \begin{center} \begin{tabular}{|r|r|r|r|r|} \hline \textbf{Model} & \textbf{Setting 1} & \textbf{Setting 2} & \textbf{Setting 3} & \textbf{Setting 4} \\ \hline Random & 13.9 & 13.2 & 14.6 & 13.4 \\ \hline MVN & \textbf{31.9} & 13.2 & 14.6 & 13.4 \\ \hline kNN (cos) & 30.0 & 13.2 & 14.6 & 13.4 \\ \hline kNN (phi) & 27.4 & 13.2 & 14.6 & 13.4 \\ \hline PureSVD & 28.4 & 13.2 & 14.6 & 13.4 \\ \hline SVD & 30.9 & 13.2 & 14.6 & 13.4 \\ \hline Tags & 23.4 & \textbf{22.3} & 14.6 & 13.4 \\ \hline Questions & 26.9 & 13.2 & \textbf{32.2} & 13.4 \\ \hline Tags X Questions & 23.2 & 19.9 & 24.3 & \textbf{20.1} \\ \hline \end{tabular} \label{tab1} \end{center} \end{table} \begin{table}[htbp] \caption{Recommendation List Accuracy by Precision@20 (\%)} \label{Precision} \begin{center} \begin{tabular}{|r|r|r|r|r|} \hline \textbf{Model} & \textbf{Setting 1} & \textbf{Setting 2} & \textbf{Setting 3} & \textbf{Setting 4} \\ \hline Random & 0.1 & 0.1 & 0.1 & 0.1 \\ \hline MVN & \textbf{5.0} & 0.1 & 0.1 & 0.1 \\ \hline kNN (cos) & 3.9 & 0.1 & 0.1 & 0.1 \\ \hline kNN (phi) & 3.2 & 0.1 & 0.1 & 0.1 \\ \hline PureSVD & 3.8 & 0.1 & 0.1 & 0.1 \\ \hline SVD & 4.3 & 0.1 & 0.1 & 0.1 \\ \hline Tags & 2.3 & \textbf{1.7} & 0.1 & 0.1 \\ \hline Questions & 3.4 & 0.1 & \textbf{4.3} & 0.1 \\ \hline Tags X Questions & 2.4 & 1.1 & 2.7 & \textbf{1.2} \\ \hline \end{tabular} \label{tab1} \end{center} \end{table} We report the accuracy of different models using nDCG@m in Table~\ref{nDCG} and Precision@20 in Table~\ref{Precision}. The metrics have values between 0-100\%, yet it is challenging to interpret the quality of recommendations from their absolute values. We can use accuracy metrics to compare and improve the models, but the results need to be verified qualitatively in practise. Comparing models by accuracy tells a clear-cut story. The two metrics have the same interpretation. In Setting 1, collaborative filtering methods outperform content based approaches with the MVN model delivering the best results. In Setting 2 we generalize to the new games, and only the Tags and Tags X Questions models are able to generalize. The Tags model has a greater degree of freedom and it performs better in this setting. In Setting 3 we generalize to new players, and only the Questions and Tags x Questions models are able to generalize. Again, the Questions model has more freedom to fit the data and performs better in this setting. For the last setting, only the Tags X Questions model which uses both features is able to make useful predictions. The mathematics underlying the generalization ability is illustrated in Figure~\ref{fig:models}. Predictions can only be made for player and game pairs where both games and players have representations which have been learned from the training set. However, if the representations can be learned for the setting it is useful to use more flexible models. There is therefore an important trade-off between using the provided features to generalize better or learning latent features to have better performance inside the training set games and players. \subsection{Model interpretation} \begin{figure*} \includegraphics[width=\textwidth]{illustration_interpretation.eps} \caption{Example of model interpretation: correlated games (MVN), tag responses (Tags), question responses (Questions) and interactions (Tags x Questions)} \label{fig:interpretation} \end{figure*} Because the models are based on simple linear models, we can interpret the model coefficients. The coefficients provide an explanation of why certain players are predicted to like certain games. This information can be useful for game developers or publishers that seek to understand the gaming market, and they can be used to tune the model towards qualitatively better predictions. Recalling that the MVN model predictions are based on the game mean vector $\mu$ and covariance matrix $\Sigma$, we interpret how collaborative filtering arrives at the predictions. The mean vector is simply the popularity of each game, calculated as the fraction of players that play each game. This is the starting point of the predictions, which are then adjusted based on the strength or positive or negative correlations to the games the player has played. For example, in Figure~\ref{fig:interpretation}, we provide 4 example games and their 4 most correlated games. These correlations are very believable, and these are the games whose play probability increases the most when player mentions the game in question. The exact calculation of the probability is based on the assumption of a normal distribution, which while incorrect, seems to work well in practise. The Tags model is based on inferring a player specific response vectors $T$ to the game tags, based on the games the player has liked. Fitting the model therefore produces a vector of $r$ interaction strengths to each of the game tags for each of the $n$ players. In Figure~\ref{fig:interpretation} we illustrate 4 example players with 3 liked games each and 4 tags with strongest implied interactions. It seems that the model is able to correctly learn the content of the liked games and describe the player in terms of their tag interactions. At prediction time, the games with these tags are predicted to be played the most by the player. The model can therefore generalize to new games by predicting games that have similar tag content. The Questions model is based on inferring a game specific response vectors $Q$ to the player preferences, based on the players that have liked the game. Fitting the model therefore produces a vector of $s$ interaction strengths to each of the questionnaire answers for each of the $m$ games. Figure~\ref{fig:interpretation} illustrates 4 example games and 4 answers with the strongest implied interactions. The model is able to correctly learn the content of these games from the types of players that play the game, based on their questionnaire answers. At prediction time, the players with these answers are predicted to be play the game. This model can therefore generalize to new players by predicting players that have similar preferences. The Tags X Questions model infers the interaction strengths $A$ between all player questionnaire answers and game tags, based on every player and game pair. Fitting the model produces a matrix of $r \times s$ interaction strengths, where each answer and tag pair have their own value. Figure~\ref{fig:interpretation} illustrates 4 example tags and 4 answers with the strongest implied interactions. These interactions are very logical and similar to what one might manually define: Puzzle tag for example interacts with the answer of liking 'Challenges of crosswords and other word puzzles'. With 61 possible answers and 379 game tags, manually defining and tuning 23 119 parameters is however infeasible. At prediction time, the players that have preferences which best match the game tags are predicted to be play the game. This model can therefore generalize to both new players and new games simultaneously. \subsection{Model Recommendations} Finally, we illustrate the model recommendations in Table~\ref{TopRecommendations}. The MVN model produces recommendations which are close to the games the player has played, and the Tags model provides close matches in terms of game genres. The Question and Tags x Questions models rely on rather ambiguous question answers, and as a result provide quite generic recommendations. However, their answers still seem better than random. The Tags model seems better than the Questions model, even though accuracy metrics suggest the opposite conclusion. There is a significant popularity bias visible in the Questions and Tags x Questions models, and to some extent in the MVN model. The effect of popularity can be removed from the MVN model as described earlier, and there is a similar trick that can be used with the other models. First, normalize the game like matrix $R$ column wise: substract the mean vector $\mu$ and divide by the standard deviation $\sigma=\sqrt{\mu(1-\mu)}$ to produce a matrix of standardized deviations from baseline popularity. Second, more popular games tend to have more tags provided so produce a more egalitarian 'game profile' vector by projecting $X_{\text{Tags}}$ with PCA into a lower dimensional space and normalize this vector. We found 16 dimensions worked qualitatively well. We skip reporting these results because they produced worse accuracy on the metrics, even though they virtually eliminated the effect of recommending popular but unrelated games. \begin{table*}[htbp] \caption{Example Players and Top 5 Game Recommendations from Different Models} \label{TopRecommendations} \begin{center} \begin{tabular}{|p{8mm}|p{30mm}|p{23mm}|p{23mm}|p{23mm}|p{23mm}|p{23mm}|} \hline \textbf{Player} & \textbf{Questions Liked} & \textbf{Games Liked} & \textbf{MVN} & \textbf{Tags} & \textbf{Questions} & \textbf{Tags X Questions} \\ \hline 93519 & Engaging in battle, Weapons and skills selection for characters, Searching and collecting rare treasures & Child of Light, Dungeon Master, Shin Megami Tensei: Persona 3 & Persona 5, Xenogears, Shin Megami Tensei: Persona 4, Chrono Cross, Bravely Default & Costume Quest, Ori and the Blind Forest, Abyss Odyssey, Fortune Summoners, Bahamut Lagoon & World of Warcraft, The Witcher 3: Wild Hunt, Diablo, The Elder Scrolls V: Skyrim, Overwatch & Fallout 4, Mass Effect 2, Fallout 3, Fallout: New Vegas, Warframe \\ \hline 93520 & Piloting and steering vehicles, Racing in a high speed, Challenges of tactics & Project CARS, Gran Turismo 5, Forza Horizon 2 & Grand Theft Auto V, Pokémon GO, Forza Motorsport 6, Gran Turismo 6, Hill Climb Racing 2 & DiRT 4, Gran Turismo 2, Gran Turismo (PSP), Forza Motorsport 4, Forza Motorsport 2 & Call of Duty, Grand Theft Auto, Clash of Clans, Angry Birds, Battle-field & StarCraft: Brood War, StarCraft, StarCraft II: Legacy of the Void, Doom II RPG, Call of Duty \\ \hline 93521 & Running in a fast speed while avoiding obstacles, Developing skills and abilities, Challenges of fast reaction & Shovel Knight, Super Mario 3D World, The Legend of Zelda: Ocarina of Time & The Legend of Zelda: Breath of the Wild, Super Mario Galaxy, Super Mario 64, The Legend of Zelda: The Wind Waker, The Legend of Zelda: A Link to the Past & The Legend of Zelda: Twilight Princess, Rogue Legacy, Assassin's Creed IV: Black Flag, The Legend of Zelda: A Link to the Past, Power Stone 2 & TETRIS, League of Legends, Call of Duty, Crash Bandicoot, Minecraft & StarCraft, Tomb Raider, Dota 2, StarCraft: Brood War, Counter-Strike: Global Offensive \\ \hline 93522 & Hugging, kissing and making out, Investigating the story and its mysteries, Challenges of logical problem-solving & Heavy Rain, Steins;Gate, Life Is Strange & The Last of Us, Pokémon GO, The Witcher 3: Wild Hunt, World of Warcraft, TETRIS & Beyond: Two Souls, The Wolf Among Us, Zero Escape: Zero Time Dilemma, Persona 4 Golden, Alan Wake & Sudoku, The Sims, Angry Birds, Pokémon GO, Counter-Strike: Global Offensive & Mass Effect 2, Fallout 3, The Elder Scrolls IV: Oblivion, The Elder Scrolls V: Skyrim, Fallout: New Vegas \\ \hline 93523 & Decorating rooms and houses, Hugging, kissing and making out, Challenges of logical problem-solving & Cities: Skylines, Overcooked, The Sims 2 & The Sims 3, The Sims, Civilization V, The Sims 4, The Elder Scrolls V: Skyrim & Train Valley, Prison Architect, The Sims, RollerCoaster Tycoon 3: Platinum, Tropico 4 & Sudoku, The Sims, TETRIS, Gardenscapes, World of Warcraft & Warframe, The Elder Scrolls IV: Oblivion, Dragon's Dogma: Dark Arisen, The Sims, Stardew Valley \\ \hline \end{tabular} \label{tab1} \end{center} \end{table*} \section{Conclusion} Research in game recommendation has focused on the prediction of missing game likes in data sets of historical player and game interactions. However, many practical tasks require predictions for completely new games and players. Collaborative filtering has been found to be a useful model in the traditional setting, but for games or players with few or no interactions different models are required. We presented content based Tags, Questions, and Tags X Questions models that generalize into new games, new players, or both simultaneously. These methods are inspired by the Singular Value Decomposition (SVD), a standard approach in collaborative filtering, where one or both of the feature vectors are assumed to be given. The optimization corresponds to a linear model with computational shortcuts, which makes them fast and easily interpretable. We compared the following models: Random baseline, Multivariate Normal Distribution (MVN), k Nearest Neighbour (kNN) with cosine or Pearson similarity, PureSVD, SVD, Tags, Questions, Tags x Questions. We evaluated the performance with the nDCG and Precision@20 metrics within known games and players (Setting 1), new games (Setting 2), new players (Setting 3) and both new games and new players (Setting 4). We found that each content based model performed the best in the setting for which it was designed, and restricting the models to use the provided features instead of learning latent features is useful in terms of generalization ability but has a trade off in terms of accuracy. Each model can therefore be useful depending on the setting. Finally, we note that accuracy does not tell the full story because the qualitative results do not seem to perfectly correlate with accuracy.
{'timestamp': '2020-09-21T02:18:08', 'yymm': '2009', 'arxiv_id': '2009.08947', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08947'}
arxiv
\section{1. Background} In China, with the exploding evolution of e-commerce, online-sell-platform has been iterated qualitatively and quantitatively to a highly competitive period. Therefore, in order to survive in such a dynamic and competition-fierce market environment, every online-sell-platform has to innovate new techniques to attract more consumers in buyer side and increase more retailers' revenue in seller side. This work solves a concrete problem, i.e. how to help retailers (shops) to lift up revenue by employing DMCs. As illustrated in Figure \ref{iphone}, each online shop (on the leftmost plot) on the online-sell-platform has given their DMCs in red. And in the rightmost plot each shop can complete the DMC settings manually or automated by using DMC recommendation indicated in red. The DMC recommendation is all what this paper concerning about. Though given the prototype plots in Figure \ref{iphone}, as a leading online-sell-platform in China the real application has been implemented by authors before this paper. \section{2. Introduction} In traditional marketing, campaign is often used by retailers to lift up revenues. In recent years, with the rushing development of e-commerce, DMC has been in tendency in online marketing. Especially, with the flexible implementation of combination of DMCs, more revenue can be achieved compared with those not-combined DMCs. For example, campaign threshold-discount pairs $<threshold,discount>$, say $<60, 5>$ and $<70, 8>$, mean that in an online shop a consumer can have two campaigns at the same time. If the consumer buys a basket of food worth $\$60$ then the campaign $<60, 5>$ is triggered, and the consumer obtains $\$5$'s discount. If the consumer buys a basket of food worth $\$70$ then the both campaigns $<60, 5>$ $<70, 8>$ are triggered, and the consumer obtains $\$8$'s discount. Applying these DMCs is of benefit to transfer the low-value consumer to high-value consumer, which will finally result in boosting revenue. In traditional retailing times when the big data infrastructure is not accessible, sellers use their selling experience frequently. However in new retailing era, with the help of big data, online-sell-platform can help retailers to increase their return by automated generating combined multiple DMCs. This paper presented a comprehensive solution to generating combined multiple DMCs. Here it is necessary to introduce the rules of DMC. It can be understood as a special kind of digital coupon. That is the DMC is issued by individual online shops, hence each shop on the online-sell-platform has its own DMCs oriented to distinct marketing objectives. And each DMC has a trigger threshold and a discount amount, i.e. DMC threshold-discount pair. For example, an online shop issues a DMC with a threshold-discount pair of $<90, 10>$, then if a consumer's shopping cart is fulfilled with products worth more than $\$90$ then the $<90, 10>$ DMC is triggered. And the consumer will obtain a $\$10$ discount, i.e. the consumer saves $\$10$ and only needs to pay $\$80$. \begin{figure*}[t] \centering \includegraphics[width=0.6\textwidth]{background3.png} \caption{The leftmost plot illustrates the online-sell-platform with three independent online-shops, in which there list distinct current DMCs in red in the shop. The middle plot gives the consumer side interface with red fonts indicating the current DMCs active in the shop. The rightmost plot shows the interface of the retailer side, setting DMCs with the red fonts giving the multiple DMCs recommendation. } \label{iphone} \end{figure*} In fact, it is a rather complicated problem to assure the effectiveness of recommending the digital marketing campaigns. From the macro aspect, the price elasticity can be depicted as the relationship between the discount strength and the selling volume, it is a multi-factor problem and it is hard to collect data to compute price elasticity. Therefore the problem is difficult to solve with price elasticity method commonly used in marketing field. This paper proposed a comprehensive solution to solve such problem based on DMCNet and Randomlized USM (unconstrained submodular maximization) Algorithm\ {\cite{buchbinder2015sb1}}. DMCNet is a neural network model proposed to calculate the DMC's triggering probability for each consumers. More importantly, the revenue of each DMC for a online shop can be calculated by DMCNet. More detail will be shown in Section 3. Randomlized USM Algorithm proposed a solution to non-monotonic submodular problem like optimal combination of DMCs. Together with DMCNet, the maximum of DMCs revenue will be obtained. This paper contains four parts, In section $3$, DMCNet will be introduced. Section $4$ describes the motivation to resolve optimal combination of DMCs as a non monotonic submodular problem, and the method to obtain optimal revenue of this problem. The whole recommendation solution and pseudo code are presented in section $5$. Experiment will be given in section 6. Last section concludes the paper. \begin{figure*}[t] \centering \includegraphics[width=.7\textwidth]{DMCNetLSTM.pdf} \caption{Topological structure of DMCNet}. \label{figDMCNet} \end{figure*} \subsection{Review of Related Techniques} The main techniques invested in this work contain recommender system (RS), deep learning (DL). Recommender system is a tool to retrieve information to help users make decisions efficiently. Especially with the fast development of e-commerce, RS plays a pivotal and indispensable role, not only in consecutively ameliorate the consuming experience but also helpful in lifting up retailers' revenue. Essentially, a typical RS leverages user profile, item features, user-item interaction information and other inputs like temporal and spatial data to predict the user's next choice. Typical RS can be categorized as three classes, i.e. collaborative filtering, content-based RS and hybrid RS, see \cite{rscategory}. Deep learning has been receiving in decades more and more attentions after tremendous advance in theory \cite{lecun1989cnn0,lecun1998cnn1,hinton2009DBN,cho2014gru} and computing infrastructure \cite{dean2008mapreduce,shvachko2010hadoop,zaharia2011spark,jouppi2017TPU}. Massive applications have been innovating in industry and achieving in SOTA, e.g. in fields of natural language processing \cite{vaswani2017attention, devlin2018bert,yang2019xlnet} and computer vision \cite{simonyan2014vgg,he2016resnet,redmon2016you}. The hybrid model incorporating deep learning into recommender system has become the tendency in industrial recommendation system \cite{zhang2019rssurvey}, e.g. deep collaborative model \cite{li2015deepcf}, wide and deep model \cite{cheng2016wide}, deepfm model \cite{guodeepfm}, deep interest model \cite{zhou2018din,zhou2019dien}. Here it is necessary to mention that the comprehensive solution in this work lends the idea from deep-learning based recommender system and combinatorial optimization. \section{3. Digital-Marketing-Campaign Net} In this paper the DMCNet (Digital-Marketing-Campaign Net) is employed to score the probability of triggering a single DMC by a consumer. The score is calibrated to the probability, hence the higher the score the more probable that a consumer browsing the shop would trigger a DMC. \subsection{Features Employed in DMCNet} The DMCNet is a deep neural net model and its topological net structure is shown in Figure \ref{figDMCNet}. The input layer contains four kinds of features, i.e. dense features, sparse features, target DMC threshold-discount pair and not-target DMC threshold-discount pair. The dense part contains nine features, including order date, shop id, city id, customer id, GMV in recent 30 days, GMV in recent 60 days, GMV in recent 90 days, target DMC threshold and target DMC discount. The sparse features employed in DMCNet includes shop category, consumer age and consumer gender, which are all one-hot handled. Features specifying campaign threshold and campaign discount are divided into two parts by target and not-target. Target part colored in orange in Figure \ref{figDMCNet} contains target campaign threshold and target campaign discount, while in the not-target part many not-target campaign threshold-discount pairs colored in purple in Figure \ref{figDMCNet} are employed. Not-target campaign threshold-discount pairs are used to depict campaigns simultaneously presented to the consumers along with the target campaign threshold-discount pair. \subsection{DMCNet Structure } For dense features, a three-hidden-layer fully connected forward network is employed to learn high order features. And the result of learned vector will be concatenated with the sparse features. Here the target campaign threshold-discount pair is a scalar tuple which defines the DMC triggering threshold and the discount that the DMC triggered customer can obtain. Among the observed samples, the range of the threshold and discount varies largely, therefore in this paper the both features are monotonically encoded with a 500 length vector, which is termed as the isotonic encoding. For example, a threshold-discount pair is $<10, 1>$, meaning that in this campaign if a consumer buys $\$10$ food then the consumer will obtain a $\$1$'s discount. Then the isotonic encoding for this campaign threshold-discount pair is that $\$10$ is encoded as $(1,1,1,1,1,1,1,1,1,1,0,0,0,...,0)^{\top}_{500\times 1}$ and $\$5$ as $(1,1,1,1,1,0,0,0,...,0)^{\top}_{500\times 1}$. After isotonic encoding the target campaign threshold-discount, the 500-dimensional threshold and discount vectors are element-wise multiplied individually with the above mentioned concatenated output from dense and sparse features. The rest not-target campaign threshold-discount pairs are also handled with isotonic encoding. The encoded vectors are separately element-wise multiplied to form many output vectors with 500 dimensions. \subsection{DMC Embedding} As is shown in Figure \ref{figDMCNet}, many not-target campaign threshold-discount pairs colored in purple are employed in DMCNet, whose volume varies in diverse contexts. That is for different consumers the number of all DMC threshold-discount pairs (target DMC plus not-target DMC) are different. Some consumers may be exposed with more campaigns than others. Therefore, the campaign threshold-discount pairs are specially handled as the sequential features, some sequence may be long while some may be short. Popular methods to handle the sequence data contains LSTM, GRU and Transformer-encoder. Here the LSTM with Attention is used to generate an embedding for the input not-target campaign threshold-discount pairs. This means different quantity of not-target campaign threshold-discount pairs can be compressed into an embedding, i.e. DMC-Embedding, having the same length after LSTM-Attention module on the DMCNet. Then the DMC-Embedding will be processed by a three-hidden-layer fully connected forward net. After concatenating and again a three-hidden-layer fully connected forward net on the Figure 1, the softmax score will be returned a score to specify the likelihood of the consumer's triggering the target DMC. \section{4. Marketing Campaign Combination Optimization} \subsection{Marketing Campaign Combination} Marketing campaign response depicts the relationship between campaign and revenue of retailer, which represented by function $f$. The input of $f$ is campaigns set up by retailer, the output of $f$ is revenue. From business sense, submodularity of this function can be proved. First, campaigns could improve revenue by encouraging consumers to place orders, however, consumers’ willingness-to-pay is limited, which means more campaigns will make marginal effect decrease. According to the analysis before, function $f$ obviously is submodular, which satisfies \textit{c.f.} Definition 1 and Definition 2. \begin{definition}{\cite{buchbinder2018deterministicsb3}} Given a ground set $\mathcal{N} = \{u_0, u_1,...,u_n\},\ \text{set function } f: 2^{\mathcal{N}} \xrightarrow{} R\ $ is called submodular if and only if $$f(A) + f(B) \ge f(A\cap B) + f(A\cup B)\ \forall A,B \subseteq \mathcal{N}$$ \end{definition} \begin{definition}{\cite{buchbinder2018deterministicsb3}} Given a ground set $\mathcal{N}$ = $\{u_0, u_1,...,u_n\}$, set function $f: 2^\mathcal{N} \xrightarrow{} R\ $ is called submodular if and only if $$f(A + u) - f(A) \ge f(B + u) - f(B) \ \forall A, B \subseteq \mathcal{N}, u \in \mathcal{N} \backslash B$$ \end{definition} More importantly, campaign combinatorial problem is not a strict monotonic increasing problem. For example, campaign\{a\}=$<39, 3>$, campaign\{b\}=$<29, 1>$, when \{b\} and \{a\} exposed to consumers at the same time, some consumers may choose campaign \{b\} which leads the decrease of customer price, that is $Revenue(\{a,b\}) < Revenue(\{a \})$. Marketing campaign combinatorial problem is described as follows, $\max f(A),\ s.t. \ |A| = k,\ A\subseteq \mathcal{N}$, $\mathcal{N}$ = $\{u_0, u_1,...,u_n\}.$ $k$ is the number of combination. Therefore, campaign combinatorial problem is an unconstrained and non monotonic submodular maximization problem. According to the discussion, this paper proposes a solution \textit{c.f.} Figure 3 in next section . \section{5. Recommendation Solution} \subsection{Initializing Candidate Threshold-Discount Pairs} \begin{figure}[htb] \centering \includegraphics[width=0.5\textwidth]{processgraphv3.pdf} \caption{The process graph of multiple DMCs recommending solution.} \label{processgraph} \end{figure} Firstly, an iteration traverses from minimum threshold to maximum threshold, accompanying the second iteration from 0 to threshold. As the initial candidate set of threshold-discount pairs, set $C$ contains all combinations of threshold and discount, \textit{c.f.} Algorithm 1. \begin{algorithm}[h] \caption{Initializing Basic Threshold-Discount Pairs} \begin{algorithmic}[1] \STATE $C \gets \varnothing$ \FOR{$threshold \gets threshold_{min}$ $to$ $threshold_{max}$} \FOR{$discount \gets 0 $ $to$ $threshold$} \STATE $C \gets <threshold, discount>$ \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \subsection{Computing Profit of Each Threshold-Discount Pair Employing DMCNet} Generally speaking, this paper selects consumers whose geographic location is around shops as our potential consumers. By computing threshold and discount of each potential consumer and shop, revenue of each threshold-discount pair can be obtained. Pseudo code is given as follows \textit{c.f.} Algorithm 2. Function $F$ is the DMCNet which discussed at previous section. \begin{algorithm}[h] \caption{Computing Threshold-Discount-Pair Revenue } \begin{algorithmic}[1] \STATE $i \gets 0;$ \STATE $n \gets Count(C);$ \STATE $j \gets 0;$ \STATE $m \gets Count(user)$ \FOR{$i \gets 0$ $to$ $n$} \STATE $Revenue_{C_i} \gets 0$ \FOR{$j \gets 0$ $to$ $m$} \STATE $Revenue_{C_i} \gets Revenue_{C_i} + F(C_i, user_j, \varnothing)$ \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \subsection{Iterating Greedy Algorithm to Obtain Sequence Of Threshold-Discount Pairs} So far the set of all threshold-discount pairs and their revenue have been obtained. The set generated previously contains all threshold-discount pairs, like $<60, 1>$, $<60, 2>$, $<60, 3>$, $<50, 1>$, $<50, 2>$, $<50, 3>$ and so on, which can not be shown simultaneously. For example, in actual threshold-discount pairs, either $<60, 1>$ or $<60, 2>$ will be displayed, which means only one will be shown. Therefore, more business rules is necessary, such as, one threshold can only have one discount. The difference between adjacent thresholds must be at least $n$ , which always set $n=\$5$, finally, as threshold increases, discount must increase similarly, for example, if campaign $<50, 4>$ is contained, then the discount of 60 must be higher than $\$4 $. All of the inputs based on even common sense or business rules, will have the following advantages, firstly, it will reduce the optimal threshold-discount pair computing scale afterwards. Secondly, it makes our model more consistent with business logic. By sort set $C$ with revenue and filter set $C$ with business rules, a new set $C$ is generated. Function $fit(C_i, R, D )$ return true if $C_i$ conforms with the rules $R$ \textit{c.f.} Algorithm 3. \begin{algorithm}[h] \caption{Generating Fundamental Threshold-Discount-Pair Sequence} \begin{algorithmic}[1] \STATE $C \gets Sort(C, revenue)$ \STATE $D \gets \varnothing$ \FOR{$i \gets 0 $ $to$ $n$} \IF{$fit(C_i, R, D )$} \STATE $D \gets C_i + D$ \ENDIF \ENDFOR \STATE $C \gets D$ \end{algorithmic} \end{algorithm} \subsection{Obtain Optimal Threshold-Discount Pairs By Randomized USM Algorithm} Finally, based on the generated set of threshold-discount pairs, threshold-discount pair is added to the final set successively using greedy algorithm. For each adding action, recompute revenue to decide whether this pair should be added to final set or not. Besides this, this paper use randomized USM algorithm (\textit{c.f.} Algorithm 4) which is proved more effectively. Not only it computes whether revenue is uplifted after one specific threshold-discount pair is added, but also computes the change of revenue after the pair is removed. \begin{algorithm}[h] \caption{Randomized USM Algorithm} \begin{algorithmic}[1] \STATE $X_0 \gets \varnothing, Y_0 \gets Random(C)$ \FOR{$i = 1 $ $to$ $n$} \STATE $a_i \gets {F(X_{i-1} + c_i, user) - F(X_{i-1}, user)}$ \STATE $b_i \gets {F(Y_{i-1} - c_i, user) - F(Y_{i-1}, user)}$ \STATE ${a_i'} \gets max\{a_i,0\}, {b_i'} \gets max\{b_i,0\}$ \STATE $with$ $probability$ $\frac{a_i'}{{a_i'} + {b_i'}} $ $do$ : $X_i \gets X_{i-1} + c_i, Y_i \gets Y_{i-1}$ \STATE $with$ $probability$ $\frac{b_i'}{{a_i'} + b_i'} $ $do$ : $X_i \gets X_{i-1}, Y_i \gets Y_{i-1} - c_i$ \ENDFOR \STATE $C \gets X_n$ \end{algorithmic} \end{algorithm} It can be proved that this algorithm is 1/2\ approximation algorithm for the USM problem, that means $\text{E}(f(A_k)) \geq \frac{1}{2}f(OPT)$. {\cite{buchbinder2015sb1}} \begin{table}[htb] \centering \begin{tabular}{l|l|l} \hline\hline Search Method & GMV & Time Cost \\ \hline\hline Global Optimum Searching & {3,976,560} & 6.3 hours \\ Randomized USM Searching & {2,177,239} & 20 minutes \\ Greedy Searching & {1,802,452} & 14 minutes \\ \hline\hline \end{tabular} \caption{GMVs and related time costs in employed searching methods. } \label{tb6} \end{table} \begin{table} \centering \begin{tabular}{l|l|l} \hline \hline City & Sample Size Control & Sample Size Treatment \\ \hline \hline Jinhua & 38 & 17 \\ Ningbo & 42 & 19 \\ Changsha & 62 & 20 \\ Tianjin & 158 & 19 \\ \hline \hline \end{tabular} \caption{Sample sizes in control group and treatment group distributed in four Chinese cities.} \label{tb1} \end{table} \begin{table}[htb] \centering \begin{tabular}{l|l|l} \hline\hline Model & Train AUC & Test AUC \\ \hline \hline XGBoost & 0.637 & 0.604 \\ DMCNet without LSTM Emb. & 0.750 & 0.700 \\ DMCNet with LSTM Emb. & 0.810 & 0.750 \\ DMCNet with LSTM Emb. \& Att. &0.810 & $\mathbf{0.760}$ \\ \hline\hline \end{tabular} \caption{AUC comparison with four test models.} \label{tb5} \end{table} \begin{table*}[htb] \centering \begin{tabular}{l|l|l|l|l} \hline \hline Group & Time & Avg Net GMV pS & Avg Order Vol. pS & Avg Net Cust. Price pS \\ \hline \hline Treatment & Week1 & 1019.61 & 23.4 & 43.58 \\ Treatment & Week2 & 1083.45 & 24.34 & 44.51 \\ \hline chain ratio week1 over week2 & & +6.26 & +4.02\% & +2.13\% \\ \hline Control & Week1 & 1207.11 & 28.74 & 42.01 \\ Control & Week2 & 1216.89 & 29 & 41.96 \\ \hline chain ratio week1 over week2 & & +0.81\% & +0.9\% & -0.12\% \\ \hline Ratio of Treatment over Control & & +5.45\% & +3.11\% & +2.25\% \\ \hline \hline \end{tabular} \caption{Comparison of average net GMVs (Gross Merchandise Volume) per shop and average order volume per shop and average net customer price per shop between control group and treatment group.} \label{tb2} \end{table*} \begin{table*}[htb] \centering \begin{tabular}{l|l|l|l} \hline \hline Group & Time & Net Cust. Price Aft. Triggering Camp. & Not Net Cust. Price Aft. Triggering Camp. \\ \hline \hline Treatment & Week1 & 45.65 & 42.98 \\ Treatment & Week2 & 51.13 & 41.90 \\ \hline chain ratio week1 over week2 & & +12.02\% & -2.52\% \\ \hline Control & Week1 & 43.64 & 41.42 \\ Control & Week2 & 41.73 & 42.05 \\ \hline chain ratio week1 over week2 & & -4.39\% & +1.53\% \\ \hline Ratio of Treatment over Control & & +16.41\% & -4.05\% \\ \hline \hline \end{tabular} \caption{Comparison of control group and treatment group in net customer after triggering a campaign and not net customer after triggering a campaign. } \label{tb3} \end{table*} \begin{table*}[htb] \centering \begin{tabular}{l|l|l|l|l} \hline \hline Group & Time & Ratio of Camp.-based Order Vol. Over Total Order Vol. & App P1 & App P2 \\ \hline\hline Treatment & Week1 & 22.31\% & 5.87\% & 24.74\% \\ Treatment & Week2 & 28.14\% & 6.27\% & 26.61\% \\ \hline chain ratio week1 over week2 & & 26.13\% & 6.81\% & 7.56\% \\ \hline Control & Week1 & 26.64\% &7.25\% & 27.85\% \\ Control & Week2 & 27.94\% & 7.18\% & 29.44\% \\ \hline chain ratio week1 over week2 & & +4.88\% & -0.97\% & +5.71\% \\ \hline Ratio of Treatment over Control & & +21.25\% & +7.78\% & +1.85\% \\ \hline \hline \end{tabular} \caption{Comparison of control group and treatment group in ratio of campaign-based order volume over total order volume, app p1 (click-through) and app p2 (conversion).} \label{tb4} \end{table*} \section{6. Real Online Experiment} \subsection{Experiment Setup} The online experiment is an A/B-test which was performed in diverse Chinese cities' online-shops. Treatment group and control group are selected from four Chinese cities, see Table \ref{tb1}. Totally, 65 online-shops for treatment group and 300 for control group are chosen. Two time windows (two weeks in total) are selected, one for control group between 2020-04-17 and 2020-04-23 and another for treatment group between 2020-04-24 and 2020-04-30. There are many diverse types of shops in authors' online-sell-platform, including online supermarket, online convenience-store, online fruit-shop and online fresh-supermarket. In this work only online convenience-store are tested, since this kind shops are popular in Chinese cities. \subsection{Model Comparison} Deep neural network tested in the experiment contains four distinct models, including XGBoost, DMCNet without embedding, DMCNet with only LSTM embedding, and DMCNet with LSTM embedding and multihead-attention. From Table \ref{tb5}, it is outstanding that the DMCNet with LSTM embedding and multihead attention performs better than the other models. Especially, the difference between DMCNet with and without LSTM embedding is about 10 percent large. Hence it shows that the DMCNet with LSTM embedded sequence of the threshold-discount pairs is vital in improving the model performance. \subsection{Optimization Methods Comparison} This paper compares three optimization methods on 100 stores data during one month. The greedy algorithm and randomized USM Algorithm and Global Search Algorithm. From Table \ref{tb6}, randomized USM algorithm obtains higher revenue than the greedy algorithm and less time than global search algorithm. \subsection{Evaluation Metrics} In this experiment, eight distinct metrics have been employed, including average net GMV per shop, average order volume per shop, and average net customer price per shop, \textit{c.f.} Table \ref{tb2}. Also net customer price after triggering a campaign and net customer price not triggering a campaign are contained in Table \ref{tb3}. And ratio of campaign-based order volume versus total order volume, and app p1 (click-through) and app p2 (conversion) are included as evaluation metrics in Table \ref{tb4}. \subsection{Experiment Results Discussion} First of all, within two weeks' experiment, the real net GMV increasing rate arrived at $6.26\%$ compared to the pre-set target rate of $3\%$. Secondly, the daily net GMV in treatment group through week 2 is $5.45\%$ higher than it in week 1, \textit{c.f.} Table \ref{tb1}. Thirdly, compared with control group, the increase rate of net customer price in treatment group is higher than it in control group. From the perspective of net customer price after triggering a campaign and net customer price not triggering a campaign, the former increases positively while the later negatively. This evicts that the former's effect can terminate the negative effect by the later and eventually pushes up the total net customer price, see Table \ref{tb3}. And the two weeks' chain ratios of net customer price after triggering a campaign between the control and treatment groups also demonstrates that the DMC recommendation is reasonable. Fourthly, in metric of campaign-based order volume over total order volume, treatment group's performance is better than the control group. This shows that the DMC recommendation indeed enlarge the order volume. Combining with the third point, it concludes that the DMC recommendation is the direct momentum to increase the net GMV in treatment group. Last but not the least, the click-through (APP P1) and conversion (APP P2) both increase in treatment group while not in the control group, see Table \ref{tb4}, meaning that it has positive relationship with applying multiple DMCs. \section{7. Conclusion} This work proposes a comprehensive solution of using digital-marketing-campaign to increase shop's GMV. First of all, the DMCNet is employed to compute the probability of triggering DMC, whose network structure is a hybrid deep learning model combining deep net and LSTM-Attention. Deep net component is used to learn the representation of user profile and contextual features and LSTM-Attention component is served as the DMC embedding generator. The combinatorial optimization is performed based on the sub-modular optimization theory to generate a set of optimal threshold-discount pairs. The real online A/B-test on a online e-commerce platform evicts that the proposed solution increase the revenue of retailers significantly.
{'timestamp': '2020-09-21T02:18:08', 'yymm': '2009', 'arxiv_id': '2009.08949', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08949'}
arxiv
\section{Improving User Engagement Through an AI-driven Design for Diagnostic Interface} As the user decides whether to continue their study through \emph{Santa} after viewing the diagnostic page, we consider the page design that encourages user engagement and motivates them to study further. Throughout this section, we explore the design of the diagnostic page that can most effectively express the AI features brought by back-end AI models and better explains the user’s problem-solving process in the diagnostic test. We propose two page designs summarizing the user’s diagnostic test result: page design A (Figure \ref{fig:page_A}) and page design B (Figure \ref{fig:page_B}). Each page design provides analytics of the diagnostic test result at different levels of information and explainability, and is powered by different AI models running behind \emph{Santa}. The effectiveness of each page design and its impact on user engagement is investigated through controlled A/B tests in Section \ref{sec:exp}. \begin{figure*} \centering \begin{subfigure}[ht]{0.49\columnwidth} \centering \includegraphics[width=0.5\columnwidth]{figures/page_A.png} \caption{} \label{fig:page_A} \end{subfigure} \begin{subfigure}[ht]{0.49\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_B.png} \caption{} \label{fig:page_B} \end{subfigure} \caption{Page design A(a) and B(b) proposed in the paper. Note that the original version of each page is in Korean. We present the English version of each page design in order to facilitate the understanding of readers around the world.} \label{fig:page_AB} \end{figure*} \subsection{Page Design A} Page design A presents the following four components: \emph{Estimated Score}, \emph{Grade by Part}, \emph{Comparison to Users in the Target Score Zone} and \emph{Tutor’s Comment}. \begin{figure*} \centering \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_A_score.png} \caption{} \label{fig:page_A_score} \end{subfigure} \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_A_part.png} \caption{} \label{fig:page_A_part} \end{subfigure} \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_A_tutor_comment.png} \caption{} \label{fig:page_A_tutor_comment} \end{subfigure} \caption{\emph{Estimated Score}, \emph{Grade by Part} and \emph{Tutor's Comment} components in the page design A.} \end{figure*} \subsubsection{Estimated Score} This component shows the user’s overall expected performance on the actual TOEIC exam and presents the following features: estimated scores, target scores and percentile rank (Figure \ref{fig:page_A_score}). The estimated scores are computed from the back-end score estimation model and the target scores are values the user entered before the diagnostic test. The estimated scores and the target scores are presented together so that the user easily compares them. The percentile rank is obtained by comparing the estimated score with scores of more than a million users recorded in the database of \emph{Santa}. \subsubsection{Grade by Part} This component provides detailed feedback for the user’s ability on each question type to help them identify their strengths and weaknesses (Figure \ref{fig:page_A_part}). For each part in TOEIC exam, the red and white bar graphs show the user’s current proficiency level and the required proficiency level to achieve the target score, respectively. The red bar graphs are obtained by averaging the estimated probabilities of the user correctly answering the potential questions for each part. Similarly, the white bar graphs are obtained by computing the averaged correctness probabilities for each part of users in the target score zone. \begin{figure*} \centering \includegraphics[width=0.4\columnwidth]{figures/page_A_radar_chart.png} \caption{\emph{Comparison to Users in the Target Score Zone} in the page design A. The radar chart is intended to give the feeling that the AI teacher is analyzing the users closely from multiple perspectives by presenting the five features of their particular aspects of ability.} \label{fig:page_A_radar_chart} \end{figure*} \subsubsection{Comparison to Users in the Target Score Zone} This component shows a radar chart of five features representing the user’s particular aspects of ability (Figure \ref{fig:page_A_radar_chart}). The five features give explanations of how AI models analyze the user’s problem-solving process, making \emph{Santa} looks more like an AI teacher. The five features are the followings: \begin{itemize} \item Performance: The user’s expected performance on the actual TOEIC exam. \item Correctness: The probability that the user will correctly answer each given question. \item Timeliness: The probability that the user will solve each given question under time limit. \item Engagement: The probability that the user will continue studying with \emph{Santa}. \item Continuation: The probability that the user will continue the current learning session. \end{itemize} The red and white pentagons present the five features with values of the current user and averaged values of users in the target score zone, respectively. This component is particularly important as shown in Section \ref{sec:exp} that users’ engagement factors vary greatly depending on the presence or absence of the radar char. \subsubsection{Tutor's Comment} This component presents natural language text describing the user’s current ability and suggestions for achieving the target score (Figure \ref{fig:page_A_tutor_comment}). This feature is intended to provide a learning experience of being taught by a human teacher through a more human-friendly interaction. Based on the user’s diagnostic test result, the natural language text is selected among a set of pre-defined templates. \subsection{Page Design B} Although the page design A is proposed to provide AI-powered feedback for the user’s diagnostic test result, it has limitations in that the composition is difficult to deliver detailed information and insufficient to contain all the features computed by AI models. To this end, the page design A is changed in the direction of making better use of AI features, leading to the page design B which is more informative and explainable to the user’s problem-solving process in the diagnostic test. The page design B consists of the following seven components: \emph{Estimated Score}, \emph{Analysis of Problem-Solving Process}, \emph{Skill Proficiency}, \emph{Recommended Lectures}, \emph{Analysis of Users Similar to You}, \emph{Adaptively Offered Curriculum} and \emph{Santa Labs}. \begin{figure*} \centering \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_B_score.png} \caption{} \label{fig:page_B_score} \end{subfigure} \centering \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_B_problem_solving.png} \caption{} \label{fig:page_B_problem_solving} \end{subfigure} \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_B_proficiency.png} \caption{} \label{fig:page_B_proficiency} \end{subfigure} \caption{\emph{Estimated Score}, \emph{Analysis of Problem-Solving Process} and \emph{Skill Proficiency} components in the page design B.} \end{figure*} \subsubsection{Estimated Score} The target scores and the mountain shaped graphic illustrating the percentile rank in the \emph{Estimated Score} component of the page design A are excluded in that of the page design B (Figure \ref{fig:page_B_score}). The \emph{Estimated score} component of the page design B only shows the estimated scores and the number indicating the percentile rank, making this component more concise and intuitive. \subsubsection{Analysis of Problem-Solving Process} This component provides an overall review session for the diagnostic test (Figure \ref{fig:page_B_problem_solving}). It presents the percentage of correct answers, the time taken to complete the diagnostic test and how much time has passed than the recommended time. Also, through the \emph{View Explanations} button, the user can review the questions in the diagnostic test and their explanations. \subsubsection{Skill Proficiency} This component shows the user’s current proficiency level on each skill for TOEIC exam, making AI’s analysis of diagnostic test result more transparent and explainable (Figure \ref{fig:page_B_proficiency}). The radar chart represents proficiency levels on a scale of 1 to 10 for the following five skills: listening, reading, grammar knowledge, grammar application and vocabulary. Each proficiency level is obtained by normalizing the average estimated correctness probabilities of potential questions for each skill. The red and white pentagons present the values for the five skills of the current user and averaged values of users in the target score zone, respectively. \begin{figure*} \centering \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_B_lectures.png} \caption{} \label{fig:page_B_lectures} \end{subfigure} \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_B_analysis.png} \caption{} \label{fig:page_B_analysis} \end{subfigure} \begin{subfigure}[ht]{0.33\columnwidth} \centering \includegraphics[width=1\columnwidth]{figures/page_B_curriculum.png} \caption{} \label{fig:page_B_curriculum} \end{subfigure} \caption{\emph{Recommended Lectures}, \emph{Analysis of Users Similar to You} and \emph{Adaptively offered curriculum} components in the page design B.} \end{figure*} \subsubsection{Recommended Lectures} This component helps the user identify their weaknesses and suggests lectures to complement (Figure \ref{fig:page_B_lectures}). Among the five skills in the \emph{Skill Proficiency} component, two skills with the lowest proficiency and their sub-skills are presented and two lectures on these skills are recommended. \subsubsection{Analysis of Users Similar to You} This component provides information of the change in average scores of \emph{Santa} users at the similar level to the current user, conveying the feeling that the specific score can be attained by using \emph{Santa} (Figure \ref{fig:page_B_analysis}). It shows how the scores of the \emph{Santa} users change by dividing them into top 20\%, median 60\% and bottom 20\%, and presents the estimated average score attained after studying with \emph{Santa} for 60 hours. This feature is obtained by finding \emph{Santa} users with the same estimated score as the current user and computing the estimated score every time they consume a learning item. \subsubsection{Adaptively Offered Curriculum} This component presents the learning path personalized to the user to achieve their learning objective (Figure \ref{fig:page_B_curriculum}). When the user changes the target date and target score by swiping, \emph{Santa} dynamically suggests the number of questions and lectures the user must study per day based on their current position. The amount of study the user needs to consume every day is computed by finding \emph{Santa} users whose initial state is similar to the current user and tracking how their learning progresses so that the user can achieve the target score on the target date. \begin{figure*} \centering \includegraphics[width=0.8\columnwidth]{figures/page_B_Santa_labs.pdf} \caption{\emph{Santa Labs} component in the page design B. When the user presses the flask button next to the \emph{Estimated Score} component, a window appears with an explanation of how the estimated scores are calculated.} \label{fig:page_B_Santa_labs} \end{figure*} \subsubsection{Santa Labs} When the user presses the flask button next to each component, a window pops up and provides an explanation of AI models used to compute the features of the component (Figure \ref{fig:page_B_Santa_labs}). For instance, when the user presses the flask button next to the \emph{Estimated Score} component, a window appears with an explanation about the Assessment Modeling \cite{choi2020assessment}, the \emph{Santa}'s score estimation modeling method. This component conveys information about the AI technology provided by \emph{Santa} to the user, giving them a feeling that the AI is actually analyzing them, increasing the credibility of the system. \subsection{Back-end AI Engine} The features in the components of each page design are computed by processing the output of \emph{Santa}’s AI engine, which takes the user's past learning activities and models individual users. Whenever the user consumes a learning item suggested by \emph{Santa}, the AI engine updates models of individual users and makes predictions on specific aspects of their ability. The predictions that the AI engine makes include the followings: response correctness, response timeliness, score, learning session dropout and engagement. The response correctness prediction is made by following the approaches introduced in \cite{lee2016machine} and \cite{choi2020towards}. \cite{lee2016machine} is the Collaborative Filtering (CF) based method which models users and questions as low-rank matrices. Each vector in the user matrix and question matrix represents latent traits of each user and latent concepts for each question, respectively. SAINT \cite{choi2020towards} is a deep learning based model that follows the Transformer \cite{vaswani2017attention} architecture. The deep self-attentive computations in SAINT allows to capture complex relations among exercises and responses. Since the CF-based model can quickly compute the probabilities of response correctness for the entire questions of all users and SAINT predicts the response correctness probability for each user with high accuracy, the two models are complementary to each other in real world applications where both accuracy and efficiency are important. Assessment Modeling (AM) \cite{choi2020assessment} is a pre-train/fine-tune approach to address the label-scarce educational problems, such as score estimation and review correctness prediction. Following the pre-train/fine-tune method proposed in AM, a deep bidirectional Transformer encoder \cite{devlin2018bert} based score estimation model is first pre-trained to predict response correctnesses and timelinesses of users conditioned on their past and future interactions, and then fine-tuned to predict scores of each user. The response timeliness and score are predicted from the pre-trained model and the fine-tuned model, respectively. The learning session dropout prediction is based on the method proposed in DAS \cite{lee2020deep}. DAS is a deep learning based dropout prediction model that follows the Transformer architecture. With the definition of session dropout in a mobile learning environment as an inactivity for 1 hour, DAS computes the probability that the user drops out from the current learning session whenever they consume each learning item. The engagement prediction is made by the Transformer encoder based model. The model is trained by taking the user’s learning activity record as an input and matching the payment status based on the assumption that the user who makes the payment is engaged a lot with the system. \section{Conclusions and Future Work} We have investigated the effects of AI-driven interface design for ITS. In particular, we hypothesized that diagnostic page design summarizing analytics for students' problem-solving process that makes better use of AI features would encourage student engagement. For this, we proposed several page designs that couple the interface with AI features in different levels and empirically verified their impacts on student engagement. We have conducted A/B tests on new students using an active mobile ITS \emph{Santa}. We considered conversion rate, Average Revenue Per User (ARPU), total profit and the average number of free questions a user consumed as factors measuring the degree of engagement. The A/B test results showed that the page designs that effectively expresses the AI features brought by back-end AI engine and thus better explain analysis of the user’s diagnostic test result promote all factors of engagement, concluding that AI-driven interface design improves student engagement. Avenues of future work include 1) updating a page summarizing the AI’s analysis on the user in the learning session after the diagnostic test. 2) finding more interface designs that can further enhance student engagement by making good use of, expressing and utilizing AI features. \section{Experimental Studies} \label{sec:exp} In this section, we provide supporting evidence that AI-driven interface design for ITS promotes student engagement by empirically verifying the followings through the real world application: 1) the impact of the radar chart in the page design A on user engagement, and 2) comparison of the page design A and B on user engagement. We conduct A/B tests on new incoming users of \emph{Santa}, with the users randomly assigned either group A or B. Both groups of users take the diagnostic test, and at the end, users in different groups are shown different diagnostic test analytics pages. Throughout the experiments, we consider the following four factors of engagement: conversion rate, Average Revenue Per User (ARPU), total profit and the average number of free questions a user consumed. Monetary profits are an essential factor for evaluating the users’ engagement since paying for a service means that the users are highly satisfied with the service and requires a strong determination of actively using the service. For users without the determination to make payment, the average number of free questions a user consumed after the diagnostic test is a significant measure of engagement since it represents their motivation to continue the current learning session. \subsection{Impact of Radar Chart in Page Design A on Student Engagement} From April 15th to 24th, we conducted an A/B test by randomly assigning two different diagnostic test analytics pages to the users: one without the radar chart in the page design A (1,391 users) and another one the page design A (1,486 users). Table \ref{tab:radar_chart} shows the overall results. We see that the page design A with the radar chart improves all factors of user engagement. With the radar chart, the conversion rate, ARPU, total profit and the average number of free questions a user consumed are increased by 22.68\%, 17.23\%, 25.13\% and 11.78\% respectively, concluding that a more AI-like interface design for ITS encourages student engagement. Figure \ref{fig:daily_payment_radar_chart} and Figure \ref{fig:daily_questions_radar_chart} show the comparison of the conversion rate and the average number of free questions a user consumed per day between the users of the A/B test, respectively. We observe that the users of the page design A with the radar chart made more payments and solved more free questions throughout the A/B test time period. \begin{table}[h] \caption{Impacts of the radar chart on user engagement.} \centering \begin{tabular}{ccc} \toprule & w/o radar chart & w/ radar chart \\ \hline Conversion rate (\%) & 5.25 & 6.26 \\ ARPU (\$) & 5.92 & 6.94 \\ Total profit (\$) & 8,236.01 & 10,305.58 \\ \# of free questions consumed & 14.77 & 16.51 \\ \bottomrule \end{tabular} \label{tab:radar_chart} \end{table} \begin{figure*}[h] \centering \includegraphics[width=0.7\columnwidth]{figures/daily_payment_radar_chart.pdf} \caption{Comparison of the conversion rate on every day between the users of the A/B test.} \label{fig:daily_payment_radar_chart} \end{figure*} \begin{figure*}[h] \centering \includegraphics[width=0.7\columnwidth]{figures/daily_questions_radar_chart.pdf} \caption{Comparison of the average number of free questions a user consumed on every day between the users of the A/B test.} \label{fig:daily_questions_radar_chart} \end{figure*} \subsection{Comparison of Page Design A and B on user engagement} The A/B test of the page design A and B was conducted from August 19th to September 11th by randomly allocating them to the users. 9,442 users were allocated to the page design A and 9,722 users were provided the page design B. The overall results are shown in Table \ref{tab:AB}. Compared to the page design A, the page design B is better at promoting all factors of user engagement by increasing 11.07\%, 10.29\%, 12.57\% and 7.19\% of the conversion rate, ARPU, total profit and the average number of free questions a user consumed, respectively. Note that although the page design with the radar chart in the previous subsection and the page design A are the same, there is a difference between the values of the engagement factors of page design with the radar chart in Table \ref{tab:radar_chart}, and those of the page design A in Table \ref{tab:AB}. The absolute value of each number can be changed by external factors, such as timing and the company's public relations strategy, and these external factors are not a problem as they apply to both A and B groups in the A/B test. The comparisons of the conversion rate and the average number of free questions a user consumed on every two days between the users assigned to the page design A and B are presented in Figure \ref{fig:daily_payment_design_AB} and Figure \ref{fig:daily_questions_design_AB}, respectively. We can observe in the figures that users experiencing the page design B made more payments and solved more free questions during the A/B test time period. Throughout the experiment, the results show that a more informative and explainable design of interface for ITS by making better use of AI features improves student engagement. \begin{table}[h] \caption{Impacts of the page design A and B on user engagement.} \centering \begin{tabular}{ccc} \toprule & Page design A & Page design B \\ \hline Conversion rate (\%) & 5.60 & 6.22 \\ ARPU (\$) & 5.54 & 6.11 \\ Total profit (\$) & 83,335.76 & 93,807.27 \\ \# of free questions consumed & 15.15 & 16.24 \\ \bottomrule \end{tabular} \label{tab:AB} \end{table} \begin{figure*}[h] \centering \includegraphics[width=0.7\columnwidth]{figures/daily_payment_design.pdf} \caption{Comparison of the conversion rate on every two days between the users of the A/B test.} \label{fig:daily_payment_design_AB} \end{figure*} \begin{figure*}[h] \centering \includegraphics[width=0.7\columnwidth]{figures/daily_questions_design.pdf} \caption{Comparison of the average number of free questions a user consumed on every two days between the users of the A/B test.} \label{fig:daily_questions_design_AB} \end{figure*} \section{Introduction} The recent COVID-19 pandemic has caused unprecedented impact all across the globe. With social distancing measures in place, many organizations have implemented virtual and remote services to prevent widespread infection of the disease and support the social needs of the public. Educational systems are no exception and have changed dramatically with the distinctive rise of online learning. Also, the demands for evaluation methods of learning outcomes that are safe, reliable and acceptable have led the educational environment to take a paradigm shift to formative assessment. An Intelligent Tutoring System (ITS), which provides pedagogical services in an automated manner, is a promising technique to overcome the challenges post COVID-19 educational environment has brought to us. However, despite the development and growing popularity of ITS, most of the studies in ITS research have mainly focused on diagnosing students' knowledge state and suggesting proper learning items, and less effort has been conducted to design the interface of ITS that promotes students' interest in learning, motivation and engagement by making better use of AI features. For example, Knowledge Tracing (KT), a task of modeling students' knowledge through their learning activities over time, is a long-standing problem in the field of Artificial Intelligence in Education (AIEd). From Bayesian Knowledge Tracing \cite{corbett1994knowledge,yudelson2013individualized} to Collaborative Filtering \cite{thai2010recommender,lee2016machine} and Deep Learning \cite{piech2015deep,zhang2017dynamic,choi2020towards,ghosh2020context}, various approaches have been proposed and KT is still being actively studied. Learning path construction is also an essential task that ITS performs, where learning items are suggested to maximize students' learning objectives. This task is commonly formulated as a reinforcement learning framework \cite{liu2019exploiting,huang2019exploring,bassen2020reinforcement,zhou2020improving} and is also an active research area in AIEd. On the other hand, little works have been done in the context of the user interface for ITS including intelligent authoring shell \cite{granic2000user}, affective interface \cite{lin2014usability,lin2014influence} and usability testing \cite{chughtai2015usability,koscianski2014design,roscoe2014writing}. Although they cover important aspects of ITS, the methods are outdated and their effectiveness is not reliable since the experiments were conducted on a small scale. Interface of ITS not fully supportive of making AI’s analysis transparent to students adversely affects their engagement. Accordingly, improving the interface of ITS is also closely related to explainable AI. Explaining what exactly makes AI models arrive at their predictions and making them transparent to users is an important issue \cite{gunning2017explainable,gunning2019darpa,dove2020monsters}, and have been actively studied in both human-computer interaction \cite{abdul2018trends,kizilcec2016much,stumpf2009interacting,wang2019designing} and machine learning \cite{samek2017explainable} communities. There are lots of works about the issue of explainability in many subfields of AI including computer vision \cite{norcliffe2018learning,fong2017interpretable,kim2017interpretable,zhang2018interpretable}, natural language processing \cite{lei2017interpretable,fyshe2015compositional,jiang2018interpretable,panigrahi2019word2sense} and speech processing \cite{ravanelli2018interpretable,korzekwa2019interpretable,sun2020fully,tan2015improving}. Explainability in AIEd is mainly studied in the direction of giving feedback that helps students identify their strengths and weaknesses. A method of combining item response theory with deep learning has been proposed, from which students' proficiency levels on specific knowledge concepts can be found \cite{cheng2019dirt,wang2019neural,yeung2019deep}. Also, \cite{barria2019explaining,choi2020choose} attempted to give students insight why the system recommends a specific learning material. In this paper, we explore AI-driven design for the interface of ITS describing diagnostic feedback for students' problem-solving process and investigate its impacts on their engagement. We propose several interface designs composed of different AI-powered components. Each page design couples the interface with AI features in different levels, providing different levels of information and explainability. We empirically evaluate the impacts of each design on student engagement through \emph{Santa}, an active mobile ITS. We consider conversion rate, Average Revenue Per User (ARPU), total profit, and the average number of free questions a student consumed as factors measuring the degree of engagement. Controlled A/B tests conducted on more than 20K students in the wild show that AI-driven interface design improves the factors of engagement by up to 25.13\%. \section{Related Works} \begin{comment} The work of this paper is related to the following two categories of research areas: UI for ITS and and explainability of AIEd. Explaining what exactly makes AI models arrive at their predictions and making them transparent to users is an important issue \cite{gunning2017explainable,gunning2019darpa,dove2020monsters}, and have been actively studied in both HCI \cite{abdul2018trends,kizilcec2016much,stumpf2009interacting,wang2019designing} and ML \cite{samek2017explainable} community. There are lots of works about the issue of explainability in many subfields of AI including computer vision \cite{norcliffe2018learning,fong2017interpretable,kim2017interpretable,zhang2018interpretable}, natural language processing \cite{lei2017interpretable,fyshe2015compositional,jiang2018interpretable,panigrahi2019word2sense} and speech processing \cite{ravanelli2018interpretable,korzekwa2019interpretable,sun2020fully,tan2015improving}. In this section, we narrow down the scope and describe how the AIEd researchers have addressed the issue. \end{comment} \subsection{Design of UI for ITS} Although the development of ITS has become an active area of research in recent years, most of the studies have mainly focused on learning science, cognitive psychology and artificial intelligence, resulting in little works done in the context of UI. \cite{granic2000user} describes the UI issue of an intelligent authoring shell, which is an ITS generator. Through experiences in the usage of TEx-Sys, an authoring shell proposed in the paper, the authors discusses the importance of a well designed UI that brings system functionality to users. \cite{glavinic2001interacting} considers applying multiple views to UI for ITSs. The paper substantiates the usage of multiple perspectives on the domain knowledge structure of an ITS by the implementation of MUVIES, a multiple views UI for ITS. Understanding students' emotional states has become increasingly important for motivating their learning. Several works \cite{lin2014influence,lin2014usability} incorporate affective interface in ITS to monitor and correct the students' states of emotion during learning. \cite{lin2014influence} studies the usage affective ITS in Accounting remedial instruction. Virtual agents in the system analyze, behave and give feedback appropriately to students' emotions to motivate their learning. \cite{lin2014usability} proposes ATSDAs, an affective ITS for digital arts. ATSDAs analyzes textual input of a student to identify emotion and learning status of them. A visual agent in the system adapts to the student, provides text feedback based on the inferred results and thereby increases their learning interest and motivation. The performance of a software can be measured by its usability, a quality that quantifies ease of use. Whether applying usability testing and usability principles to the design of UI can improve the performance of ITS is an open question \cite{chughtai2015usability}. \cite{koscianski2014design} discusses the importance of UI design, usability and software requirements and suggests employing heuristics from software engineering and learning science domains in the development process of ITS. An example of applying basic usability techniques to the development and testing of ITS is presented in \cite{roscoe2014writing}. The paper introduces Writing Pal, an ITS for helping to improve students’ writing proficiency. The design of Writing Pal includes many usability engineering methods, such as internal usability testing, focus groups and usability experiments. \subsection{Explainability in AIEd} Providing an explainable feedback which can identify strengths and weaknesses of a student is a fundamental task in many educational applications \cite{conati2018ai}. DIRT \cite{cheng2019dirt} and NeuralCDM \cite{wang2019neural} propose methods to enhance explainability of educational systems through a cognitive diagnosis modeling, which aims to discover student’s proficiency levels on specific knowledge concepts. DIRT incorporates neural networks to compute parameters of Item Response Theory (IRT) model. With the great feature representation learning power of neural networks, DIRT could learn complex relations between students and exercises, and give explainable diagnosis results. A similar approach is taken in NeuralCDM. However, the diagnosis model of NeuralCDM is an extended version of IRT with monotonicity assumption imposed on consecutive fully-connected neural network layers before the final output. Deep-IRT \cite{yeung2019deep} is a synthesis of IRT and DKVMN \cite{zhang2017dynamic}, a memory-augmented neural networks based knowledge tracing model. Deep-IRT leverages intermediate computations of DKVMN to estimate the item difficulty level and the student ability parameters of IRT model. EKT, proposed in \cite{huang2019ekt}, is a bidirectional LSTM based knowledge tracing model. EKT explains the change of knowledge mastery levels of a student by modeling evolution of their knowledge state on multiple concepts over time. Also, equipped with the attention mechanism, EKT quantifies the relative importance of each exercise for the mastery of the student’s multiple knowledge concepts. As pointed in \cite{manouselis2012recommender}, explainability also poses challenges to educational recommender systems. \cite{barria2019explaining} addresses this issue by providing a visual explanation interface composed of concepts’ mastery bar chart, recommendation gauge and textual explanation. When a certain learning item is recommended, the concepts’ mastery bar chart shows concept-level knowledge of a student, the recommendation gauge represents suitability of the item and the textual explanation describes the recommendation rule why the item is suggested. Rocket, a tinder-like UI introduced in \cite{choi2020choose}, also provides explainability in learning contents recommendation. When an ITS proposes a learning material to a user, Rocket shows a polygonal visual summary of AI-extracted features, such as the probability of the user correctly answering the question being presented and expected score gain when the user correctly answers the question, which gives the user insight into why the system recommends the learning material. Based on the AI-extracted features, the user can decide whether to consume the suggested learning material or not through swiping or tapping action. \section{Santa: A Self-Study Solution Equipped with an AI Tutor} \begin{figure*} \centering \includegraphics[width=1\columnwidth]{figures/Santa_flow.pdf} \caption{The flow of a user entering and interacting with \emph{Santa}} \label{fig:santa_flow} \end{figure*} \emph{Santa}\footnote{\url{https://aitutorsanta.com}} is a multi-platform AI tutoring service with more than a million users in South Korea available through Android, iOS and Web that exclusively focuses on the Test of English for International Communication (TOEIC) standardized examination. The test consists of two timed sections named Listening Comprehension (LC) and Reading Comprehension (RC) with a total of 100 questions, and 4 or 3 parts respectively. The final test score ranges from 10 to 990 in steps of 5 points. Santa helps users prepare the test by diagnosing their current state and dynamically suggesting learning items appropriate for their condition. Once a user solves each question, \emph{Santa} provides educational feedback to their responses including explanation, lecture or another question. The flow of a user entering and using the service is described in Figure \ref{fig:santa_flow}. When a new user first opens \emph{Santa}, they are greeted by a diagnostic test (1). The diagnostic test consists of seven to eleven questions resembling the questions that appear on the TOEIC exam (2). As the user progresses through the diagnostic test, \emph{Santa} records the user's activity and feeds it to a back-end AI engine that models the individual user. At the end of the diagnostic test, the user is presented with a diagnostic page detailing the analytics of the user’s problem-solving process in the diagnostic test (3). After that, the user may choose to continue their study by solving practice questions (4).
{'timestamp': '2020-09-22T02:00:08', 'yymm': '2009', 'arxiv_id': '2009.08976', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08976'}
arxiv
\section{Challenges and Issues}\label{sec:challenges} The central concept in the VR literature is to define a more advanced form of user-computer interaction in real-time using synthetic three-dimensional multisensory devices \cite{Burdea94, LaValle:2019}. Objects can be presented, providing a sense that they are not the same as the user's perception when observing them in a limited area, such as a monitor screen. VR can be classified according to the user's presence, as immersive and non-immersive. It is said to be immersive when the user has the sensation of being present within the virtual world using sensory devices (stereoscopic glasses or helmets with motion trackers) that capture their movements and behavior. Moreover, it is considered non-immersive when the user is partially transported to the virtual world via a monitor or projector \cite{Tori06}. \begin{figure*} \centering \includegraphics[scale = 0.7]{vr_architecture.pdf} \caption{General VR application architecture (Source: own construction, based on \protect\cite{Capilla:2004})} \label{fig:vr_arch} \end{figure*} According to Machado et al. \cite{machado_2003} and LaValle \cite{LaValle:2019}, immersion, and interactivity correspond to how the user interacts with the virtual environment, using devices that allow the manipulation of virtual objects. Several graphical libraries have emerged to help develop applications that reproduce requirements in a virtual environment; these libraries act as an abstraction layer providing information about the device's position or orientation, without the application knowing in which device the information is processed. Despite the benefits of adopting VR for the development of applications in several areas, this poses new challenges for software quality assurance activities. For example, software developed for the context of VR has unique software structures, which may represent new sources of faults for the programs developed \cite{Takala:2017}. These new challenges have motivated the development of some approaches that aim to contribute to the quality assurance process of software in the context of VR. Automating software testing activities is often a complicated and challenging process. The main tasks of this activity include organizing, executing, registering the execution of the test cases, and verifying the result of their execution. In order to address these tasks, in the context of VR, some key points discussed in the next subsections should be understood. \subsection{What should be tested?}\label{subsec:what_test} Virtual reality systems use individual hardware devices to allow the interaction with the user and the system. The work of graphics engines is not the primary concern for VR application developers. Defining scene graphs for organizing 3D objects in a VR world, managing virtual users, controlling sensors for detecting events such as object collision and processing events for reacting to user inputs are some of the typical elements of VR systems that the developers should be concerned about \cite{Zhao:2009}. According to Runeson \cite{Runeson:2006}, unit testing aims to test the smallest units that make up the system, thus ensuring the proper functioning of elements and easy-to-find programming faults, incorrect or poorly implemented algorithms, incorrect data structures, limiting the internal logic within the limits of the unit. Figure \ref{fig:vr_arch} presents a general architecture of VR applications, as we can observe, VR applications differ from general programs by handling specific devices, and data structures used to represent the objects in a three-dimensional scene. Beyond represent various aspects of the real or imaginary world, such as geometric descriptions, appearance, transformations, behaviors, cameras, and lighting. Each of the properties above is created, aiming to represent objects present in a virtual environment, thus emerging new challenges related to how to test them. By observing the organization of 3D object elements and assets in scene graphs, it seems that it needs a higher-level type of test. In general, because they are independent, they do not have an architecture correlation of the source code. Therefore, integration testing tends to be a more appropriate approach to be used. In integration testing, the main aim is to verify the communication between the units that make up the system. \subsection{What does ``adequate testing'' mean?} The solution to define this question: \textit{``What does adequate testing mean?"} is to apply test criteria, which consists of a set of rules for dividing and evaluating the valid input domain for the program being tested. A test criterion defines elements of a program that must be exercised during its execution, thereby guiding the tester in the process of designing the test cases for the system. A test requirement may be, for example, a software-specific execution path, a functionality obtained through specification, a mutation-based approach, etc \cite{Bertolino:2003}. As pointed out in the previous question, due to the different structures existing in VR applications, it is difficult to define which aspects of a VR application should be considered when designing a test routine for VR applications. For example, the Figure \ref{fig:scene_render_ex} shows that for a single frame existing in a 3D scene, there are different layers that have different aspects that can be taken into account when testing the application. Corrêa et al. \cite{Santos:2013} presented a set of studies that deal with the application of software testing techniques to programs in the VR context, showing that there is an interest in the literature on the subject, however, there is still no concept regarding systematized practices for the activity. \begin{figure}[ht] \centering \includegraphics[scale = .43]{scene_render_example.pdf} \caption{Example of scene rendering process (Source: own construction, based on \protect\cite{Adrian:2016})} \label{fig:scene_render_ex} \end{figure} Due to the lack of defined requirements, it is not easy to identify test adequacy criteria for VR systems. How can we decide that testing is enough? This question needs to be adapted to the context. \subsection{What is a failure in a VR software?} In the context of VR applications, the testing activity hinges on the difficulty of systematizing how the behavior of a test case can be measured. This difficulty is described in the literature as ``test oracle problems" and it appears in cases where traditional means of measuring the execution of a test case are impractical or are of little use in judging the correction of outputs generated from the input domain data \cite{Rapps:1985, Barr:2015}. Test oracles deal with a primary issue in software testing activities - deciding on program correctness based on predetermined test data. In general, the test oracle accesses a data set needed to evaluate the correctness of the test output. This data set is taken from the specification of the program under testing and should contain sufficient information to support the final decision of the Oracle \cite{Oliveira14}. It is possible to explore a wide range of faults in the context of VR software. It is possible to verify the strictness of specification based on scene graphs concepts, in addition to specific features related to the virtual environment, it is also possible to verify the behavior of objects and the actions performed by multiple devices. As can be seen, in addition to traditional source code routines, several characteristics need to be taken into account when testing and the definition of what can be considered a failure is an important step for each of the described aspects above can be analyzed correctly during the testing activity. \subsection{Can we reuse something?} General tools such as capturing and replaying can be used, but they offer a shallow level of abstraction. Thus, any small change to the system will result in the fact that the tests should be redone \cite{Leotta:2013}. Therefore, using capture and replay tools cannot be used when the system is in development. From a unit test point of view, we can still reuse a traditional approach in which we can quickly gauge the expected output to a method execution, ensuring that the smallest units of the VR system have been sufficiently tested against their specifications. Regarding integration testing which is expected to handle new kinds of elements (3D objects, assets, behaviors, etc.) the literature review shows that we still need better-systematized practices for this activity \cite{Santos:2013}. \subsection{What is done nowadays?} Almost all 3D applications require some common features. Therefore, developers tend to use platforms that provide these features out-of-the box. Using game engines is one of the most popular techniques among developers due to the fact it helps produce the systems, besides speeding up the development process. Recently popular game engines, such as \textit{Unity3D}\footnote{\url{https://docs.unity3d.com/Manual/testing-editortestsrunner.html}} and \textit{Unreal Engine}\footnote{\url{https://docs.unrealengine.com/latest/INT/Programming/Automation}}, released their own set of testing tools, which allows developers to produce automated testing during the development phase of the system which can substantially increase the stability of the product developed. Despite the existence of tools, it still does not provide observable test criteria, perhaps due to the lack of studies that propose, experiment and validate effectively applicable approaches, which can be additionally repeatable, documented and do not rely only on the tester’s creativity. \section{Conclusion and Future Work}\label{sec:conclusion} This paper discusses the main challenges related to using software testing practice in the VR domain. Some of the critical issues related to the quality of these systems were pointed out and possible solutions were also discussed that could be used and adapted to deal with such issues. We discussed whether or not there is a real need to test VR systems. To better understand this, a comprehensive study was conducted, guided by 3 research questions, whose objective was: to understand the state of the practice of software testing in the context of VR programs ($RQ_1$), to measure metrics and quality attributes in VR software ($RQ_2$), and finally to evaluate fault proneness in the collection of the software analyzed ($RQ_3$). In order to answer the raised questions, a collection of 119 VR projects, available in open source projects and manually analyzed, was cataloged to understand the state of the practice concerning the application of software testing techniques. Regarding the application of software testing techniques ($RQ_1$), it was observed that out of all the projects, only 6 of them had some test cases in their project. Given the results pointed out by $RQ_1$, we decided to evaluate how the negligence of the practice of software testing can be detrimental to a software project, and it was decided to evaluate the distribution of code smells among the analyzed projects. Smells related to architecture, design, and implementation were analyzed. It can be concluded that there is a high incidence of smells in the projects analyzed, especially regarding implementation smells. We discussed the most common smells for each of the categories and how they can discourage the practice of software testing, and also how they can be avoided if a software testing activity is appropriately conducted. Finally, considering the results of $RQ_2$, it was decided to investigate how the lack of good practices and the presence of code smells can impact the quality of the source code produced. To do so, an approach that evaluates code metrics was used to point out classes that are fault-prone ($RQ_3$). The study pointed out that about 12\% of the analyzed VR classes have such characteristics, revealing a significant risk to the success of the projects. The distribution of these classes was also evaluated when observed concerning the size of the projects analyzed. It was observed that the larger a project becomes, there is a higher incidence of fault-prone classes, which may be an indication that neglecting test practices in larger projects becomes even more riskier. We believe that the results reported in this paper will contribute to raising the awareness of the software testing and virtual reality community about the needs of software testing approaches for VR developers. As software testing phase, also makes up one of the development phases, it is necessary to understand the point of view of stakeholders involved in the process, allowing these groups narrow what they deem important, thus making it possible to prioritize verification concerning failures that should not manifest in VR applications. Observing such aspects, it is possible to guide the development of a project using a specific testing approach for the VR domain. So, in future works, we intend to survey what types of faults in VR applications contribute to a negative experience. The goal of this study is to obtain a view of the interest groups (for example, which types of failures are most critical, which are less relevant, how much each affects the quality of the final product, etc.), in addition to investigating the knowledge of the groups of interest regarding specific types of failures in VR applications. Understanding the intends of stakeholders we expect to propose a fault taxonomy to the context of VR programs. It is believed that having such taxonomy, it would be possible to encourage the development of specific software testing techniques and criteria to the context of VR programs, thus spreading the practice of software testing in order to mitigate possible problems and move towards software projects that best meet software quality requirements. \section{Results and Discussion}\label{sec:discussion} In this section, we address the research questions and further discuss the results obtained from the analysis and our observations with the empirical study. \subsection{How is VR software tested?} Existing software testing techniques seek to establish rules to define test case sets that exercise the testing requirements needed to eliminate software faults when they exist. Testing techniques and criteria are of paramount importance in selecting test cases because the tester can create more effective test cases, and thus reduce the number of test cases, ensuring that specific pieces of software are exercised by the tests. Testing techniques differ from one another in the source of information used to create the test requirements. Regarding the first research question ($\mathbf{RQ_1}$) of the study, which aims to understand the question: \textit{``How does testing happen in open-source VR software systems?"}, the 119 projects were manually evaluated and it was found that only 6 VR projects (\textit{Bowlmaster - 53 tests, CameraControls - 60 tests, GraduationGame - 15 tests, MiRepositorio\_VRPAD - 11 tests, space\_concept - 11 tests, UnityBenchmarkSamples - 4 tests}) are concerned with the software testing practices, including a total of 154 unit test cases, to evaluate the projects' functionalities. Despite the existence of unit testing, we were unable to calculate information regarding testing criteria, such as code coverage, since \textit{Unity} does not provide an out-of-the box solution to code coverage (till the present time) and \textit{Unity} uses its own fork of \textit{Mono} \cite{Mono}, which makes it impractical to use other C\# coverage tools \cite{Haas:2014}. Based on the information collected, it can be observed that from the 119 analyzed projects, only 6 (5.04\%) have some software testing activity, and even the projects that have test cases, do not present many tests that can ensure that the main functionalities of the applications were adequately tested. Another interesting aspect observed when analyzing the 6 projects that have test cases is the fact that the \textit{Bowlmaster} project is part of a popular course, with more than 334,000 students enrolled \footnote{\url{https://github.com/CompleteUnityDeveloper/08-Bowlmaster-Original}}, which aims to teach VR application development practices. This demonstrates that there is a concern on the part of educators regarding the awareness that testing activity is a determining factor in the software development process and it is expected that students are capable of apply concepts related to testing practice software in their future projects. Concerning $RQ_1$ we came to the conclusion that there is not yet consensus regarding the application of software testing practices for VR applications and this motivated us to explore the next research questions. These results are in agreement with the most recent papers in the literature. Karre et al. \cite{Karre:2019} conducted an empirical study of VR practitioners to learn the current practices and challenges faced in industry. The software testing related results points out to the absence of adequate tools, as well as uncertainty about how to test the VR app apart from conducting a standard field evaluation. As a consequence, this lack of usability evaluation methods and automated testing tools tend to cost a lot of time to release a VR product. One possible explanation is due to the challenges of systematizing how the behavior of a test case can be measured in the context of VR programs. This difficulty is described in the literature as a ``test oracle problem" and arises in cases where traditional means of gauging the execution of a test case are impractical or are of little use in judging the correctness of outputs generated from input domain data \cite{Rapps:1985, Barr:2015}. Test oracles deal with a primary issue in software testing activities - deciding on program correctness based on predetermined test data. In general, the test oracle accesses a data set needed to evaluate the correctness of the test output. This data set is taken from the specification of the program under testing and should contain sufficient information to support the final decision of the Oracle \cite{Oliveira14}. It should be emphasized that building a project with good test cases is not an easy task. Testing requires discipline, concentration, and extra effort \cite{Kasurinen:2010}. As a reward, the code presents a set of characteristics such as cleanliness, easy-to-maintain, loosely coupled, and reusable APIs. Besides the fact that testable code is easier to understand, maintain and extend. In order to understand the risks and advantages of these characteristics and to accurately answer $RQ_2$ and $RQ_3$, in the next sessions, we compare the difference between the VR projects and Non-VR projects concerning code smells and fault-proneness distribution. \subsection{Distribution of Code smell} Observing the lack of software testing practice in all the other projects, we decided to investigate how this practice is reflected within the projects. To do so, we decided to measure the incidence of code smells \cite{Fowler:2018} within the projects investigated. This leads us to the second research question ($\mathbf{RQ_2}$) presented: \textit{``What are the distribution of architecture, implementation, and design smells in VR projects?"}. In general, the presence of code smells in software projects indicates the presence of quality problems. For instance, one of the most well-known code smell, God Class, is defined as a class that knows or does too much in the software system. God Class is a strong indicator of possible problems because this component is aggregating functionality that should be distributed among several others components, therefore increasing the risk of software faults \cite{Hall:2014}. Such problems directly impact features such as maintainability and contribute to make it difficult for software to evolve. To perform the evaluation discussed in this section we started from an assumption that projects that do not have test cases in their composition tend to have a lower code quality opposed to projects that have been tested, considering developers probably may not have observed aspects that would be capable of triggering unexpected behavior in the application, besides the fact the smaller the number of bugs in the system, the higher the quality related to a given project. In order to better understand what is related to the lack of tests, we compared the results obtained in the VR projects with the results obtained in Non-VR applications, which have well-defined test cases within the projects. To better understand $\mathbf{RQ_2}$, we identified three different types of code smells in the projects: \begin{itemize} \item \textbf{Architecture smells}: focus on identifying points of interest for possible structural problems that can negatively contribute and hamper activities such as debugging and refactoring, as well as increasing the cost for fault correction and refactoring, due to the characteristic of increasing the complexity of the software, when present \cite{Mo:2015}. \item \textbf{Implementation smells}: code smells or implementation smells were first introduced by Fowler \cite{Fowler:2018} and seek to establish a concept to classify shortcomings in object-oriented design principles. This class of smells covers principles such as data abstraction, encapsulation, modularity, hierarchy, etc. \item \textbf{Design smells}: are specific types of structures that may indicate a violation of a fundamental principle, which can impact aspects of design quality \cite{Suryanarayana:2014}. \end{itemize} In order to calculate the distribution of the code smells previously described within the projects, we use the \textit{Designite} tool \cite{Sharma:2016}. The smells were classified according to the number of occurrences in the analyzed classes and percentage distribution. The data is presented in Tables \ref{tab:architecture_smells}, \ref{tab:implementation_smells} and \ref{tab:design_smells}. It is worth mentioning that test case classes were not taken into account for this smell classification, once our initial target was to measure the quality aspects of the source code classes. Besides that, smells in software test codes require a whole different classification approach \cite{Tufano:2016}. \subsubsection{Architecture smells results} It can be observed that in Table \ref{tab:architecture_smells}, among the VR projects, there is a low incidence of architecture smells, with only three types (ACD, AFC, and AGC) presenting a percentage of occurrence between 0.93 \% and 1.70 \%. Observing the Non-VR projects, it can be observed that this category of smells had a lower incidence compared to VR projects. The AUD, AGC and AFC smells showed the highest occurrence rates, with percentages between 0.26\% and 0.57\%. VR project behavior can be justified due to the fact that within the \textit{Unity} platform, although an object-oriented language (C\#) is mostly used, the development model is considered a component-based programming approach. This approach focuses on the separation of concerns regarding the features to be developed in the system. \begin{table}[ht] \scalefont{0.73} \centering \caption{Description of the detected architecture smells and their distribution} \begin{tabular}{l|l|r|r|r|r} \hline \textbf{ID} & \textbf{Smell} & \multicolumn{2}{c|}{\textbf{VR}} & \multicolumn{2}{c}{\textbf{Non-VR tested}} \\ \hline AAI & Ambiguous Interface & 29 & 0.13\% & 1 & 0.02\% \\ ACD & Cyclic Dependency & 212 & 0.99\% & 6 & 0.14\% \\ ADS & Dense Structure & 3 & 0.01\% & 2 & 0.05\% \\ AFC & Feature Concentration & 366 & 1.70\% & 24 & 0.57\% \\ AGC & God Component & 201 & 0.93\% & 12 & 0.29\% \\ ASF & Scattered Functionality & 84 & 0.39\% & 8 & 0.19\% \\ AUD & Unstable Dependency & 78 & 0.36\% & 11 & 0.26\% \\ \hline Std Dev & \multicolumn{1}{c|}{\graycell} & 118.34 & \multicolumn{1}{c|}{\graycell} & 7.17 & \multicolumn{1}{c}{\graycell} \\ \hline Average & \multicolumn{1}{c|}{\graycell} & 139.0 & \multicolumn{1}{c|}{\graycell} & 9.14 & \multicolumn{1}{c}{\graycell} \\ \hline \end{tabular} \label{tab:architecture_smells} \end{table} Among the main advantages of a component-based programming approach, we can point out the high reuse capacity of the developed components due to the low coupling characteristics of the components that make up the systems. Despite Non-VR applications presenting lower rates of architecture smells, it mainly shows a higher incidence of smell AFC. This smell occurs when a component performs more than one architectural concern/feature. This can be explained due to the programming model adopted. A large part of Non-VR projects corresponds to web applications, which typically use a Model-View-Controller (MVC) standard for application development. As shown by Aniche et al. \cite{Aniche:2018}, systems that adopt such architecture can be affected by types of poor practices that lead to the apparition of such a smell. From a software testing point of view, the lower rate of architecture smells can be considered as a decisive successful factor, since the low dependence between modules is a characteristic that facilitates the application of unit tests \cite{Aniche:2013}. In general, when it is necessary to communicate with other units of code, sometimes \textit{stubs} or \textit{mock} objects are used to represent this communication. A huge benefit of this approach is that by lower coupling the system it is possible to reproduce complex scenarios more easily. Despite the advantages, it is important to keep in mind that there are some threats related to the use of a component-based approach in the context of integration testing, which as discussed in subsection \ref{subsec:what_test} must be one of the characteristics prioritized in the context of testing VR applications. The main problems are related to the use of components produced by third parties since in general they work as a black box and it is necessary to trust their correct functionality. An example of this model is the components asset store available in the Unity platform\footnote{\url{https://assetstore.unity.com/}}. In order to better understand the presented results, regarding each of the classes of smells analyzed, we verified if there is, in fact, a statistical difference between the presence of smells between groups of classes that were not tested and groups of classes that were tested during its development process. Therefore, due to the low number of smell types for each category (architecture, design and implementation), and since we can not guarantee that the data collected departs from a normal distribution, we applied the Mann-Whitney test \cite{Fay:2010} to verify whether there is a statistical difference between the presence of smells for each category of smells evaluated. The null hypothesis ($H_0$) of the Mann-Whitney test indicates that \textit{``The distribution of the variable in question is identical (in the population) in the two groups"}, that is, there is no difference in the presence of smells between classes that have not been tested and classes that have been tested and the alternative hypothesis ($H_1$) indicates that \textit{``The distributions in the two groups are not the same"}, therefore, there is a statistical difference between the incidence of smells for classes that were not tested against classes that were tested. Considering the value of alpha = 0.05, which comprises the complement of the margin of a confidence level of 95\%, for the architecture smells, $H_0$ with a p-value = 0.00760 could be rejected. Thus, it indicates that there is a statistical difference between the presence of smells when comparing architecture smells in classes that were not tested against classes that were tested. Using a descriptive analysis, obtained by analyzing the number of occurrences of each type of smells, it could be observed that classes that were not tested tend to present a higher rate of architecture smells in relation to classes that were tested. \subsubsection{Implementation smells results} It can be observed that, different from the architecture smells, in Table \ref{tab:implementation_smells}, we can identify a high rate of implementation smells in the VR projects. We highlight ILI, ILS, and IMN, which had a percentage of occurrence of 31.81\%, 55.55\%, and 117.46\%, respectively. Although it does not pose a direct risk to the source code produced, smell ILI may be an indicator that something can be revised/refactored. A very long identifier may be an indication that there is a need for too much text to distinguish/identify variables and in some instances, this may indicate that the programmer may not be using the most suitable data structure to represent it. \begin{table}[ht] \scalefont{0.69} \centering \caption{Description of the detected implementation smells and their distribution} \begin{tabular}{l|l|r|r|r|r} \hline \textbf{ID} & \textbf{Smell} & \multicolumn{2}{c|}{\textbf{VR}} & \multicolumn{2}{c}{\textbf{Non-VR}} \\ \hline ICM & Complex Method & 1,812 & 8.42\% & 9 & 0.22\% \\ ICC & Complex Conditional & 684 & 3.18\% & 14 & 0.33\% \\ IDC & Duplicate Code & 9 & 0.04\% & 1 & 0.02\% \\ IECB & Empty Catch Block & 150 & 0.70\% & 5 & 0.12\% \\ ILM & Long Method & 583 & 2.71\% & 9 & 0.22\% \\ ILPL & Long Parameter List & 2,117 & 9.84\% & 13 & 0.31\% \\ ILI & Long Identifier & 6,841 & 31.81\% & 12 & 0.29\% \\ ILS & Long Statement & 11,947 & 55.55\% & 40 & 0.96\% \\ IMN & Magic Number & 25,264 & 117.46\% & 36 & 0.86\% \\ IMD & Missing Default & 931 & 4.33\% & 17 & 0.65\% \\ IVMCC & Virtual M. C. C.** & 35 & 0.16\% & 5 & 0.12\% \\ \hline Std Dev & \multicolumn{1}{c|}{\graycell} & 7,425.91 & \multicolumn{1}{c|}{\graycell} & 11.87 & \multicolumn{1}{c}{\graycell} \\ \hline Average & \multicolumn{1}{c|}{\graycell} & 4,579.36 & \multicolumn{1}{c|}{\graycell} & 14.63 & \multicolumn{1}{c}{\graycell} \\ \hline \multicolumn{6}{l}{**Virtual Method Call from Constructor} \\ \hline \end{tabular} \label{tab:implementation_smells} \end{table} ILS occurs when there is an excessively long statement. Long declarations tend to make it difficult to manage the code and are consequently villains if observed from the practice of software testing. Very long code snippets tend to be harder to test because they often become too complex when compared to smaller snippets that are managed more efficiently. Finally, IMN occurs when an unexplained number is used in an expression. In general, magic numbers are unique values that have some symbolic meaning. Good programming practices indicate that in these cases, such numbers should be declared as constants to facilitate the reading of the source code, as well as to standardize its use. Non-VR projects again presented a lower occurrence rate. The most frequent smells were ILS, IMN and IMD which achieved, respectively, percentages of 0.96\%, 0.85\%, and 0.65\%. The occurrence of this type of smells is connected with the lack of guidelines for standardization of code as well as the lack of code refactoring practices. Usually, numbers have a meaning, therefore it is recommended that it should be assigned variables to make the code more readable and self-explaining. The names of the variables should at least reflect what the variable means, not necessarily its value. Basic guides guide to the test to give a more appropriate context and explanation of whatever numbers are present within the test. The more sloppily the tests are written, the worse the actual code will be and could become a door to possible faults, details about that possibility will be addressed in the next section. From the standpoint of software testing, opting to use of constants instead of magic numbers can ensure that once the value of the constant has been tested, there is no risk that the value of the constant is erroneously declared in the future. We also applied the Mann-Whitney test to verify whether there is a statistical difference between the presence of implementation smells in groups of classes that were not tested when compared to the classes that were tested. Adopting a confidence interval of 95\%, the test presented the p-value = 0.00040, which rejects the null hypothesis of the test and confirms the data presented in Table \ref{tab:implementation_smells}, proving that classes that were tested tend to present a lower rate of implementation smells. \begin{table}[ht] \scalefont{0.65} \centering \caption{Description of the detected design smells and their distribution} \begin{tabular}{l|l|r|r|r|r} \hline \textbf{ID} & \textbf{Smell} & \multicolumn{2}{c|}{\textbf{VR}} & \multicolumn{2}{c}{\textbf{Non-VR}} \\ \hline DBH & Broken Hierarchy & 245 & 1.14\% & 8 & 0.19\% \\ DBM & Broken Modularization & 991 & 4.61\% & 46 & 1.10\% \\ DCM & Cyclically-dependent M. & 3,149 & 14.64\% & 45 & 1.08\% \\ DCH & Cyclic Hierarchy & 6 & 0.03\% & 4 & 0.10\% \\ DDH & Deep Hierarchy & 0 & 0.00\% & 1 & 0.02\% \\ DDE & Deficient Encapsulation & 8,101 & 37.67\% & 13 & 0.31\% \\ DDA & Duplicate Abstraction & 2,469 & 11.48\% & 11 & 0.26\% \\ DHM & Hub-like Modularization & 4 & 0.02\% & 16 & 0.38\% \\ DIA & Imperative Abstraction & 627 & 2.92\% & 9 & 0.22\% \\ DIM & Insufficient Modularization & 1,171 & 5.44\% & 44 & 1.05\% \\ DMH & Missing Hierarchy & 18 & 0.08\% & 2 & 0.05\% \\ DMA & Multifaceted Abstraction & 209 & 0.97\% & 2 & 0.05\% \\ DMH & Multipath Hierarchy & 1 & 0.00\% & 2 & 0.05\% \\ DRH & Rebellious Hierarchy & 389 & 1.81\% & 9 & 0.22\% \\ DUE & Unexploited Encapsulation & 15 & 0.07\% & 2 & 0.05\% \\ DUH & Unfactored Hierarchy & 483 & 2.25\% & 7 & 0.17\% \\ DUA & Unnecessary Abstraction & 3,741 & 17.39\% & 17 & 0.41\% \\ DTA & Unutilized Abstraction & 6,987 & 32.49\% & 23 & 0.55\% \\ DWH & Wide Hierarchy & 64 & 0.30\% & 5 & 0.12\% \\ \hline Std Dev & \multicolumn{1}{c|}{\graycell} & 2,344.41 & \multicolumn{1}{c|}{\graycell} & 14.59 & \multicolumn{1}{c}{\graycell} \\ \hline Average & \multicolumn{1}{c|}{\graycell} & 1,508.94 & \multicolumn{1}{c|}{\graycell} & 14.00 & \multicolumn{1}{c}{\graycell} \\ \hline \end{tabular} \label{tab:design_smells} \end{table} \subsubsection{Design smells results} Finally, we have the design smells which seek to identify breaches of design principles. It can be concluded from Table \ref{tab:design_smells} it is possible to conclude that this class of smells was the one that presented the highest degree of incidence in the VR projects. DUA, DTA and DDE smells were the ones with the highest percentage of occurrence with 17.39\%, 32.49\%, and 37.67\% respectively. The DUA smell deals with the practice of unnecessary abstractions and is identified when an abstraction has more than one responsibility attributed to it. This smell tends to occur when there is an application of procedural programming features in the context of object-oriented programming languages \cite{Suryanarayana:2014}. From the standpoint of VR applications that adopt component-based programming, the appearance of this smell can be explained by the fact that the programming approach focuses on creating interchangeable code modules that work almost independently, not requiring that to be familiar with their inner workings in order to use them. Unnecessary design abstractions increase their complexity needless and affect the comprehensibility of the overall design. From a software testing point of view, this bad practice tends to hamper test practices DTA occurs when an abstraction is left unused, is not being used directly, or because it is not reachable in the source code. This smell correlates with DUA since unnecessary abstractions tend not to be used. Another impact factor for the appearance of this smell is linked to possible code maintenance/refactoring activities, which tend to leave traces of code that are no longer needed. From the standpoint of software testing, the existence of a test base that can be used as a regression test tends to facilitate the localization of source code that is no longer necessary, causing the occurrence of this smell to be reduced. From a tester's point of view, if there is a code that is not being used in the project, it does not need to be tested. Therefore, identifying these snippets of code can lead to more efficient testing activities. Finally, smell DDE, which identifies cases of poor encapsulation, had the highest occurrence rate in this class of smells. This smell occurs when the declaration of attribute visibility of a class is more permissive than necessary. For example, when the attributes of a class are unnecessary declared as public. From the standpoint of software testing, separation of interests allows implementation details to be hidden. If an abstraction exposes implementation details unnecessarily, it leads to undesirable coupling in the source code. This will have an impact on the testing activity because checking units that have a high degree of coupling becomes a more challenging task due to the need for more complex mocks and stubs.. Similarly, the high degree of coupling causes changes that are made in a code snippet to reflect in various parts of the application causing previously designed tests to fail if they are not adequately designed. Non-VR applications had a lower occurrence in this category of smells, in which DBM and DCM are the two that presented the highest occurrence, with 1.10\% and 1.08\% respectively. The explanations for the occurrence rate for the DCM smell are related to the cyclic dependence issue of the MVC model and the DBM smell arises when data and/or methods that ideally should have been localized into a single abstraction are separated and spread across multiple abstractions. Once again, we applied the Mann-Whitney test to check whether the data obtained from our empirical evaluation can draw a real picture about the behavior of class that does not have tests compared to classes that were properly tested. Once again the Mann-Whitney test proved with a p-value = 0.00089 that classes that were tested tend to present lower rates of smells when compared to classes that were not tested. Our second research question ($RQ_2$) sought to understand \textit{``What are the distribution of architecture, implementation and design smells in VR projects?"}. We investigated the main types of smells for VR applications and compared their results with Non-VR applications. We observed that in the context of VR applications there is a greater incidence of code smells related to implementation and design respectively since these two categories have code smells that are repeated frequently due to the characteristics existing in the development of VR applications. We also presented a discussion about how software testing practices can benefit from avoiding the smells that obtained the highest occurrence rate. Finally, the statistical tests performed showed that when comparing VR and Non-VR projects, it was possible to observe that the software testing practice can contribute to increase the quality criteria and to reduce the presence of code smells. \begin{figure*} \centering \includegraphics[scale= 0.8]{acl_workflow.pdf} \caption{General process of ACL fault prediction approach (Source: own construction)} \label{fig:acl_workflow} \end{figure*} According to Hall et al. \cite{Hall:2014}, code smells have a significant but small effect on faults. This can justify the fact that Non-VR application projects, which have test cases, present a lower rate of code smells when compared to VR applications, which do not have, for the most part, a well-defined test activity. However, the presence of smells not only hides potential source code flaws but also contributes to hindering the maintainability and evolution of the source code in larger projects. This leads us to the last research question of this study ($RQ_3$), which aims to investigate the fault proneness of VR projects. In a similar way to the analysis of code smells, evaluate this in more depth, we inserted the analysis of Non-VR projects so as to better understand the results. \subsection{Analyzing fault proneness} As mentioned before, the presence of code smells can indicate the absence of quality attributes in the source code and this can be an indication of faults in a software \cite{Hall:2014}. Similarly, as previously mentioned, the higher occurrence rate of code smells in the projects can hinder the practice of software testing. To understand the risks of neglecting this activity, we analyzed the projects concerning fault proneness. Since code smells are identified according to rules and thresholds defined in code metrics \cite{Khomh:2009}, we aim to investigate ($\mathbf{RQ_3}$) the question: \textit{``Can we draw a relationship between code metrics and fault proneness?"}. To do so, we use the code metrics described in Table \ref{tab:projects_metrics} with a fault prediction technique, which uses the metrics value as an indicator to suggest whether a given source code is fault-prone or not. By exploring relationships between software metrics and fault proneness, we seek to justify the need for software testing activities. For instance, a high threshold in a specific metric may lead us to suspect, with high probability, about the reliability of some parts of the code. The effectiveness of fault prediction techniques is often demonstrated using historical repository data \cite{Herbold:2017}. However, once these techniques are adopted, it is not clear how they would affect projects that do not match with the characteristics (language, platform, domain) of the built model \cite{Peng:2015}. Since we do not have access to a dataset or a bug track history maintained with VR systems data, we tried to exploit an approach that uses an unsupervised fault prediction technique \cite{Yang:2016}, that does not rely on historical data, to investigate fault proneness on the analyzed projects. We use the Average Clustering and Labeling (ACL) \cite{Yang:2016} approach to predict fault proneness in unlabeled datasets. ACL models obtain good prediction performance and are comparable to typical supervised learning models in terms of precision and recall, offering a viable choice for fault prediction when we do not have historical data related to faults. This study can help software developers to understand the characteristics of VR software and the potential implications of neglect software testing activities. Raising awareness is the first step towards VV\&T activities. Figure \ref{fig:acl_workflow} describes the process used by the approach to attest if a given instance of code is defined as fault-prone or not. In general terms, the the process to run the approach consist mostly of four steps: \begin{itemize} \item calculates the average value for each of the code metrics used; \item build a violation matrix metric; \item calculates metrics of instance violation; and \item defines whether the analyzed instance is considered as fault-prone or clean. \end{itemize} The first step is self-explanatory and uses the individual metrics for each class, similar to those presented in Table \ref{tab:projects_metrics}, as input data. After this stage, a violation matrix, which evaluates each metric, is built using as a basis the average of the results constituted for all classes in the project. The next step is to check the number of violations for each class concerning the metrics evaluated and, finally, in the last step to classify whether a particular instance is fault-prone or not. To perform the classification, it is necessary to define a cutoff that will be used as a threshold and, if violated, it will identify whether the class is fault-prone or not. The cutoff point is calculated using the number of metrics that are used in the evaluation. Full details of the approach and the implementation can be found in \cite{Yang:2016} and in the repository that contains the information about this work. The 119 VR projects were analyzed using the described approach and according to the classification metric adopted, from 21,508 classes contained in all the projects, a total of 2,627 classes or 12.21\% were classified as classes with a high probability of having faults, due to the fact they extrapolate the threshold defined by the approach to consider them as clean. Similarly, in the 107 Non-VR projects, out of 21,568 classes, a total of 1,921 were labeled as fault-prone, which corresponds to a percentage of 8.90\% of the analyzed classes. In a superficial analysis it is possible to have a mistaken view of the results of this study and imagine that the percentage of propensity to fail presented appears low and, therefore, the time and expense necessary to identify them is perhaps not justified. However, according to previous investigations \cite{Walkinshaw:2018}, the \textit{Pareto} principle also tends to apply to a software faults context. It is believed that 20\% of the files are responsible for up to 80\% of the faults found in a project. Therefore, it is natural that the percentage of classes with a propensity to fail to follow this same trend, since it is not an exact proportion and the classification approach is not an exact formula and serves only as a mechanism to assist in efforts to apply a software testing approach. As pointed out by Nam \cite{Nam:2014}, defect prediction approaches play a role as a complementary approach to help identify potential problems in the source code as well as a mechanism to improve it and consequently get rid of productivity bottlenecks and future issues. Thus, the results presented here are not intended to point out the exact number of problems in a software product evaluated, but to strengthen the hypotheses that projects that adopt quality criteria, such as software testing practice, tend to be less predisposed to future issues. It's also important to note that, since there is no precise information about the test criteria used in Non-VR projects, as well as any information regarding the coverage reached by the designed tests, it is impossible to guarantee that the tests designed for a class are enough to ensure that it is free of any problems. Therefore, it is natural that the percentage of fault-proneness between projects that have not been tested (VR projects) and projects that have test cases (Non-VR projects) is slightly similar. It can be observed that despite having a larger number of classes and lines of code for those analyzed in the VR projects, Non-VR projects presented a lower fault-proneness rate. It is worth noting that the fault-prone algorithm is executed only in the classes related to the source code of the application, thus disregarding the test classes in the Non-VR projects. This analysis could be an indication that due to the practice of testing, classes of the Non-VR projects have a higher degree of reliability, and therefore are less fault-prone when compared to the classes existing in the VR projects, which mostly do not present test cases. \begin{figure*} \centering \includegraphics[scale = 0.35]{pie_chart.pdf} \caption{Classification of the VR projects according to the ACL approach (Source: own construction)} \label{fig:pie_chart_vr} \end{figure*} These numbers can be observed in Figure \ref{fig:pie_chart_vr} and are alarming numbers since they show the negative impact that a lack of robust and standardized testing technologies can cause to the software industry \cite{Planning:2002}. Consequently, it contributes to an increase in the incidence of avoidable faults that tend to appear only after the software is used by its end users. Similarly, the software development cost tends to increase because historically the process of identifying and correcting faults during the software development process represents more than half of the costs incurred during the development cycle \cite{Brooks:1995}. This delay in the product development can lead to situations such as the increase in the time needed to put a product on the market, also resulting in market opportunity losses \cite{Afonso:2008}. We went further trying to understand how the faults pointed out by the approach are distributed into the projects. Since the projects have a great variety of sizes, we grouped them into 6 different categories (by the number of classes) in order to observe how the distribution of fault-prone classes occurs. \begin{figure}[ht] \centering \includegraphics[scale=0.6]{fault_distribution.pdf} \caption{Distribution of fault-prone classes according to the size of the projects (Source: own construction)} \label{fig:lines_chart} \end{figure} Figure \ref{fig:lines_chart} shows this distribution. It can be observed that in both VR and Non-VR projects, there is a relation between the number of fault-prone classes and the size of the projects. This relation points out that the higher the number of classes in the projects, the higher the average fault-prone classes, and leads us to conclude that neglecting testing activity in larger projects may be even more riskier in terms of the project’s success. Future analyses could be extracted from the data obtained. However, we believe that the presented data are capable of attesting a clear answer to $RQ_3$, making it clear that in a general context, the lack of software testing techniques have a direct impact on quality attributes, as demonstrated by the metrics extracted from the analyzed projects and this directly reflects the adoption of bad development practices, which lead to the existence of code smells, consequently becoming an outlet for the increase in faults. $RQ_3$ sought to understand the question: \textit{``Can we draw a relationship between code metrics and fault proneness?"} and by implementing the approach to detect fault proneness in the projects investigated, it could be observed that neglecting the test activity can lead to a higher probability of development problems. According to our analysis, it was seen that the VR projects, which do not present test cases, have a higher propensity to present faults to Non-VR projects, and that propensity tends to increase as the complexity of the projects increases. It was also observed that although Non-VR projects present test cases in all projects, they still present a high rate of fault proneness. This underscores the importance of the developing software testing practice within the scope of project development. Although Non-VR projects have test cases, the test sets provided do not meet the basic test criteria, such as code coverage, so that part of the code that is not tested is still prone to possible failures. Another point that this study raised is the need for specific test practices for a specific domain. Software of different domains have different characteristics, which must be adequately investigated. In the context of VR applications, the simple use of unit tests may not be sufficient to attest the quality of the developed product, since the technological advancement has led to the development of systems with advanced features such as images, sounds, videos, and differentiated interaction, presenting new challenges when compared to software testing in conventional domains, such as the lack of information on typical defects and even the lack of a precise definition of a test case and the oracle problem \cite{Rapps:1985, Barr:2015}. \section{Do We Really Need to Test Virtual Reality Software?}\label{sec:experiment} Considering popularizing VR application development, we are interested in understanding, from the software engineering point of view, how the development process of these applications is currently conducted. We are especially interested in software testing practices in the development process of such applications in order to address what kinds of malfunctions the lack of test practice can lead to. One of the most used approaches to quantify quality attributes in software projects is the evaluation of source code metrics. Source code metrics are a significant component for the software measurement process and are commonly used to measure fault proneness and improve the quality of the source code itself \cite{Palomba:2014}. \begin{figure*}[t] \centering \includegraphics[scale = 0.6]{svr_study_design.pdf} \caption{Steps taken to carry out the study (Source: own construction)} \label{fig:study_design} \end{figure*} Another factor that can be exploited to evaluate code quality is to identify anti-patterns since some studies show that there is a correlation with fault proneness \cite{Khomh:2012}. Therefore, these are two aspects that are taken into account in the evaluation carried out in our study to investigate the quality aspects of the code in the context of software testing. Ghrairi et al. \cite{Ghrairi:2018} made an exploratory study on \textit{Github} and \textit{Stack Overflow} in order to investigate which are the most popular languages and engines used in VR projects. According to their results, the most popular language for VR development is C\#, and Unity is the most used game engine during VR application development. Thus, we focus our analyses targeting these characteristics. \subsection{Overview of the study} We formulated the following research questions regarding the quality analysis goal of VR projects. \begin{itemize} \item $\mathbf{RQ_1}:$ \textit{``How does testing happen in open-source VR software systems?"} We focus on understanding how testing practices are being applied in open-source VR projects. \item $\mathbf{RQ_2}:$ \textit{``What are the distribution of architecture, implementation and design smells in VR projects?"} We investigated the distribution of smells to find out whether there is a set of code smells that occur more frequently in VR systems. \item $\mathbf{RQ_3}:$ \textit{``Can we draw a relationship between code metrics and fault proneness?"} It is commonly believed that code metrics and fault-proneness, i.e., if a set of code metrics reaches a predefined threshold, it is very likely that the project could also have some faults. We investigate this using an unsupervised defect prediction approach. \end{itemize} \begin{table*}[ht] \scalefont{0.85} \centering \caption{Characteristics of the repositories used in the experiment} \begin{tabular}{l|r|r|r|r|r|r} \hline \multicolumn{1}{c|}{\multirow{2}[4]{*}{Features / Characteristics}} & \multicolumn{2}{c|}{Small size ( 1 $\thicksim$ 80 classes)} & \multicolumn{2}{c|}{Medium size (80 $\thicksim$ 200 classes)} & \multicolumn{2}{c}{Large size ( 201+ classes)} \\ \cmidrule{2-7} & \multicolumn{1}{c|}{\textbf{VR}} & \multicolumn{1}{c|}{\textbf{non-VR}} & \multicolumn{1}{c|}{\textbf{VR}} & \multicolumn{1}{c|}{\textbf{non-VR}} & \multicolumn{1}{c|}{\textbf{VR}} & \multicolumn{1}{c}{\textbf{non-VR}} \\ \hline Nº C\# Classes & 31.5 & 30.2 & 121.7 & 126.4 & 374.8 & 4320 \\ \hline Nº Branches & 1.45 & 1.7 & 1.7 & 2.5 & 2.56 & 11.4 \\ \hline Nº Commits & 78.4 & 45.5 & 48.8 & 245 & 66.2 & 8931 \\ \hline Nº Contributors & 2.6 & 1.4 & 2.5 & 2.2 & 2.9 & 47.1 \\ \hline Nº Forks & 34.7 & 1.9 & 10.9 & 1 & 76.6 & 82.4 \\ \hline Nº Subscribers & 15.8 & 2 & 8.1 & 2.5 & 22.3 & 176.8 \\ \hline Nº Stars & 111.6 & 4 & 23.8 & 0.7 & 187.8 & 89.4 \\ \hline \end{tabular}% \label{tab:github_stats}% \end{table*}% \subsection{Study Design} The process of selecting open-source projects consists of a systematized search, on \textit{Github}, using the keywords ``virtual reality" and ``VR". With the objective of drawing a more specific profile, the search focused only on projects developed for the \textit{Unity} platform, since it has emerged as the most popular VR development platform due to its extensive documentation \cite{Ghrairi:2018}. Our primary aim is to explore virtual reality projects from both project and source code perspectives. To do so, we cataloged and analyzed a total of 151 open-source projects, available in \textit{Github}. Some of the projects could not be analyzed due to either missing external dependencies or custom-build mechanisms (i.e., missing standard C\# project files), thus we were able to analyze a total of 119 projects. In order to draw a picture concerning research questions $RQ_2$ and $RQ_3$, we also cataloged a set of general (Non-VR) open-source projects, which have similar characteristics (same C\# programming language). The goal is to try to compare the information observed in the VR application with Non-VR application. Therefore, we catalog a total of 177 Non-VR projects. After an individual process analysis, we removed duplicated projects and projects that had missing external dependencies or custom-build mechanism. In the end we achieved a total of 107 Non-VR projects able to be used in our experiment. Since our goal is to analyze which impacts the lack of software testing practice can cause on VR projects, concerning Non-VR projects, we will use only data related to classes that have been properly tested. Thus, for all the experiments, two types of projects were gathered. The first is a set of VR projects. The second is a set of general-purpose projects that hold some unit test code used to evaluate their modules. The purpose of the first step is to manually evaluate VR projects in order to understand how much open-source VR application developers are concerned regarding testing practices for this specific domain. Based on the observation of the results of the initial analysis, the second step is to assess how much the lack of software testing activity can contribute to the construction of codes that become more difficult to maintain over time. For this, an analysis is made regarding the presence of code smells and the results obtained in VR projects are compared with the results obtained in general-purpose projects. Finally, the last step aims to assess how much code metrics are capable to point about fault proneness. The goal is to evaluate the projects and observe how the VR projects and projects that have been tested behave, in order to understand whether test practice can contribute to a given code snippet being less fault-prone regarding untested code snippets. The procedure carried out during the execution of the experiment is described in Figure \ref{fig:study_design} and consists of the following steps: \begin{enumerate} \item Search the \textit{Github} platform for projects with the targeted characteristics. \begin{enumerate} \item VR projects that were developed using the Unity platform. \item General purpose projects that were developed using the C\# programming language and have software testing practices in their composition. \end{enumerate} \item Data extraction related to testing practice in VR application projects. \item Code metrics and code smells information extraction for all projects. \item Use of code metrics to calculate fault-proneness in all projects. \item Summary of the results and answer the research questions. \end{enumerate} \subsection{Overview of Projects} One of the biggest concerns when carrying out experiments using open-source artifacts is related to the representativeness of the artifacts and whether therefore the results found can be properly generalized \cite{Hillenbrand:2005}. With it in mind, we were careful to try to select the largest number of study objects, in such a way that they could meet a wide variety of characteristics and not be limited to toy examples. Table \ref{tab:github_stats} summarizes the information on the artifacts used in the experiments developed in this paper. The data related to the main characteristics of the repositories are presented in the form of average, by classifying the repositories among small projects (with up to 80 classes), medium (with projects that have between 80 and 200 classes) and large projects with a number of higher classes to 200. Below we present the main features cataloged in the repositories used: \begin{itemize} \item Branches - correspond to branches used to implement new features or correct faults, in such a way that the unstable code is not merged into the main project files. \item Commits - commits refer to the act of submitting the latest source code changes to the repository and making these changes part of the main version of the repository. \item Contributors - refers to the number of people outside the main project development team who have contributed or wish to contribute to changes to the project. \item Forks - copies from a repository. Forking a repository allows third parties to perform experiments on the source code without affecting the original project. \item Subscribers - number of people who are registered to receive notifications related to updates on activities and changes made to the project. \item Stars - indicates the number of people who have defined markers in the project so that they can follow what is happening with the project in the future ( according to Kalliamvakou et al. \cite{Kalliamvakou:2014} this metric is commonly used to measure the popularity of repositories). \end{itemize} In order to provide a view of the general scope of the artifacts used, Table \ref{tab:projects_overview} presents information about the general characteristics of all projects. \begin{table}[ht] \centering \caption{General characteristics of the analyzed projects} \begin{tabular}{l|r|r} \hline \multicolumn{1}{c|}{\textbf{Attributes}} & \multicolumn{1}{c|}{\textbf{VR}} & \multicolumn{1}{c}{\textbf{Non-VR}} \\ \hline Projects & 119 & 107 \\ Number of tested classes & 63 & 4,186 \\ Number of classes (total) & 21,508 & 21,563 \\ Lines of code (C\# only) & 2,314,522 & 2,455,766 \\ \hline \end{tabular} \label{tab:projects_overview} \end{table} Aiming to estimate non-functional requirements used to evaluate the performance of a system, such as software quality attributes of the projects, and to give an overall view of the projects analyzed, we computed, according to an object-oriented design \cite{Chidamber:1994}, a set of metrics that are summarized in Table \ref{tab:projects_metrics}. \begin{table}[ht] \scalefont{0.7} \centering \caption{Metrics of the analyzed projects} \begin{tabular}{l|r|r|r|r} \hline \textbf{Metric} & \textbf{VR} & \textbf{Average} & \textbf{Non-VR} & \textbf{Average} \\ \hline Number of Children & 3,811 & 0.17 & 716 & 0.17 \\ Number of Fields & 102,785 & 4.77 & 7,062 & 1.68 \\ Number of Methods & 107,516 & 4.99 & 14,374 & 3.43 \\ Number of Properties & 24,395 & 1.13 & 67 & 0.01 \\ Number of Public Fields & 49,793 & 2.31 & 1,368 & 0.32 \\ Depth of Inheritance Tree & 4,072 & 0.18 & 1,278 & 0.30 \\ Number of Public Methods & 65,624 & 3.05 & 9,582 & 2.28 \\ Lack of Cohesion of Methods & 34,197 & 1.58 & 7,958 & 1.90 \\ Weighted Method per Class & 190,658 & 8.86 & 21,959 & 5.24 \\ \hline \end{tabular} \label{tab:projects_metrics} \end{table} All the information about the projects, the data used for plotting the tables and graphs, as well for the discussion, are available in the experiment repository\footnote{\url{https://github.com/stevao-andrade/ACL_defect_prediction}}. \section{Introduction}\label{sec:introducao} Researchers have studied software faults extensively. These studies lead to the characterization of defects, both in the theoretical and practical contexts. Such characterization is essential to evaluate software testing techniques concerning their ability to reveal certain types of faults. These characterizations and taxonomies can provide guides for defining test approaches, which can support fault detection in specific software domains. Technological advancement has led to the development of systems with new features such as images, sounds, videos, and differentiated interaction. Thus, technologies such as Virtual Reality (VR) have led to possibilities of creating three-dimensional environments with real-time interaction. There are various techniques to obtain a greater sensation of immersion, according to the computational resources, equipment and systems used, vision, touch, and hearing experiences can be reproduced. Thus, in addition to simulating real situations, VR also allows users to depict and interact with hypothetical situations, involving static or moving virtual objects. Despite the great benefits of adopting VR for the development of applications in various areas, it poses new challenges for verification, validation, and testing (VV\&T) activities. For example, VR software presents original software structures, such as scene graphs, which may represent new sources of defects for programs. These new challenges motivated the development of some approaches that aim to contribute to the quality assurance process of software in the context of VR. As mentioned by Corrêa et al. \cite{Santos:2013}, there is interest in the literature on the subject. However, there is still no concept regarding systematized practices for conducting this activity. Studies have shown that the major problem remains in the difficulty to deal with test oracles, which is considered to be an open-ended research problem. In general, the test activities for the VR domain are manually performed and mostly conducted only after the end of the development phase \cite{Correa:2018}. Such events generally support the generation of test requirements (functional and non-functional) which must be guaranteed before the product is delivered. The lack of studies that evaluate the cost of developing new techniques or using existing ones assess their effectiveness or even propose tools that can support their application, thus contributing to impact VV\&T activities in general and aggravate this scenario. Regardless of the programming technology used, a primary development goal is to produce high-quality software. Consequently, VR also needs to be tested and vetted for quality. According to Neves et al. \cite{Neves:2018} there are series of conceptual challenges and key questions related to quality that need to be addressed when planning to apply software testing practices in new domains: \textit{What should be tested?, What does ``adequate testing" mean?, What is a failure in VR software?, Can we reuse something?, What is done nowadays?} Systematic testing of the VR system must be based on fault models that reflect the structural and behavioral characteristics of VR software. Criteria and strategies for testing VR should be developed based on that fault model. In this paper, we discuss whether new challenges for VV\&T of VR exist that require novel techniques and methods, or instead, we need new ways of combining and using existing approaches. We also try to evaluate how much the lack of VV\&T activities can negatively impact VR software development. To do so, we analyze the most popular open-source projects and categorize fault-proneness codes that could be mitigated by adopting VV\&T activities. This paper is organized as follows: Section \ref{sec:related} present the related work and discusses how they differ from our work; Section \ref{sec:challenges} discusses the critical questions described above, as well as what testing approaches proposed in other domains could be reused for the VR domain; Section \ref{sec:experiment} presents an exploratory study to assess how much the lack of VV\&T activities can be prejudicial to open-source projects; Section \ref{sec:discussion} discusses the results of the experiment presented; Section \ref{sec:limitations} points out some limitations related to this study; finally the conclusions and future work are shown in Section \ref{sec:conclusion}. \section{Limitations and Threats to Validity}\label{sec:limitations} The main limitations of this study are related to the fact that the data used in this study were gathered from \textit{Github}. Although the collected data enabled us to discuss the state of practice regarding the application of software testing techniques in the context of VR, open source projects still represent only a small portion of what is produced in the context of VR applications. Commercial projects and closed projects are also part of this universe, and it is not possible to attest that the results discussed from data extracted from open source projects can be generalized for these other scenarios. The problem described above opens opportunities to develop similar research in partnership with industry in order to understand whether the results converge in the same direction. In addition to the limitations described above, another obstacle that must be pointed out is the fact that despite the fact that the assumptions made during the study were related to the context of VR applications, it should be emphasized that all the samples observed only use a single technology (\textit{Unity}), therefore the results indicated here cannot be generalized for other platforms. To achieve such generalization, new studies should be carried out to corroborate or counter the results presented in this study. The validity of the results achieved in experiments depends on factors in the experiment settings. Different types of validity can be prioritized depending on the goal of the experiment. Concerning the threats to the validity of this study, which are related both to the evaluation of code smells and to fault-proneness detection, we can highlight the fact of performing an analysis using samples extracted only from a platform and just for open source projects was a significant threat to validity - this relies on the lack of representativity of the projects in serving as a real sample of the universe of all types of projects for the VR domain. Unfortunately the lack of representativity is a problem that affects the entire software engineering area, since there is no well-fledged theory capable of ensuring that a set of programs is considered a representative sample for experimentation. To try to mitigate this threat, the most significant possible number of projects was assembled, varying in size (small, medium and large) and application purposes (entertainment, simulation, training, health). Another measure taken to try to mitigate the threat described above was to analyze Non-VR projects, which served as subsidies to compare with the results obtained from VR projects, ensuring a better grounded discussion and a minimum baseline for comparison, since, unfortunately, there are still no projects cataloged with VR applications that meet the requirements to be used in this work. Related to threats to construct validity, possible mistakes can be pointed out both in the analysis of codes smells, as well as in the evaluation of fault proneness. To minimize this threat, the tool \textit{Designite} was used to detect code smells, \textit{Designite} is a commercial tool and has already been successfully used in other experiments \cite{Sharma:2017}. In the context of the experiments carried in this study, in addition to using a commercial tool to support the gathering of data related to the code smell, all the data presented was evaluated using both descriptive analyses, and hypothesis testing in order to guarantee that the conclusions drawn from this work enable us to paint a clear and quantitative picture about the subject explored. Regarding the approach to detect fault proneness, the strategy used was previously validated through experiments in large datasets to attest its efficacy \cite{Yang:2016}, and it is worth mentioning the fact that the main point of the approach was not, in fact, to detect faults in the projects, but point out classes that have a high probability of having faults, serving as a guide to direct testing efforts and to discuss the necessity of apply software testing techniques. Finally, we discuss threats to the internal validity of the study, which are related to the level of confidence between the expected results and the results obtained. The whole study was conducted in a way that minimized this threat. To increase confidence about the presented results, the data were analyzed using tables and graphs and were also made available in a repository to enable the replication if it is deemed necessary. \section{0pt}{12pt plus 3pt minus 3pt}{1pt plus 1pt minus 1pt} \titlespacing\subsection{0pt}{10pt plus 3pt minus 3pt}{1pt plus 1pt minus 1pt} \titlespacing\subsubsection{0pt}{8pt plus 3pt minus 3pt}{1pt plus 1pt minus 1pt} \newcommand\graycell{\cellcolor{lightgray}} \usepackage{comment} \usepackage{colortbl} \usepackage{scalefnt} \usepackage{multirow} \usepackage{subcaption,mwe} \usepackage{ amssymb } \title{Towards the Systematic Testing of Virtual Reality Programs (extended version)} \usepackage{authblk} \renewcommand*{\Authfont}{\bfseries} \author[1]{Stevão A. Andrade} \author[2]{Fatima L. S. Nunes} \author[1]{Marcio E. Delamaro} \affil[ ]{Universidade de São Paulo} \affil[1]{Instituto de Ciências Matemáticas e de Computação} \affil[2]{Escola de Artes, Ciências e Humanidades} \affil[ ]{\tt{\{stevao, delamaro\}@icmc.usp.br, [email protected]}} \begin{comment} \title[Towards the Systematic Testing of Virtual Reality Programs]{Towards the Systematic Testing of Virtual Reality Programs} \author[S. A. Andrade, F. L. S. Nunes, and M. E. Delamaro]{ \affil{\textbf{Stevão A. Andrade}~\href{https://orcid.org/0000-0002-1559-6789}{\textcolor{orcidlogo}{\aiOrcid}}~~[~\textbf{Universidade de São Paulo - ICMC~}|\href{mailto:[email protected]}{~\textbf{\textit{[email protected]}}} ]} \affil{\textbf{Fatima L. S. Nunes}~\href{https://orcid.org/0000-0003-0040-0752}{\textcolor{orcidlogo}{\aiOrcid}}~~[~\textbf{Universidade de São Paulo - EACH~}|\href{mailto:[email protected]}{~\textbf{\textit{[email protected]}}} ]} \affil{\textbf{Marcio E. Delamaro}~\href{https://orcid.org/0000-0001-7535-5891}{\textcolor{orcidlogo}{\aiOrcid}}~~[~\textbf{Universidade de São Paulo - ICMC~}|\href{mailto:[email protected]}{~\textbf{\textit{[email protected]}}} ]} } \end{comment} \begin{document} \twocolumn[ \begin{@twocolumnfalse} \maketitle \begin{abstract} \textbf{Abstract} Software testing is a critical activity to ensure that software complies with its specification. However, current software testing activities tend not to be completely effective when applied in specific software domains in Virtual Reality (VR) that has several new types of features such as images, sounds, videos, and differentiated interaction, which can become sources of new kinds of faults. This paper presents an overview of the main VR characteristics that can have an impact on verification, validation, and testing (VV\&T). Furthermore, it analyzes some of the most successful VR open-source projects to draw a picture concerning the danger of the lack of software testing activities. We compared the current state of software testing practice in open-source VR projects and evaluate how the lack of testing can be damaging to the development of a product. We assessed the incidence of code smells and verified how such projects behave concerning the tendency to present faults. We also perform the same analyses on projects that are not VR related to have a better understanding of these results. The results showed that the practice of software testing is not yet widespread in the development of VR applications. It was also found that there is a high incidence of code smells in VR projects. Analyzing Non-VR projects we noticed that classes that have test cases tend to produce fewer smells compared to classes that were not tested. Regarding fault-proneness analysis, we used an unsupervised approach to VR and Non-VR projects. Results showed that about 12.2\% of the classes analyzed in VR projects are fault-prone, while Non-VR projects presented a lower fault-proneness rate (8.9\%). Regarding the application of software testing techniques on VR projects, it was observed that only a small number of projects are concerned about developing test cases for VR projects, perhaps because we still do not have the necessary tools to help in this direction. Concerning smells, we concluded that there is a high incidence in VR projects, especially regarding implementing smells and this high incidence can have a significant influence on faults. Finally, the study related to fault proneness pointed out that the lack of software testing activity is a significant risk to the success of the projects. \end{abstract} \keywords{Software Testing \and Virtual Reality \and Validation \and Verification \and Code Smells \and Fault Proneness} \vspace{0.35cm} \end{@twocolumnfalse} ] \input{introduction.tex} \input{related.tex} \input{challenges.tex} \input{experiment.tex} \input{discurssion.tex} \input{limitations.tex} \input{conclusion.tex} \section*{Acknowledgements} Stevão A. Andrade research was funded by FAPESP (São Paulo Research Foundation), process number 2017/19492-1. This study was also financed in part by FAPESP (São Paulo Research Foundation) process number 2019/06937-0. The authors are grateful to Brazilian National Council of Scientific and Technological Development (CNPq) for assistance (process 308615/2018-2), and National Institute of Science and Technology Medicine Assisted by Scientific Computing INCT MACC ( Process 157535/2017-7). We also would like to thanks Tushar Sharma and \textit{Designite} team by providing us an Academic license of \textit{Designite} tool. \bibliographystyle{apalike} \section{Related Work}\label{sec:related} Although virtual reality studies date back a long time \cite{Boman:1995}, only recently have few studies addressed the development of VR applications from a software engineering perspective. The increase in community interest has emerged with the recent popularization of tools that have facilitated access, and consequently developers' interest in this technology, which is still considered as emerging. Rodriguez and Wang \cite{Rodriguez:2017} present a survey about projects developed for the \textit{Unity} platform, highlighting the growth of the number of projects in recent years. Another highlight is the fact that despite the higher number of applications focused on games and entertainment, there has been an increase in the number of applications for other purposes, such as training and simulations. Unlike our work, the paper does not analyze the content of the cataloged material in detail, and is limited to studying the growing trends, development involvement, favorite topics, and frequent file changes in these projects. Ghrairi et al. \cite{Ghrairi:2018} conducted a study on the exploratory analysis of \textit{Github} projects and questions extracted from \textit{StackOverflow}, analyzing it from a software engineering point of view. The study demonstrates the current state of practice regarding the development of open-source VR applications, highlighting mainly the most used platforms and technologies. Moreover, the paper also discusses topics of interest for VR developers by analyzing the VR questions extracted from \textit{StackOverflow}. The main results show the greater popularity of the \textit{Unity} and \textit{Unreal Engine} platforms as being the most popular among VR application developers. However, they also point out that more work needs to be done to better understand the VR requirements under a software engineering context, which is one of the points that our work seeks to elucidate. From the perspective of software testing applications in the context of VR, we highlight the work produced by Corrêa et al. \cite{Correa:2018}, which presents a proposal for application software testing for VR applications. This study generates test data using specified requirements through a semi-formal language for VR application development. This approach moves in the direction pointed out by our study, which is the proposition of mechanisms that allow the systematization of the test activity for VR applications. Karre et al. \cite{Karre:2019} conducted a year-long multi-level exploratory study to understand the various software development practices within VR product development teams in order to understand whether the traditional software engineering practices are still exercised during VR product development. The main results show that VR practitioners adopted hybrid software engineering approaches in VR product development and, in general, interviewed developers complain about the lack of software testing tools. An alternative presented to solve this problem is the involvement of consumers during the testing (pre-release versions) phase to understand the customer experiences and reactions. Posteriorly Karre et al. \cite{Karre:2020} also assessed aspects related to tasks such as scene design, acoustic design, vergence manipulation, image depth, etc. which are specific to VR apps and hence require evaluation processes that may be different from the traditional ones. They presented a categorization that can support decision making in choosing a usability evaluation method for the future development of VR products. By using the categorization, the teams can use unique methods to improve the usability of their products, once depending on the industry (automobile, education, healthcare, etc.) the usability and the metrics of evaluation methods can change.
{'timestamp': '2020-09-21T02:17:37', 'yymm': '2009', 'arxiv_id': '2009.08930', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08930'}
arxiv
\section{Introduction} \label{intro} Over the past few years, the adoption of Machine Learning (ML) techniques to the field of network security has become prominent \cite{granville1,granville2}. This is mainly due to the possibility of tackling a range of ever more sophisticated attacks able to circumvent security-based systems which rely on classic features inspection (e.g. port-control, signature-based flow detection, IPs black-listing, etc.). It is useful to recall that, especially in encrypted traffic analysis, the difference between \textit{deterministic} and \textit{stochastic} features is crucial. Deterministic ones pertains to ``static'' information embodied in security protocols such as TLS (e.g. record length, handshake types, cipher suites, etc.) \cite{cisco-nids}, or IPSec (ISAKMP SPI Initiator/Responder, payload length, etc. ). On the other hand, stochastic features exploit the probabilistic nature (hard to hide in encrypted flows as well) of some traffic characteristics (e.g. the distribution of inter-arrival times). On behalf of ML-based techniques, it becomes quite straightforward to manage stochastic features which, coupled with the deterministic ones, allow to characterize as accurately as possible an encrypted data flow. Moreover, new network intrusion detection systems (NIDS) \cite{gaspary1,gaspary2} can actually interact with ML-based engines in order to learn the statistical features that characterize the various traffic flows and, in turn, classify them according to specific performance/time efficiency trade-offs. Among various possibilities of interaction, the Simple Network Management Protocol (SNMP) offers a flexible and standardized way to collect traffic data from a number of agents, by relying on Management Information Base (MIB) objects which provide information about some features to be managed \cite{cerroni1,cerroni2,cerroni3}. This notwithstanding, one of the biggest problems is to deal with the jungle of ML techniques which, depending on the underlying strategy, can exhibit completely different performance when applied in the intrusion detection field. In fact, most attempts at surveying ML-based traffic classification problems have resulted in non-homogeneous comparisons and often unfair outcomes. Another flaw found in existing literature concerns the choice of a valid dataset. Most of studies, in fact, rely on the obsolete KDD$99$ dataset \cite{kdd-dataset}, or its evolved version NSL-KDD \cite{nsl-kdd}. These datasets either do not contemplate essential features of modern data traffic (e.g. voice, video), or contain outdated signatures of network attacks \cite{icissp-dataset3}. In this paper we address the aforementioned shortcomings, providing the following main contributions. \textit{i)} We survey neural-based techniques, which have recently taken prominence thanks to deep-based methods, in the specific context of traffic classification problems; we provide a critical comparison of algorithms that share a common paradigm (e.g. deep neural networks, linear vector quantization, etc.), including also techniques that are not typically applied to intrusion detection, such as weightless neural networks, whose results are quite unexpected. \textit{ii)} We go beyond a traditional survey, providing an experimental-based assessment; we take into account novel traffic datasets (such as CIC-IDS-2017/2018), where both single-class cases (namely benign vs. malign) and multi-class cases (namely benign vs. malign$_1$ ... vs. malign$_k$) are considered; we perform both performance analysis (through accuracy/F-measure figures) and time-complexity analysis. The paper is organized as follows. Section \ref{sec:rw} presents an {\em excursus} of related literature and, by means of a comparative table, we highlight differences and commonalities with other surveys. In Sect. \ref{sec:nn} we review the most credited neural-based methods. Section \ref{sec:dataset} presents details about the novel considered datasets, where traffic features are grouped according to a similarity criterion. In Sect. \ref{sec:experim} we provide an experimental-based comparison, where different neural-based techniques are juxtaposed through performance and time-complexity analyses. Finally, Section \ref{sec:conclusion} concludes this work by also indicating some promising research directions. \section{Related Work on ML techniques applied to network intrusion detection} \label{sec:rw} ML-based intrusion detection is becoming attractive for a variety of network environments including service providers \cite{classif_dimauro}, sensor networks \cite{classif_liotta}, Internet of Things \cite{tnsm-classif-iot}, and automotive \cite{classif_pascale}. This notwithstanding, a great part of scientific literature, which faces the problem of data traffic classification through machine learning techniques, suffers from the datasets obsolescence issue. For many years, the only dataset available to the scientific community was the so-called KDD$99$, which is still broadly used today to validate ML-based algorithms and techniques when dealing with traffic classification problems. Unfortunately, this is an outdated $20$-years-old dataset involving network attacks that have already been mitigated. An example is {\em satan probing}, an attack aimed at probing a computer for security loophole, based on the {\em satan} tool that was created at the end of the 1990’s, but is today no longer documented as a Web page. Other examples include: {\em warezmaster/warezclient}, which exploits some old vulnerabilities of the anonymous FTP protocol, and {\em smurf attacks}, aimed at attaining default router settings that allowed directed broadcasts. Yet, currently, router vendors simply deactivate this functionality. An ameliorated version of KDD$99$ is known as NSL-KDD. However, despite providing some improvements (e.g. no redundant records, better balancing between training and test set), NSL-KDD is still not taking into account crucial information that characterizes novel cyber attacks. This notwithstanding, both KDD$99$ and NSL-KDD datasets are still broadly used to test some functionalities of NIDS systems that implement neural-based techniques. For instance, in \cite{precic_paper2,precic_paper3,ids_ann_19} the authors show the effectiveness of using an NIDS in conjunction with an artificial neural network (ANN) to improve the quality of traffic detection, where a validation stage onto the KDD$99$ dataset is performed. A deep learning approach is used in \cite{precic_paper1}, based on KDD$99$, to verify accuracy against an SVM methodology. A novel approach based on ANN (referred to as self-taught learning) is applied in \cite{precic_paper4} to enable an NIDS to detect previously unseen attacks via reconstructions made on unlabeled data. This work provides tests on both KDD$99$ and NSL-KDD. In \cite{precic_paper5} and \cite{precic_paper6} the authors adopt neural-based methods exploiting Self-Organizing Maps. In \cite{precic_paper7} and \cite{precic_paper8}, Learning Vector Quantization is coupled with SVM and k-Nearest Neighbor, respectively, to detect traffic anomalies. In \cite{ids_dnn_1,ids_dnn_2,ids_dnn3,ids_dnn4} deep neural networks concepts are applied to intrusion detection systems. The KDD$99$ and NSL-KDD datasets have also been used to test a variety of non neural-based techniques such as Support Vector Machine \cite{kdd_svm1,kdd_svm2,kdd_svm3,kdd_svm4,kdd_svm5}, Principal Component Analysis \cite{kdd_pca1,kdd_pca2,kdd_pca3,kdd_pca4,kdd_pca5}, Decision Trees \cite{kdd_decision1,kdd_decision2,kdd_decision3,kdd_decision4,kdd_decision4,kdd_decision5}, and various unsupervised approaches \cite{kdd_unsup1,kdd_unsup2,kdd_unsup3,kdd_unsup4,kdd_unsup5,kdd_unsup6}. By contrast to the aforementioned works, some recent datasets are emerging from new testbeds which adhere more strictly to real-world network scenarios. For instance, the Cyber Range Lab of the Australian Centre for Cyber Security provides two recent datasets: the UNSW-NB15 dataset \cite{unsw2} which includes a mix of legitimate network activities and synthetic attacks, and the Bot-IoT dataset \cite{bot-iot1} which embeds normal and simulated network traffic gathered in an IoT-compliant testbed, along with various types of attacks. Again, the datasets recently released by the Canadian Institute for Cybersecurity (CIC) \cite{cic} represent the state-of-the-art, in terms of both complexity and novelty of network attacks. These datasets have been created starting from an experimental testbed under controlled conditions \cite{icissp-dataset3}, whereby an attack network (including a router, a switch, and four PCs equipped with Kali Linux OS, which is a popular Linux distribution to perform penetration testing) is counterposed to a victim network (including routers, firewalls, switches, and various PCs equipped with Windows, Linux, and MacOS operating systems). An evolved version of this testbed has been designed to run on Amazon AWS \cite{aws}. In this case, the attacking infrastructure includes $50$ PCs, and the victim network includes $420$ PCs and $30$ servers. The implemented attacks encompass Distributed Denial of Service (DDoS), Portscan, Bruteforce, along with some typical Android-based network attacks injecting malicious codes such as adwares, malwares, and ransomwares. The interest for such novel datasets is proven by novel works as detailed in the following. In \cite{cic_paper1}, authors validate an artificial neural network system onto a CIC-released dataset to detect the malicious traffic generated by a botnet, out of the regular traffic. A hybrid neural network to detect anomalies in network traffic is proposed in \cite{cic_paper2}, where the CIC-IDS-2017 dataset has been exploited. Specifically focused on DDoS detection is the work in \cite{cic_paper3}, where a neural-based approach relying on the implementation of a simple Multi-Layer Perceptron is contrasted to the Random Forest technique. Again focused on DDoS detection is \cite{cic_paper4}, where some classic ML-based techniques (e.g. Na\"{\i}ve Bayes and Logistic Regression) are used to distinguish regular traffic from malicious one. \begin{table*}[h] \centering \caption{Prominent Related Work surveying ML techniques applied to Network Intrusion Detection.} \small \renewcommand{\arraystretch}{1.4} \begin{tabular}{|p{2.7cm}|p{3cm}|p{2.5cm}|p{6cm}|} \hline \textbf{Authors} & \textbf{Experiments} & \textbf{Single/Multi Class} & \textbf{Description} \\ \hline Nguyen et al. \cite{survey_pure1} & N/A & N/A & Classic survey on ML-based techniques with pointers to other works but with no experiments. \\ \hline Boutaba et al. \cite{survey_pure2} & N/A & N/A & Survey on ML-based techniques applied to various networking-related problems (from traffic classification to routing or QoS/QoE management). \\ \hline Hindy et al. \cite{survey_pure3} & N/A & N/A & Survey on IDS techniques taking into account ML algorithms such as ANN, K-means and SVM. \\ \hline Khraisat et al. \cite{survey_pure4} & N/A & N/A & Survey on Signature and Anomaly-based IDS techniques applying ML methods on NSL-KDD dataset. \\ \hline Aldweesh et al. \cite{survey_pure5} & N/A & N/A & Survey on Deep Learning techniques for IDSs with pointers to other works but with no experiments. \\ \hline Fernandes et al. \cite{survey_pure6} & N/A & N/A & Survey on various techniques (ML, Statistical, Information Theory) for intrusion detection with pointers to other works but with no experiments. \\ \hline Buczak et al. \cite{survey_pure7} & N/A & N/A & Survey on Data Mining and ML methods for intrusion detection with pointers to other works but with no experiments. \\ \hline Tidjon et al. \cite{survey_pure8} & N/A & N/A & Survey on various techniques (mainly ML-based) to be applied in intrusion detections with pointers to other works but with no experiments. \\ \hline Azwar et al. \cite{azwar} & Performance analysis & Single Class & Non-homogeneous comparisons among various approaches (trees, NN) by using modern CIC-IDS$17$ dataset. \\ \hline Moustafa et al. \cite{moustafa_table} & Performance analysis & Single Class & Holistic Survey on ML methods with experiments on feature reduction techniques (ARM, PCA, ICA). \\ \hline Meena et al. \cite{Meena} & Time analysis & Single Class & Non-homogeneous comparisons between J48 and Na\"{\i}ve Bayes techniques on KDD and NSL-KDD datasets. \\ \hline Rama et al. \cite{kdd_rama} & Performance analysis, Time analysis (partial) & Single Class & Non-homogeneous comparisons among various algorithms (e.g. J48, Na\"{\i}ve Bayes, Bagging) on KDD and NSL-KDD datasets. \\ \hline Yin et al. \cite{kdd_rnn} & Performance analysis & Single/Multi Class & Non-homogeneous comparisons among various and different approaches (e.g. J48, ANN, SVM) on KDD$99$ dataset. \\ \hline This work & Performance analysis, Time analysis & Single/Multi Class & Homogeneous comparisons among neural-based approaches (Deep, Weightless NN, LVQ, SOM) performed on modern CIC-IDS-2017/2018 datasets. \\ \hline \end{tabular} \label{tab:works} \end{table*} Going more precisely into the set of papers that share with the proposed work the purpose of surveying and/or comparing ML techniques for intrusion detection, we have gathered the prominent papers in Table \ref{tab:works}. The first column contains a pointer to the source; the second column reports the type of experimental analysis (if any); the third column highlights the type of datasets utilized (single/multi-class); the last column provides a brief description of the surveyed material, whereby the qualification ``non-homogeneous" refers to a comparison among techniques belonging to different families, thus, hardly comparable. Going beyond the adoption of novel datasets, we want to highlight the two most significant differences arising between the proposed review and the technical literature: First, to avoid dispersions, we prefer to focus on a specific family of ML techniques, namely the neural networks, so to guarantee more fair comparisons among outcomes. Such a focus allows us to better reveal the surprising behavior of weightless neural networks (traditionally exploited in the field of image classification) which exhibits an extraordinary advantageous accuracy/time complexity trade-off w.r.t. other NN-based methods. Then, we carry out an experimental analysis including performance and time complexity (this latter often neglected in technical literature) about all the described NN techniques; this effort overcomes the limit of gathering findings from various works (where different authors exploit different testbeds exhibiting different performance), thus, it results in a uniform vision of neural methods in the field of intrusion detection. Accordingly, Table \ref{tab:works} helps pinpointing such novel aspects of the present paper, as per last row. \section{Neural-based techniques under scrutiny} \label{sec:nn} In this section we offer a brief recap of neural-based techniques that we then employ in Section V to perform our comparative assessment. We start with Multi-Layer Perceptron (MLP) which represents the basis for implementing ANNs and deep neural networks (DNN). Then, we consider WiSARD, one of the most representative algorithms of weightless neural networks. These typically provide interesting performance results, but have traditionally been applied in domains such as image classification rather than intrusion detection. We examine Learning Vector Quantization (LVQ) methods (with $3$ variants), where the notion of {\em codebook vector} will be introduced. Finally, we take into account the Self-Organizing Maps (SOM) technique. \subsection{Multi-Layer Perceptron} The Multilayer Perceptron is one of the most representative type of feedforward-based ANNs, whereby there are no cycles arising in the connections among nodes. MLPs exhibit a fully connected structure of neurons, where each individual neuron calculates the weighted sum of $n$ inputs, adds a bias term $b$, and then applies an activation function $\phi(\cdot)$ to produce the output $s$, namely \begin{equation} s=\phi \left( \sum_{i=1}^{n}w_i x_i +b \right). \label{eq:neuron} \end{equation} Figure \ref{fig:nn} depicts \textit{i)} (left panel) the model of a single neuron (or single-unit perceptron) implementing (\ref{eq:neuron}), and \textit{ii)} (middle panel) a simplified structure of a typical MLP model with $5$ neurons in the input layer, $3$ neurons in the hidden layer, and $1$ neuron in the output layer. In case of multiple hidden layers, MLP implements a Deep Neural Network (DNN) \cite{bengio} as reported in the right panel. The basic MLP functioning is described next. Input $I_n$ (see Fig. \ref{fig:nn} - middle panel) activates the hidden layer (or layers) by following the forward activation direction, which is what justifies the term {\em feed-forwarding} neural network. Similarly, neurons in the hidden layers feed forward into output neurons, thus, an output value is obtained. It is useful to recall that the activation function is aimed at deciding whether or not a neuron would be activated, introducing some non-linearity into the neuron output. A variety of activation functions exist \cite{glorot} including: step function, linear, sigmoid, hyperbolic tangent, ReLU (Rectified Linear Unit), Softmax and many others. \begin{figure*}[t] \centering \includegraphics[scale=0.65,angle=90]{Images/nn3} \caption{Single Neuron model (left panel). MLP model (middle panel). Deep NN model (right panel)}. \label{fig:nn} \end{figure*} The MLP training stage is achieved through \textit{backpropagation}, a mechanism exploited to adjust weights of neurons aimed at progressively minimizing the error through Gradient Descent (GD), an iterative optimization algorithm useful to find local minima. Precisely, the purpose is to minimize an error function (e.g. least squares): \begin{equation} \mathcal{E}=\sum_{p \in \mathcal{P}} || t_p - s_p ||^2, \end{equation} where $\mathcal{P}$ is the set of training patterns, $t_p$ is the target, and $s_p$ is the output for the example pattern $p$. The weight-updating rule, used to progressively compute the new weight $w_{new}$, is derived by evaluating the gradient $\partial \mathcal{E} / \partial w$, so that: \begin{eqnarray} w_{new}=w+\Delta w, \nonumber \\ \nonumber \\ \Delta w = - \eta \frac{\partial \mathcal{E}}{\partial w} + \alpha \Delta w_{prev}, \end{eqnarray} where: \textit{i)} $\eta$ is the {\em learning rate}, namely a hyperparameter lying in the range $(0,1)$ associated to the step size of the GD procedure (N.B.: too small $\eta$ implies difficulty of convergence, whereas too large $\eta$ could result in indefinite oscillations); \textit{ii)} $\alpha$ is defined as the {\em momentum}, a term lying in the range $(0,1)$ used to weight the influence of each iteration. It is worth noting that, since derivative operations are involved in the backpropagation algorithm, non-linear activation functions (e.g. Sigmoid, ReLU) have to be exploited, whose derivative functions exist and are finite. In our MLP-based experiment we use two types of activation functions: ReLU for all the layers except for the output, and Softmax for the neurons in the output layer. ReLU has been proven to be one of the most effective activation functions when dealing with deep neural networks \cite{relu1,relu2} since it allows the whole network to converge rapidly. Conversely, Softmax is particularly suited for handling multiple classes in the output stage \cite{softmax}. \subsection{Evolved Deep architectures} Deep learning approaches allow to face a problem in a hierarchical way. Lower layers of the model are associated to a basic representation of the problem, whereas higher layers encode more complex aspects. Inputs feeding each layer of a DNN are manipulated through transformations which are parametrized by a number of weights. Although deep approaches are very promising, two main issues remain opened: first, training these architectures requires a significant computational power, and, then, the huge number of hyperparameters makes the tuning process very hard. In the following, we briefly discuss the most recent architectures relying on a deep-based approach. \textbf{Convolutional Neural Networks (CNNs)}: Such a technique \cite{cnn} takes inspiration from the human visual cortex, which embodies areas of cells responsive to particular regions of the visual field. This structure makes CNNs exceptionally suited for applications such as images classification or objects detection. Two main stages characterize the CNN lifecycle: feature extraction and classification. In the first stage, the so-called convolutional filters extract multiple features from the input and encode them in feature maps. The ``convolution'' is the mathematical operation consisting in an element-wise product and sum between two matrices, and has the main drawback of being hugely time consuming. The output of each convolutional layer feeds the activation function layer (e.g. ReLU) which produces an activation map by starting from a feature map. Finally, an optional pooling layer keeps only significant data. On the other hand, the classification stage is composed of a number of fully connected (or dense) layers followed by a Softmax output layer. \textbf{Recurrent Neural Networks (RNNs)}: It is a class of DNNs conceived on the basis of a work of Rumelhart \cite{rnn}, explicitly designed to deal with sequential data. Thus, RNNs are well suited for modelling language (intended as a sequence of interconnected words) in the field of the so-called natural language processing (NLP). The key concept in RNNs is the presence of cycles, which represent the internal memory exploited to evaluate current data with respect to the past. Such a temporal dependency calls for the introduction of time-based hidden states obeying to: \begin{eqnarray} h(t)=\phi(h(t-1),x(t)), \end{eqnarray} with the meaning that an internal state $h$ at time $t$ can be represented in terms of the input at time $t$ and the previous hidden state at time $t-1$. In this way, an RNN is helpful to predict the next element of a time series, or the next word in a sentence based on the number of the previous words. One of the main drawbacks of RNNs is dealing with long-term dependencies connected with transferring information from earlier to later times steps across too long sequences. To tackle this issue, two more sophisticated variants of RNNs have been introduced: LSTM and GRU. \textbf{Long Short-Term Memory (LSTM)}: It is a special RNN architecture \cite{lstm} conceived to learn long-term dependencies, namely, to store information for a long period of time. Basically, an LSTM unit (replacing an ordinary node in the hidden layer) is represented by a cell state in charge of carrying the information, and by three different \textit{gates} aimed at regulating the information flow: \textit{forget}, \textit{input}, and \textit{output} gates. The \textit{forget} gate decides what information keep or discard on the basis of a forgetting coefficient calculated by input data $x(t)$ and the previous hidden state $h(t-1)$; the \textit{input} gate decides how to update the cell state; the \textit{output} gate decides which information has to be passed to the next unit, on the basis of input data and the previous hidden state. For the $i$-th LSTM unit, the hidden state at time $t$ can be expressed as: \begin{eqnarray} h^i(t)=out^i(t) \cdot tanh(c^i(t)) , \end{eqnarray} where $out^i(t)$ is an output gate which tunes the amount of memory, and $c^i(t)$ represents the cell state of LSTM unit $i$ at time $t$. \textbf{Gated Recurrent Unit (GRU)}: It is a lightweight version of LSTM \cite{gru} and has only two gates: \textit{update} gate and \textit{reset} gate. The former plays a similar role of forget and input gates of LSTM; the latter is exploited to decide how many past data to forget. In the GRU model, the hidden state $h^i(t)$, corresponding to the $i$-th GRU unit, can be expressed as a linear interpolation between the hidden state at time $t-1$ and the candidate activation (or hidden state) $\widetilde{h^i}(t)$ viz. \begin{eqnarray} h^i(t)=(1-z^i(t)) h^i(t-1) + z^i(t) \widetilde{h^i}(t), \end{eqnarray} where $z^i(t)$ is the update gate which decides about the updating amount of its candidate activation. \begin{figure}[t] \centering \includegraphics[scale=0.36,angle=90]{Images/discriminator} \caption{Model of a single class discriminator for the WiSARD algorithm.} \label{fig:discri} \end{figure} \subsection{WiSARD} WiSARD\footnote{\textbf{Wi}lkes, \textbf{S}tonham and \textbf{A}leksander \textbf{R}ecognition \textbf{D}evice } is a supervised method \cite{wisard,wisard_new} that was originally conceived for image classification, but has recently been proven to be effective in more general multi-class problems. WiSARD falls under the class of weightless neural networks (WNNs) since it exploits lookup tables, instead of weights, to store the functions evaluated by the individual neurons. WNNs rely on a mechanism inspired to the random access memory (RAM) encoding functionalities, since input data are transformed into binary. This process has a noteworthy benefit in terms of time complexity due to the use of Boolean logic, which can be further improved by exploiting pipelining and parallelism. In short, WiSARD is composed of a set of classifiers (or {\em discriminators}), each one in charge of learning binary patterns associated to a particular class. In turn, a discriminator is composed of a set of neurons, referred to as RAM neurons as depicted in Fig. \ref{fig:discri}. Similarly to conventional RAM circuits, a RAM neuron (a.k.a. $n$-tuple neuron) can be interpreted as a RAM having $2^n$ memory locations addressed by $n$ address lines (inputs) representative of neuron connectivity. During the training stage, each RAM neuron learns the occurrences of $n$-tuple vectors extracted from a training pattern, and stores them in a memory cell (equivalent to a RAM writing operation). Precisely, given $\mu_{a,i}$ the memory cell with address $a$ in the $i$-th RAM (initially empty), the following update rule holds: \begin{equation} \mu_{a,i}=\theta \left( \sum_{{p}\in{\mathcal{P}}} \delta_{a,a_i (p)} \right), \end{equation} where: function $\theta(z)$ amounts to $z$ if $0\le z \le 1$ and to $1$ if $z>1$; $p$ is a pattern defined in the training set $\mathcal{P}$; $a_i (p)$ is the address generated starting from pattern $p$; $\delta$ is the Kronecker delta function, amounting to $1$ if $a=a_i (p)$ and 0 elsewhere. The classification stage (equivalent to a RAM reading operation) consists of classifying an unseen pattern $s$ by assigning $s$ to a class $c$, provided that the correspondent discriminator exhibits the highest output, namely \begin{equation} \argmax_{c} \left( \sum_{i=1}^{K} \mu_{a_i(s),i} \right), \end{equation} whereas, the response of the $c$-th class discriminator on pattern $s$ is: \begin{equation} r_c(s)=\frac{1}{K} \sum_{i=1}^{K} \mu_{a_i(s),i}. \end{equation} Accordingly, since WiSARD is made of a set of discriminators, the overall response of a set of discriminators trained on $N$ classes produces a response vector $\bold{r}(s)=[r_{c_1}(s),\dots,r_{c_N}(s)]$. \subsection{Learning Vector Quantization} Learning Vector Quantization (LVQ) \cite{lvq} directly stems from classical Vector Quantization, a signal-approximation method aimed at representing the input data vectors $x \in \mathbb{R}^n$ through a finite number of {\em codebook} vectors $m_i \in \mathbb{R}^n, i=1,2,\dots,k$. The goal is to find the codebook vector ${m_v}$ that best approximates $x$, usually in terms of Euclidean distance, namely: \begin{equation} v= \argmin_{i} || x - m_i ||. \label{eq:lvq} \end{equation} The main purpose of LVQ is to define {\em class regions} (over the input data space), each one containing a subset of a similarly labeled codebook. Accordingly, it is possible to pinpoint hyperplanes between neighboring codebook vectors defining the so-called {\em quantization regions}. By assuming that all samples of ${x}$ derive from a finite set of classes $S_k$, the idea is to \textit{i)} assign a subset of codebook vectors to each class $S_k$, and \textit{ii)} search for ${m_v}$ having the smallest Euclidean distance from ${x}$. Different versions of LVQs have been introduced in the literature with slight differences, as introduced in the following. \vspace{6pt} \subsubsection{LVQ1} Assume that $x(t)$ is an input sample and $m_i(t)$ contains sequential values of $m_i$ ($t=0,1,2,\dots$). The LVQ1 algorithm allows to find values of $m_i$ in (\ref{eq:lvq}) that asymptotically minimize errors, and is defined by the following set of equations: \begin{eqnarray} &m_v(t+1)&=m_v(t)+\alpha(t)\left[x(t)-m_v(t)\right], \label{eq:lvq_1} \\ &m_i(t+1)&=m_i(t), \label{eq:lvq_2} \label{eq:lvq1} \end{eqnarray} where (\ref{eq:lvq_1}) refers both for cases that $x$ and $m_v$ belong to the same or different classes, (\ref{eq:lvq_2}) holds for $ i \neq v$, and $\alpha(t)$ is the learning rate. This algorithm admits also an optimized version (a.k.a. OLVQ1), where an individual learning rate $\alpha_i$ is assigned to $m_i$, thus, basic $m_v(t+1)$ equation in (\ref{eq:lvq1}) becomes: \begin{equation} m_v(t+1)=\left[ 1- c(t)\alpha_v(t) \right] m_v(t) + c(t)\alpha_v(t)x(t), \end{equation} where $c(t)=+1 [-1]$ if the classification is correct [wrong]. \vspace{6pt} \subsubsection{LVQ2} Differently from the standard procedure implemented in LVQ1, here two codebook vectors $m_i$ and $m_j$ (belonging to the correct and to the wrong class, respectively) are simultaneously updated. In this case, $x$ must fall within a ``window" defined around the hyperplanes of $m_i$ and $m_j$. The correspondent algorithm is defined by the following set of equations: \begin{eqnarray} &m_i(t+1)&=m_i(t)-\alpha(t)\left[ x(t) -m_i(t) \right], \label{eq:lvq2_1} \\ &m_j(t+1)&=m_j(t)-\alpha(t)\left[ x(t) -m_j(t) \right], \label{eq:lvq2_2} \end{eqnarray} where (\ref{eq:lvq2_1}) holds when $x$ and $m_i$ belong to the same class, (\ref{eq:lvq2_2}) holds when $x$ and $m_i$ belong to different classes, and with $m_i$ and $m_j$ being the two closest codebook vectors to $x$. Moreover, $x$ has to fall within a window of relative width $w$ if \begin{equation} \textnormal{min} \left( \frac{e_i}{e_j}, \frac{e_j}{e_i} \right) > k, \end{equation} where $e_i$ and $e_j$ represent, respectively, the Euclidean distances of $x$ from $m_i$ and $m_j$, and $k=\frac{1-w}{1+w}$. \vspace{6pt} \subsubsection{LVQ3} \label{sec:lvq3} This variant of LVQ2 admits the same set of equations (\ref{eq:lvq2_1}), (\ref{eq:lvq2_2}), with the difference that the learning rate is weighted with a parameter $\epsilon$, whose best values are found empirically to lie in the [0.1-0.5] interval of values: \begin{equation} m_h(t+1)=m_h(t)+\epsilon \alpha(t) \left[x(t)-m_h(t)\right], \end{equation} for $k \in {i,j}$ if $x$, $m_i$, and $m_j$ belong to the same class. \subsection{Self-Organizing Maps} SOM takes inspiration from a particular adaptive characteristic that allows the human brain to empower the experience. Specifically, given a physical stimulus (namely, the input) which activates multiple neurons of a certain brain area in parallel, those neurons that are more sensitive to the input stimulus will go about influencing all other neighboring neurons. This biological mechanism has led to designing SOM as a nonlinear mapping of high-dimensional input data onto elements of a low-dimensional array (a.k.a. \textit{lattice}) \cite{kohonen}, according to a principle known as competitive learning. This is different from the classic ANN-based approach, where weights are updated to iteratively minimize errors. In competitive learning, several neurons are fed with the same input (in parallel) and compete to become the possible ``winner" in relation to that particular input. According to this strategy, and assuming that the weight vector of neurons has the same dimensionality as the input, the output neuron activation increases with larger similarity between the weight vector of the neuron and the input \cite{aggarwal}. Precisely, by considering a network composed of $k$ neurons (with $k<<n$ being $n$ the data set size), an input vector $x=\left[ x_1, x_2, \dots, x_n \right]^T \in \mathbb{R}^n$ and a reference (or weight) vector $m_i=\left[m_{i1}, m_{i2}, \dots, m_{in} \right]^T \in \mathbb{R}^n$ associated with neuron $i$, the competitive approach can be summarized according to the following steps: \begin{itemize} \item[] \textit{i)} Compute the smallest Euclidean distance $d=\argmin_{i}$ $\lvert\lvert$ $x$ $-$ m$_i$ $\lvert\lvert$ $\forall i \in (1,\dots,m)$ having the meaning of the activation value for the $i$-th neuron. The neuron having $d$ is declared as winner. \item[] \textit{ii)} The $i$-th neuron is updated according to the following rule: $m_i(t+1)=m_i(t) h(t)\left[ x(t) - m_i(t) \right]$ where $t=(0,1,\dots)$ is an integer discrete time reference, whereas $h(t)$ is the {\em neighborhood function} defined over the lattice points that is typically implemented through a Gaussian kernel (the same as then one exploited for the present experimental analysis): \begin{equation} h(t)=\alpha(t)\cdot \textnormal{exp} \left( - \frac{\lvert\lvert \ell_c - \ell_i \lvert\lvert^2}{2 \sigma^2 (t)} \right), \end{equation} where: $\alpha(t)$ is the learning rate factor, $\ell_c \in \mathbb{R}^2$ and $\ell_i \in \mathbb{R}^2$ are, respectively, the location vectors of neurons $c$ and $i$ mapped on the lattice structure (supposed to be bi-dimensional), and $\sigma(t)$ represents the kernel width. \end{itemize} Although SOM may be considered as the unsupervised counterpart version of LVQ, a common way to exploit SOM for classification purposes is to consider a supervised version (sometimes dubbed as LVQ-SOM \cite{kohonen} and implemented in our analysis) relying on the following consideration: once we know that each training sample $x(t)$ and $m_i(t)$ have been assigned to specific classes, $h(t)$ has to be set to positive if $x(t)$ and $m_i(t)$ belong to the same class, and negative if they belong to different classes, by taking into account that such a rule is applied for each $m_i(t)$ in the neighborhood of the winner. \begin{table}[htp] \centering \caption{Synthetic description of adopted features} \resizebox{.45\textwidth}{!}{ \begin{tabular}{c|l} \textbf{Family} & \multicolumn{1}{c}{\textbf{List of features}} \\ \midrule \multirow{5}[2]{*}{\textbf{Coarse-Grained}} & 1. Source IP Address \\ & 2. Destination IP Address \\ & 3. Source Port \\ & 4. Destination Port \\ & 5. Transport Protocol Type \\ \midrule \multirow{23}[2]{*}{\textbf{Time-Based}} & 6. Flow duration \\ & 7. Average inter-arrival times (IAT) between two flows \\ & 8. IAT standard deviation (std) between two flows \\ & 9. IAT max between two flows \\ & 10. IAT min between two flows \\ & 11. IAT tot between two pkts sent in fwd direction \\ & 12. IAT avg between two pkts sent in fwd direction \\ & 13. IAT std between two pkts sent in fwd direction \\ & 14. IAT max between two pkts sent in fwd direction \\ & 15. IAT min between two pkts sent in fwd direction \\ & 16. IAT tot between two pkts sent in bwd direction \\ & 17. IAT avg between two pkts sent in bwd direction \\ & 18. IAT std between two pkts sent in bwd direction \\ & 19. IAT max between two pkts sent in bwd direction \\ & 20. IAT min between two pkts sent in bwd direction \\ & 21. Avg time a flow was active before becoming idle \\ & 22. Std time a flow was active before becoming idle \\ & 23. Min time a flow was active before becoming idle \\ & 24. Max time a flow was active before becoming idle \\ & 25. Avg time a flow was idle before becoming active \\ & 26. Std time a flow was idle before becoming active \\ & 27. Min time a flow was idle before becoming active \\ & 28. Max time a flow was idle before becoming active \\ \midrule \multirow{6}[2]{*}{\textbf{Flow-Based}} & 29. Flow byte rate \\ & 30. Flow pkt rate \\ & 31. Avg no. of pkts in a sub-flow in fwd direction \\ & 32. Avg no. of pkts in a sub-flow in bwd direction \\ & 33. Avg no. of bytes in a sub-flow in fwd direction \\ & 34. Avg no. of bytes in a sub-flow in bwd direction \\ \midrule \multirow{20}[2]{*}{\textbf{Packet-Based}} & 35. Tot pkts in the fwd direction \\ & 36. Tot length of pkts in the fwd direction \\ & 37. Avg length of pkts \\ & 38. Std length of pkts \\ & 39. Variance length of pkts \\ & 40. Avg length of pkts in the fwd direction \\ & 41. Std length of pkts in the fwd direction \\ & 42. Max length of pkts in the fwd direction \\ & 43. Min length of pkts in the fwd direction \\ & 44. Tot pkts in the bwd direction \\ & 45. Tot length of pkts in the bwd direction \\ & 46. Avg length of pkts in the bwd direction \\ & 47. Std length of pkts in the bwd direction \\ & 48. Max length of pkts in the bwd direction \\ & 49. Min length of pkts in the bwd direction \\ & 50. Avg no. of pkt bulk rate in fwd direction \\ & 51. Avg no. of pkt bulk rate in bwd direction \\ & 52. Fwd pkt rate \\ & 53. Bwd pkt rate \\ & 54. Min segment size in fwd direction \\ \midrule \multirow{6}[2]{*}{\textbf{Byte-Based}} & 55. Avg no. of byte rate in fwd direction \\ & 56. Avg no. of byte rate in bwd direction \\ & 57. No. of bytes sent in init win in fwd direction \\ & 58. No. of bytes sent in init win in bwd direction \\ & 59. Tot bytes used for headers in fwd direction \\ & 60. Tot bytes used for headers in bwd direction \\ \midrule \multirow{19}[2]{*}{\textbf{Flag-Based}} & 61. No. of times URG flag set in fwd direction \\ & 62. No. of times PSH flag set in fwd direction \\ & 63. No. of times FIN flag set in fwd direction \\ & 64. No. of times SYN flag set in fwd direction \\ & 65. No. of times RST flag set in fwd direction \\ & 66. No. of times ACK flag set in fwd direction \\ & 67. No. of times URG flag set in bwd direction \\ & 68. No. of times PSH flag set in bwd direction \\ & 69. No. of times FIN flag set in bwd direction \\ & 70. No. of times SYN flag set in bwd direction \\ & 71. No. of times RST flag set in bwd direction \\ & 72. No. of times ACK flag set in bwd direction \\ & 73. PSH flag count \\ & 74. FIN flag count \\ & 75. SYN flag count \\ & 76. RST flag count \\ & 77. ACK flag count \\ & 78. ECE flag count \\ \bottomrule \end{tabular}% } \label{tab:superfeatures}% \end{table}% \begin{table*}[t] \centering \caption{Optimized hyperparameters for the exploited algorithms.} \small \renewcommand{\arraystretch}{1.35} \begin{tabular}{|p{2.1cm}|p{8cm}|} \hline \textbf{Algorithm} & \textbf{Optimized hyperparameters and models info} \\ \hline MLP-$1$, Deep-$2$, Deep-$3$ & $\cdot$ Stochastic Gradient Descent with adaptive hyperparams. (Adam version - \cite{adam}) \\ & $\cdot$ LR (learn. rate)=$0.001$ \\ & $\cdot$ Number of weights=$2000$ \\ & $\cdot$ Exp. Decay (first moment estimate)=$0.9$ \\ & $\cdot$ ReLU activation function \\ & $\cdot$ Neurons per hidden layer: MLP-$1$($26$); Deep-$2$($23$,$10$); Deep-$3$($20$,$16$,$11$) \\ \hline Convolutional & $\cdot$ $7$ filters $(4x1)$, $8$ neurons fully connected \\ & $\cdot$ $1$ Pooling layer with Pooling size = 2 \\ & $\cdot$ $1$ Dropout layer with Dropout rate = 0.3 \\ & $\cdot$ ReLU activation function \\ \hline Recurrent-type & $\cdot$ $18$ Recurrent units (RNN), $10$ neurons fully connected \\ & $\cdot$ $6$ LSTM units, $8$ neurons fully connected\\ & $\cdot$ $8$ GRU units, $10$ neurons fully connected \\ \hline WiSARD & $\cdot$ Batch Size=$100$ \\ & $\cdot$ Resolution (in bit) per neuron: $8$ \\ \hline LVQ(1,2,3) & $\cdot$ Batch Size=$100$ \\ & $\cdot$ LR=$0.3$ \\ & $\cdot$ Codebook Vectors=$20$ \\ & $\cdot$ Window Size (for LVQ$2$ and LVQ$3$)=$0.3$ \\ & $\cdot$ $\epsilon$ (for LVQ$3$)=$0.1$ \\ \hline SOM & $\cdot$ Batch Size=$100$ \\ & $\cdot$ LR=$0.3$ \\ & $\cdot$ Hexagonal Topology with Neighborhood Size = $8$ \\ & $\cdot$ Neighborhood Function: Gaussian \\ \hline \end{tabular} \label{tab:hyperparams} \end{table*} \section{The experimental Datasets} \label{sec:dataset} In this section we present further details about datasets employed in our experimental analysis. As already remarked in Section \ref{sec:rw}, the datasets must convey the most recent information about a variety of cyber attacks across data networks. We adopted datasets released from CIC \cite{cic}, and precisely: the {\em DDoS } dataset, containing traffic relating to distributed denial of service attacks designed to saturate network resources; the {\em Portscan} dataset, including attempts of Portscan, a technique used to discover open ports on network devices; the {\em WebAttack} dataset which encompasses various malicious traffic ranging from Cross-Site Scripting to Sql Injection; the {\em TOR} dataset, a collection of network traffic traversing the anonymous TOR circuit often conveying malicious information; and the {\em Android} dataset, embedding a number of mobile (Android-based) adwares. These datasets have been used to perform two kinds of neural-based analyses: a {\em single-class} analysis, aimed at classifying the network traffic as benign or malign (binary information); and a {\em multi-class} analysis, aimed at distinguishing more classes of attacks. Each dataset has been cleaned and re-balanced through a Python routine designed from scratch, and contains $2\cdot10^4$ instances and $78$ features, which are then grouped in $6$ macro-classes, as indicated in the following (refer to the Table \ref{tab:superfeatures} for an exhaustive list of features): \begin{itemize} \item \textbf{Coarse-grained features:} Source and Destination Port, Protocol Type, Source and Destination IP Address; \item \textbf{Time-based features:} Backward/Forward inter-arrival times between two flows, duration of active flow (mean, std, min, max), duration of an idle flow (mean, std, min, max), etc.; \item \textbf{Flow-based features:} Length of a flow (mean, min, max, etc.); \item \textbf{Packet-based features:} Backward/Forward number of packets in a flow, Backward/Forward length of packets in a flow (mean, std, min, max, etc.); \item \textbf{Byte-based features:} Backward/Forward number of bytes in a flow, Backward/Forward number of bytes used for headers, etc.; \item \textbf{Flag-based features:} Number of packets with active TCP/IP flags (SYN, FIN, PUSH, RST, URG, etc.). Please note that, for example, feature $62$ ($68$) indicates the no. of times the PSH flag is set in the forward (backward) direction, whereas feature $73$ indicates the overall number of packets containing such a flag. \end{itemize} These features allow to derive statistical information that cannot be hidden in a possible malicious flow. Let us consider, for instance, a DDoS attack. This is typically designed to overwhelm the resources of a target network \cite{ddos1bis,ddos2} by conveying legitimate information (e.g. trivial HTTP requests in case of an application-layer DDoS attack) which would pass unnoticed to a classic signature-based detection systems. However, DDoS attacks are designed to be a coordinated effort where multiple, malicious entities (a.k.a. {\em bots}) send few, tiny packets to the target. Similarly, the structure of a Portscan attack, characterized by a very quick scan of the victim's destination port by the network attacker, can be learned by crossing information of destination port and time-based information. \begin{figure*}[t!] \centering \begin{tabular}{cc} \subfloat[]{\includegraphics[scale=0.51]{Images/single-dd-perf-colab2}} \hspace{2.5mm} \subfloat[]{\includegraphics[scale=0.51]{Images/single-ps-perf-colab2}} \hspace{2.5mm} \\ \subfloat[]{\includegraphics[scale=0.51]{Images/single-wa-perf-colab2}} \hspace{2.5mm} \subfloat[]{\includegraphics[scale=0.51]{Images/single-tor-perf-colab2}} \hspace{2.5mm} \end{tabular} \caption{Performance in terms of Accuracy/F-Measure for different single-class datasets: (a) DDoS; (b) Portscan, (c) WebAttack, (d) TOR.} \label{fig:perf_single} \end{figure*} \section{Experimental-based Assessment} \label{sec:experim} The main purpose of our experimental analysis is to compare the neural techniques introduced in Sect. \ref{sec:nn} across the datasets described in Section IV. Aimed at a fair comparison, we adopt a $10$-fold cross validation for each experiment. The model structure for each algorithm and the pertinent hyperparameters are summarized in Table \ref{tab:hyperparams}. \noindent The whole assessment comprises: \begin{itemize} \item \textbf {Performance analysis}: obtained by evaluating two metrics typically used in the field of traffic classification \cite{accuracy2,tnsm-perf}, viz. \SubItem {\em Accuracy}: ratio of correctly predicted observations to the total, calculated by \begin{equation} \frac{TP+TN}{TP+TN+FP+FN}; \end{equation} \SubItem {\em F-Measure}: an indicator of a per-class performance, calculated by \begin{equation} 2 \cdot \frac{\textnormal{Precision} \cdot \textnormal{Recall} }{\textnormal{Precision}+\textnormal{Recall}}, \end{equation} where Precision is the ratio of correctly classified traffic over the total predicted traffic in a class, and Recall is the ratio of correctly classified traffic over all ground truth traffic in a class. \item \textbf {Time complexity analysis}: derived by measuring the whole classification process (including training time) as the number of instances grows from $10^3$ to $2\cdot10^4$. \end{itemize} We perform the overall analysis on a PC equipped with Intel CoreTM i5-7200U CPU@ 2.50GHz CPU and 16 GB of RAM. For the sake of convenience, we split our analysis in two: the single-class and the multi-class cases. \begin{figure*}[t!] \centering \begin{tabular}{cc} \subfloat[]{\includegraphics[scale=0.47]{Images/single_perf_var_inst_ddos}} \hspace{2.5mm} \subfloat[]{\includegraphics[scale=0.47]{Images/times_single_ddos}} \hspace{2.5mm} \\ \subfloat[]{\includegraphics[scale=0.47]{Images/single_perf_var_inst_ps}} \hspace{2.5mm} \subfloat[]{\includegraphics[scale=0.47]{Images/times_single_ps}} \hspace{2.5mm} \end{tabular} \caption{Single-class (DDoS): (a) Average Accuracy vs. dataset size; (b) Classification Time vs. dataset size; Single-class (Portscan): (c) Average Accuracy vs. dataset size; (d) Classification Time vs. dataset size.} \label{fig:aveacc_time} \end{figure*} \subsection{Single-Class Analysis} We start by evaluating the performance of the different neural-based techniques by considering four single-class datasets ({\em DDoS}, {\em Portscan}, {\em WebAttack}, and {\em TOR}), reporting accuracy and F-measure in Figures \ref{fig:perf_single}(a), \ref{fig:perf_single}(b), \ref{fig:perf_single}(c), and \ref{fig:perf_single}(d), respectively. The choice of four completely different datasets (representative of four substantially different network attacks) is useful to verify the effectiveness of the tested algorithms and their relationships with the data. Among classic ANN-based algorithms we distinguish between deep versions (Deep-$2$, Deep-$3$) and non-deep ones (MLP-$1$) whose detailed structure is reported in Table \ref{tab:hyperparams}. MLP-$1$ refers to a standard MLP with $3$ layers: $1$ input layer, $1$ hidden layer, and $1$ output layer. On the other hand, deep versions are indicated by Deep-$2$ ($1$ input layer, $2$ hidden layer, $1$ output layer) and Deep-$3$ ($1$ input layer, $3$ hidden layer, $1$ output layer). In order to compare algorithms with similar performances, MLP-$1$, Deep-$2$ and Deep-$3$ have been set with the same number of weights ($2k$). This is about one order of magnitude smaller than the dataset size, according to what is recommended in the literature \cite{lisboa,prasad08}. We also note that the number of weights for MLP-$1$, Deep-$2$ and Deep-$3$ directly results from the different number of neurons chosen per each hidden layer, namely: $26$ neurons for MLP-1, $23$ and $10$ neurons for the two hidden layers of Deep-2, and $20$, $16$, and $11$ neurons for the $3$ hidden layers of Deep-3 (see also Table \ref{tab:hyperparams}). As concerns the evolved deep models (CNN, RNN, LSTM, GRU), details about their structures are available in Table \ref{tab:hyperparams}. Also for these approaches, the choice of a particular structure (e.g. the number of filters in CNN, the number of recurrent units in RNN, and so forth), is aimed at obtaining a number of weights comparable with MLP-$1$, Deep-$2$, and Deep-$3$ so to have a fair comparison. In our analysis, the MLP-based versions (MLP-$1$, Deep-$2$ and Deep-$3$) and the evolved deep techniques (CNN, RNN, LSTM, GRU) exhibit good values of average accuracy (all around $0.99$) for all the four examined datasets (panels of Fig. \ref{fig:perf_single}). Similarly, for all the aforementioned algorithms and for each dataset, F-measure exhibits high values, indicating a very negligible fraction of false positives and false negatives. Similar high performance is exhibited by Wisard for all the datasets with a slight exception of Portscan Dataset. By contrast, LVQs and SOM methodologies have lower performance and seem to suffer from the presence of more false positives and false negatives. This is visible for the Portscan dataset (Fig. \ref{fig:perf_single}(b)) that exhibits an oscillating F-measure, which can be ascribed to the different codebook vectors obtained when considering different input datasets. In particular, competitive learning methods seem suffer from the particular type of attack dataset. In fact, the Euclidean distance (which is used as the main metric within the discussed competitive learning approaches) may not perfectly capture the properties of various datasets, being they structurally different. This is due to the fact that Euclidean distance is a not scale invariant measure, thus, it has difficulty to deal with vector components having different dynamic range. This is also the reason why the $3$ variants of LVQ can behave slightly differently when considering diverse datasets. Another useful analysis is aimed at evaluating the impact of dataset size on performance. For the sake of compactness, we choose DDoS and Portscan as benchmark datasets, being DDoS and Portscan representative of two completely different and well structured network attacks. Precisely, we evaluate the average accuracy (between DDoS/Portscan and benign classes) against an interval of dataset size varying between $10^3$ and $2\cdot10^4$ instances. The results shown in Figures \ref{fig:aveacc_time}(a) and \ref{fig:aveacc_time}(c) provide a clear indication that: \textit{i)} both ANNs and WiSARD exhibit very stable performance as dataset size varies; \textit{ii)} LVQ shows some minor fluctuations, with an average accuracy that is just slightly under $0.9$ in few cases. In this case, fluctuations can be ascribed to the codebook size that would require heuristical adjustments as the dataset size varies. For the sake of fairness, the performance comparison must be complemented by a time-complexity analysis, as shown in Figs. \ref{fig:aveacc_time}(b-d). Therein, classification time (in seconds) is plotted against the number of instances (from $10^3$ to $2\cdot10^4$). For both experiments (DDoS dataset in \ref{fig:aveacc_time}(b) and Portscan dataset in \ref{fig:aveacc_time} (d)) we can reasonably recognize three slots in the Y axis: the first one, ranging from $10^3$ to $15\cdot10^4$ seconds, where MLP-$1$, Deep-$2,3$ and evolved deep architectures (CNN, RNN, LSTM, GRU) operate (slowest algorithms); the second one, ranging from about $10$ to $10^2$ seconds which includes WiSARD (medium-fast algorithm); the third one, ranging from about $1$ to $5$ seconds, including LVQ$1$, LVQ$2$, LVQ$3$, and SOM (faster algorithms). We are not surprised that deep networks are up to $2$ orders of magnitude slower w.r.t. other techniques, due to the fully connected neurons between each layer. As regards the evolved deep architectures, time complexity is typically associated to the adoption of more sophisticated structures such as the convolutional layers (CNNs), or mechanisms to retain the internal memory states (RNN, LSTM, GRU). \begin{figure*}[t!] \centering \begin{tabular}{cc} \subfloat[]{\includegraphics[scale=0.51]{Images/multi-perf-accu-colab2}} \hspace{2.5mm} \subfloat[]{\includegraphics[scale=0.51]{Images/multi-perf-fmeas-colab2}} \end{tabular} \caption{Performance analysis for a $4$-classes dataset: (a) Accuracy, (b) F-Measure.} \label{fig:perf_multi} \end{figure*} \begin{figure*}[t!] \centering \begin{tabular}{cc} \subfloat[]{\includegraphics[scale=0.5]{Images/multi_perf_var_inst-colab}} \hspace{2.5mm} \subfloat[]{\includegraphics[scale=0.5]{Images/times_multi-colab}} \end{tabular} \caption{Multi-class dataset: (a) Average Accuracy vs. dataset size; \\ ~~~ (b) Classification Time vs. dataset size.} \label{fig:multi_aveacc_time} \end{figure*} On the other hand, approaches based on competitive learning (LVQs, SOM) are faster since only the winner neurons are enabled to update their weights, although this comes at the cost of a lower accuracy. Surprisingly, the best trade-off between accuracy and time complexity is offered by WiSARD. Its RAM-based structure, in fact, allows a fast learning stage since it deals with binary information regardless on data dimension. In terms of time complexity, the feed-forward incremental learning scheme implemented in WiSARD is more advantageous than classic backpropagation, requiring many iterations to converge. \begin{figure*}[t!] \centering \begin{tabular}{cc} \subfloat[]{\includegraphics[scale=0.38,angle=90]{Images/mse_single-colab3}} \hspace{3mm} \subfloat[]{\includegraphics[scale=0.5]{Images/mse_multi-colab}} \end{tabular} \caption{MSE analysis when introducing more sophisticated deep models (CNN, RNN, LSTM, GRU). Single-class (DDoS benchmark dataset) (a), Multi-class (DDoS-Portscan-Adware-Benign dataset) (b).} \label{fig:mse_a2} \end{figure*} \subsection{Multi-Class Analysis} Multi-class analysis is useful to analyze how the various algorithms react when dealing with different classes of traffic. With this aim, we built a $4$-class dataset by mixing (in a balanced way) three malicious classes (DDoS, Portscan, and Adware) with a Benign class. The rationale behind this choice is to take into account a mix of peculiar threats. As regards the performance analysis, for the sake of readiness, we show multi-class accuracy and F-measure separately in Figs. \ref{fig:perf_multi}(a) and \ref{fig:perf_multi}(b), respectively. As a general trend, we observe a satisfactory classification performance by MLP and Deep algorithms. WiSARD exhibits good performance in classifying DDoS and Portscan ($0.9957$ and $0.9952$ accuracy, respectively), but is poor in classifying Adware and Benign classes ($0.784$ and $0.782$ accuracy, respectively). The reason is to be found behind the structural difference between those different types of attacks. DDoS and Portscan are both highly ``structured" attacks. The former can be characterized in terms of high rate of messages that a bot sends to a victim; Portscan hides continuous ping-based requests towards a target in order to unveil possible open ports. By contrast, Adwares can be easily confused within a benign flow, since they just convey annoying banners, as often occurs also within legitimate web portals. The situation changes drastically when we look at the remaining algorithms (LVQs and SOM), where false positives have high weight especially for Portscan, Adware, and Benign classes, as shown in Fig. \ref{fig:perf_multi}(b). Also, the F-measure is often below $0.4$ in case of Adware and Benign classes. With respect to the single-class case, here, the effects produced by the codebook class assignment and peculiarity of Euclidean measure are amplified. Finally, among competitive-based approaches, LVQ-$3$ exhibits the best performance, due to the introduction of the empirical parameter $\epsilon$ (see Sect. \ref{sec:lvq3}), which helps to better regulating the distance between the data and the pertinent codebook vectors. This notwithstanding, all the considered techniques exhibit fairly stable accuracy averages, across the whole range of dataset sizes (from $10^3$ to $2\cdot10^4$ instances), as revealed by Fig. \ref{fig:multi_aveacc_time}(a). As expected, the average accuracy in all cases pertaining the multi-class experiment is slightly lower than their single-class counterpart, due to the fact that classifying more than two classes is a more challenging task. Let us now discover if the multi-class analysis has an impact on the time complexity of the considered algorithms. Figure \ref{fig:multi_aveacc_time}(b) shows how the order of magnitude in classification times per algorithm is similar w.r.t. the case of single-class analysis. As to be expected, the slight increase in classification time going from single to multi-class cases can be ascribed to the higher number of different traffic flows to be classified. For example, along the varying dataset size $\left[ 10^3, 2\cdot10^3, 5\cdot10^3, 10^4, 2\cdot10^4 \right]$, WiSARD exhibits the following (approximated) classification times: $\left[ 8.047, 12.24, 30.731, 53.474, 104.783 \right]$ seconds in the single class case, and $\left[ 8.389, 15.058, 31.831, 61.958, 119.848 \right]$ seconds in the multi-class case. Once again, WiSARD appears to provide the optimal trade-off between performance needs and time complexity issues. \subsection{General Considerations} A number of interesting considerations may be derived from our comparative analysis. First, not all neural-based techniques are equally applicable to network intrusion detection, particularly when performance is the key issue. ANN approaches (including modern deep-based methods) tend to offer noteworthy accuracy, both in single-class and multi-class datasets. Unfortunately, though, accuracy comes at the expenses of time complexity, which will demand for deep-based techniques to rely on specialized GPU-based hardware. Moreover, as an auxiliary investigation pertaining the deep approach, we evaluate the impact of the updating weight mechanism on the overall performance, expressed through the Mean Square Error (MSE). The behavior is shown in Figs. \ref{fig:mse_a2}(a) and \ref{fig:mse_a2}(b) for the single and multi-class datasets, respectively, evaluated over $100$ epochs. Such analysis reveals that most techniques exhibit limited fluctuations around the median value of MSE and a quite low MSE value. The only exception is given by CNN where the higher MSE is reasonably due to the complexity of the convolution operation. Similar considerations raised in a bio-informatic study \cite{cnn_fluct} where only MLP and CNN techniques have been compared. Detailed values are reported in Table \ref{tab:mse_results}, in terms of median and inter-quartile range (difference between third and first quartile) values. On average, the most ``stable'' techniques are the classic Deep-$2$ and Deep-$3$ architectures. The addition of a bit more sophisticated structure (e.g. convolutional layer for CNN, LSTM/GRU units, and so forth) can translate into MSE fluctuations due to the presence of additional hyperparameters to tune. Obviously, such fluctuations directly reflect the internal structure of each deep technique and can be more (e.g. CNN) or less (e.g. RNN) pronounced. \begin{table}[ht] \centering \caption{ Median and IQR values (MSE analysis) for deep-based techniques} \begin{tabular}{c c c c c } & \multicolumn{2}{c}{\textbf{Median}} & \multicolumn{2}{c}{\textbf{IQR}} \\ \cmidrule{1-5} \textbf{Technique} & \multicolumn{1}{c}{Single-Class} & \multicolumn{1}{c}{Multi-Class} & \multicolumn{1}{c}{Single-Class} & \multicolumn{1}{c}{Multi-Class} \\ \midrule Deep-2 & 1.5$\cdot$ 10$^{-3}$ & 2.02 $\cdot$ 10$^{-2}$ & 1.8$\cdot$ 10$^{-3}$ & 7 $\cdot$ 10$^{-3}$ \\ Deep-3 & 7.4$\cdot$ 10$^{-4}$ & 1.45 $\cdot$ 10$^{-2}$ & 1.6$\cdot$ 10$^{-3}$ & 6.1$\cdot$ 10$^{-3}$ \\ CNN & 1.74 $\cdot$ 10$^{-2}$ & 6.2 $\cdot$ 10$^{-2}$ & 4.1$\cdot$ 10$^{-3}$ & 1.19$\cdot$ 10$^{-2}$ \\ RNN & 1.4 $\cdot$ 10$^{-3}$ & 2.06 $\cdot$ 10$^{-2}$ & 2.1$\cdot$ 10$^{-3}$ & 6.6$\cdot$ 10$^{-3}$ \\ LSTM & 1.8 $\cdot$ 10$^{-3}$ & 3.02 $\cdot$ 10$^{-2}$ & 2.9$\cdot$ 10$^{-3}$ & 6.7 $\cdot$ 10$^{-3}$ \\ GRU & 2.4 $\cdot$ 10$^{-3}$ & 2.45 $\cdot$ 10$^{-2}$ & 2$\cdot$ 10$^{-3}$ & 8.1 $\cdot$ 10$^{-3}$ \\ \hline \end{tabular}% \label{tab:mse_results}% \end{table}% Remarkably, deep-learning techniques could find interesting application in the network intrusion management field when the training set exhibits slow time dynamics. In this case, the training operation (being time/resource consuming) could be performed only once (or performed rarely across the time). As regards competitive learning techniques (LVQ in the $3$ variants and SOM), pros and cons are (almost) reversed w.r.t. ANN algorithms. In the case of single-class analysis, a dependency on the type of dataset is highlighted (better performance in DDoS dataset than in Portscan). This is reasonably due to the fact that different inputs produce different mappings with codebook vectors. As to be expected, this effect is further amplified in multi-class datasets, where false positives and false negatives lead to unstable f-measure figures (Fig. \ref{fig:perf_multi} (b)). However, the competitive learning algorithms exhibit very appealing time complexity figures (up to $3$ orders of magnitude lower than ANNs), thanks to their approach to taking into account only the ``winner" neurons during the whole classification process. Accordingly, cooperative techniques could find useful application in highly time-variant intrusion detection settings, where it is crucial to quickly adapt to the dataset variations. Possibly, they can operate an early (even rough) detection to be refined later by means of other algorithms. Finally, an unexpected finding is offered by WiSARD that, through its weightless mechanism, provides the best trade-off between performance (accuracy/F-measure) and time complexity, in both single and multi-class cases. This outstanding behavior is mainly due to two aspects: first, the binarization scheme (jointly with the RAM-like neurons structure) adopted by WiSARD allows to handle multivariable data in a fast way. Then, the training stage follows an incremental approach since each sample reinforces the past knowledge in updating the network state; this implies a fast convergence and makes WiSARD particularly suitable in domains where online learning is crucial. What is even more interesting is that WiSARD has hardly ever been considered in the field of traffic flow classification, while it appears to be a very interesting candidate to be exploited in intrusion detection. This WNN-based approach should certainly be considered as a promising alternative to existing methods, particularly for its potential to meet the near-real-time constraints involved in NIDS classification problems. \section{Conclusion} \label{sec:conclusion} This work explores the applicability of prominent neural-based techniques in network intrusion detection. We carry out an experiment-based comparison to quantify performance and trade-off achievable with each solution. Our aim to perform a fair comparison has directed our investigation to focus on artificial neural networks (ANN). This was to avoid the typical issues arising when comparing ML methods relying on different rationale (e.g. ANN vs. SVM vs. Decision Trees). In the related work section, we have provided pointers to numerous other surveys, illustrating similarities (in aims) and differences (in methodologies). The key peculiarity of our paper is its experimental-based approach to reviewing alternative ANN options. We based our evaluation on modern datasets (CIC-IDS-2017/2018), while most of the earlier experimental results are based on the outdated KDD$99$ dataset (reflecting network attack issues that have largely been solved). Our review provides useful performance (in terms of accuracy and F-measure) and time complexity data, providing the basis for a trade-off analysis across different ANNs such as deep networks or competitive learning-based networks. To add value to our study, we wanted to consider also methods that have not typically been employed in intrusion detection, particularly the weightless neural networks (WNNs). The outcomes reveal a number of interesting findings. \textit{i)} ANN-based approaches (including deep networks) are characterized by outstanding performance in almost all cases (as to be expected). Yet, they suffer the drawback of being slow due to the underlying backpropagation algorithm, which is typically slow to converge. \textit{ii)} Neural-based techniques relying on a competitive learning approach (LVQ$1$, LVQ$2$, LVQ$3$, SOM) overturn this perspective, thanks to a much reduced time complexity (due to the winner-neuron mechanism). However, this comes with a lower performance when different datasets are considered (due to the different mapping mechanism between input and codebook vectors). \textit{iii)} The WiSARD algorithm (representative of WNNs) exhibits a surprisingly best trade-off in terms of performance and time complexity, making it an appealing candidate to operate in conjunction with intrusion detection systems. The proposed analysis could be extended in several ways. The first (and perhaps natural) direction is to better investigate the potential of weightless neural networks in the context of network intrusion detection. Beyond WiSARD, in fact, other WNN algorithms such as Probabilistic Logic Node (PLN), Goal Seeking Neuron (GSN), or General Neural Unit (GNU) could reveal noteworthy properties when applied in this field. Then, we would suggest to explore how the addition of a feature selection (FS) pre-processing stage would reduce time complexity. This could be particularly advantageous for deep techniques (the most critical in terms of time constraints), even if the adoption of a non well designed FS strategy could result in a further computational overhead. Finally, having identified pros and cons of neural-based techniques in the field of intrusion detection, an engine which allows to automatically select (or combine) the NN-based strategies best fitting the underlying network environment (e.g. hugely vs. scarcely time-variant traffic profiles) can be designed. This latter point could have intriguing implications onto prospective $6G$ scenarios which, according to the network experts, will be characterized by automatic service provisioning, intelligent resource management, and smart network adjustments. \bibliographystyle{unsrt}
{'timestamp': '2020-09-22T02:01:04', 'yymm': '2009', 'arxiv_id': '2009.09011', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09011'}
arxiv
\section{Introduction} Most of the real world is governed by complex and chaotic dynamical systems, vibration engineering, cardiac arrhythmia and stock prices. All of these dynamical systems pose a challenge in modelling via using neural networks.\\ There are several types of neural networks, such as feed-forward, CNN (Convolutional Neural Networks), RNN (Recurrent Neural Networks), Autoencoders, etc. Feed-forward and convolutional neural networks are made up of neurons connected in layers, which take inputs from the previous layer and pass on the output to the next layer. Recurrent neural networks differ from both feed-forward and convolutional neural networks as the neurons in them are connected in a “recurrent” manner, and may have feedback loops between the sets of neurons. The feedback loop allows the network additional capability to capture temporal dynamics and learn time series data. Reservoir computing, which is a subset of recurrent neural networks, was first proposed by Jaeger \cite{jaeger}. In the reservoir computing approach\cite{jaeg-haas,herzog}, the large pool of neurons act as a “reservoir” where the input data is imparted a dynamic behaviour, to generate output. \\ The primary motivation behind this research is to model complex dynamics without relying on a recurrent neural network by including a temporal part in an activation function. The activation function fluctuates based on a time-dependent parameter that can be generated in different ways such as the logistic or cubic map. \begin{figure} \begin{center} {\includegraphics[height=12.5cm]{szder.png}} \end{center} \caption{Activation Function and its derivative for $\phi(t)=1$, $\phi(t)=2.8$.}\label{fszd} \end{figure} \section{Spatio-Temporal Activation Function}\label{lgnn} Each type of network may differ in structural topology, but all share the same basic building block - the neuron and an activation function. In neural networks, the activation function acts as a way to map the weighted sum of the inputs going into each neuron to a useful output. There are four major types of activation functions: binary step, sigmoid, tanh, and ReLU. The neural networks vary in different ways, for example, the sigmoid function generates output that is normalised between $0$ and $1$, while tanh is normalised between $-1$ and $1$. In the this research work, a new spatio-temporal activation function, similar to the sigmoid activation function, is proposed, which is a function of the sum of weighted inputs, $z$, and also of a temporal term. The proposed spatio-temporal function $S(z,t)$ is \begin{equation} \label{esz} S(z,t) = \frac{1}{1-exp(-\phi(t)z)} \end{equation} The derivative of $S(z,t)$ being \begin{equation} \label{eszd} \frac{dS(z, t)}{dz}=\phi(t)S(z)(1-S(z)) \end{equation} The derivative of the new activation function, $S(z,t)$, is similar to the Gaussian probability distribution, and the temporal term $\phi(t)$ plays the role of varying its standard deviation. Figure \ref{fszd} shows the activation function and its derivative for constant $\phi(t)=1$ and $\phi(t)=2.8$. The temporal term $\phi(t)$ in the present case is a linear function of a time-dependant parameter, $\alpha(t)$, as follows \begin{equation} \label{newequation} \phi(t) = \phi_0+k\alpha(t) \end{equation} where $\phi_0$ and $k$ are constants. Figure \ref{diagram} shows the schematic of the activation function.\\ In this case, $\alpha(t)$ can follow the dynamics of the logistic map \cite{salis} based on the growth parameter $r$ as follows \begin{equation}\label{elog1} \alpha (t+1) = r \alpha(t)(1-\alpha(t)) \end{equation} The function $f(\alpha)=r\alpha(1-\alpha)$ is the logistic map, $f:[0,1] \mapsto[0,1]$, where $3.6<r<4$, giving rise to chaotic dynamical behaviour as shown in Figure \ref{flog}. It should be noted that Eqn. \ref{elog1} is the time derivative of $\alpha(t)$ while Eqn. \ref{eszd} is the derivative of the sigmoid function, and both follow a similar functional form, one in time domain $t$ and other in input domain $z$. Interestingly, the derivative of the activation function in Eqn. \ref{eszd} is also the logistic map. \begin{figure} \begin{center} {\includegraphics[height=3cm]{logistic_data.png}} \end{center} \caption{Chaotic dynamical plot of $\alpha(t)$ for $r=4 $.}\label{flog} \end{figure} \begin{figure} \begin{center} {\includegraphics[height=6cm]{logistic_bifurcation.png}} \end{center} \caption{Bifurcation diagram of the logistic map}\label{bifurcation} \end{figure} \\The temporal function $\phi(t)$ is normalised between $(\phi_{min},\phi_{max})$ as follows \begin{equation}\label{enorm} \phi(t) = \phi_{min} + \frac{(\alpha(t) -\alpha_{min})}{(\alpha_{max} - \alpha_{min})}(\phi_{max}-\phi_{min}) \end{equation} where $\alpha_{max}$ and $\alpha_{min}$ are the maximum and minimum value taken by function $\alpha(t)$. \section{Response of spatio-temporal activation function} In the case of the logistic map, when $r = 4$, $\alpha_{min}$ is 0 and $\alpha_{max}$ is 1. These values vary and can be read from the logistic bifurcation diagram as shown in Figure \ref{bifurcation}. The value of $\phi_{max}$ and $\phi_{min}$ depends on the range of the data you want to generate. Increasing the range between the $\phi_{max}$ and $\phi_{min}$ will increase the range of the neuron's output. For example, with $\alpha_{max} = 1$ and $\alpha_{min}=0$, the function $\phi(t)$ is \begin{equation}\label{enorm} \phi(t) = \phi_{min} + \alpha(t)(\phi_{max}-\phi_{min}) \end{equation} Figure \ref{fanno} shows the output from a neuron displaying the chaotic behaviour using $\phi_{max} = 1.1$ and $\phi_{min} = 0.9$. The standard deviation corresponding to this range of $\phi_{max}$ and $\phi_{min}$ is found to be $0.013$. Figure \ref{standard} shows the relationship between the standard deviation of the output generated and the difference between $\phi_{max}$ and $\phi_{min}$. By increasing the range of the bounds $(\phi_{max} - \phi_{min})$, the chaotic behaviour of the resulting output of the neuron varies with larger deviations around the mean, e.g. for $\phi_{max} = 1.2$ and $\phi_{min} = 0.8$, the standard deviation increases proportionately to $0.026$. Figure \ref{fauto} shows the autocorrelation of the resulting output of the neuron, which hovers around zero value, confirming the ability of the modified activation function to display chaotic behaviour. The logistic map is not the only chaotic map that can be used in the proposed activation function. For example, we can use the cubic map, $x_{t+1} = rx_t - x_{t}^3$, which also produces chaotic behaviour, for $2.3 < r < 3$, as shown in Figure \ref{cubicbifurcation}. As described earlier, $\alpha_{min}$ and $\alpha_{max}$ need to be set correctly by checking the range of the bifurcation diagram for the corresponding chaotic function being used. It can be worked out by looking at the maximum and minimum value of the graph for certain $r$ values. Table \ref{rtable} gives $\alpha_{min}$ and $\alpha_{max}$ for different values of $r$ for the logistic map, $x_{t+1} = rx_t(1-x_t)$. Table \ref{rtable2} gives the $\alpha_{min}$ and $\alpha_{max}$ values for the cubic map, $x_{t+1} = rx_t - x_t^3$. Both of these are rough estimates measured by generating time series data for different values of $r$, which can be improved by generating longer time series data. \begin{figure} \begin{center} {\includegraphics[height=10cm]{Diagram.png}} \end{center} \caption{Neuron with the spatio-temporal activation function}\label{diagram} \end{figure} \begin{table} \begin{tabular}{|c|c|c|} \hline $r$ & $\alpha_{min}$ & $\alpha_{max}$ \\ \hline\hline 3.5 & 0.382 & 0.875 \\ \hline 3.6 & 0.333 & 0.894 \\ \hline 3.7 & 0.261 & 0.923 \\ \hline 3.8 & 0.181 & 0.949 \\ \hline 3.9 & 0.123 & 0.967 \\ \hline 4.0 & 0.000 & 1.000 \\ \hline \end{tabular} \caption{$\alpha_{max}$ and $\alpha_{min}$ for different values of $r$ in the logistic map.}\label{rtable} \end{table} \begin{table} \begin{tabular}{|c|c|c|} \hline $r$ & $\alpha_{min}$ & $\alpha_{max}$ \\ \hline\hline 2.3 & 0.668 & 1.342 \\ \hline 2.4 & 0.585 & 1.408 \\ \hline 2.5 & 0.286 & 1.520 \\ \hline 2.6 & -1.605 & -0.035 \\ \hline 2.7 & -1.698 & 1.664 \\ \hline 2.8 & -1.759 & 1.405 \\ \hline 2.9 & -1.884 & 1.899 \\ \hline 3.0 & -1.953 & 1.861 \\ \hline \end{tabular} \caption{$\alpha_{max}$ and $\alpha_{min}$ for different values of $r$ in the cubic map.}\label{rtable2} \end{table} \begin{figure} \begin{center} {\includegraphics[height=4.9cm]{chart.png}} \end{center} \caption{Standard deviation corresponding to different ranges of $(\phi_{max} - \phi_{min})$.}\label{standard} \end{figure} \begin{figure} \begin{center} {\includegraphics[height=4.5cm]{annout.png}} \end{center} \caption{Output of the neuron displaying the chaotic dynamical behaviour using flat input data.}\label{fanno} \end{figure} \begin{figure} \begin{center} {\includegraphics[height=4.5cm]{autocorr.png}} \end{center} \caption{Autocorrelation of the resulting output of the neuron.}\label{fauto} \end{figure} \begin{figure} \begin{center} {\includegraphics[height=5.4cm]{cubic.png}} \end{center} \caption{Bifurcation diagram of the cubic map.}\label{cubicbifurcation} \end{figure} \section{Numerical Experiment}\label{ann} A numerical experiment was done with a flat time series as the input and chaotic time series as the output, as shown in Figure \ref{outputvsinput}. A single neuron using the proposed spatio-temporal activation function was trained against this chaotic data, while the input was a flat value, with parameters $\phi_{max} = 3.5$ and $\phi_{min} = -2.7$ while $\alpha_{max}$ and $\alpha_{min}$ were 1 and 0 respectively. \begin{figure} \begin{center} {\includegraphics[height=4cm]{outputandinput.png}} \end{center} \caption{Chaotic time series and flat input data.}\label{outputvsinput} \end{figure} After training, the same flat input data was fed to the neural network and the generated output time series data compared well with the actual chaotic time series data as shown in Figure \ref{output}. In this study, the Lyapunov exponent\cite{salis}, $\lambda$, is used as measure of chaos. The Lyapunov exponent of the function $f(x)$ is defined as follows: \begin{equation} \lambda = \frac{1}{n} \sum_{i=0}^{n-1}ln(|f'(x_i)|) \end{equation} where $x_{n+1} = f(x_n)$. For the chaotic data, the Lyapunov exponent, $\lambda = -1.01$, while the neural network's output's $\lambda = -0.98$. Thus, the new activation function is able to map the chaotic time series data successfully.\\ Figure \ref{sigmoid} shows the different instances of the activation function while generating the output time series as depicted in Figure \ref{output}. An important thing to notice is that the activation function occasionally flips because the $\phi_{min}$ taken in this example is negative. Though it may be odd, this helps the neuron generate chaotic data that matches the range of the expected output.\\ \begin{figure} \begin{center} {\includegraphics[height=5cm]{trained.png}} \end{center} \caption{Chaotic time series vs Output of neural network.}\label{output} \end{figure} \begin{figure} \begin{center} {\includegraphics[height=4cm]{sigmoid.png}} \end{center} \caption{Instances of activation function with different $\phi$ values during the generation of the chaotic time series output.}\label{sigmoid} \end{figure} \section{Conclusion}\label{conclusion} In the present research work, a two-dimensional activation function is proposed, by including an additional temporal term to impart dynamic behaviour on the output without relying on recurrent neural networks. The temporal term can be either a logistic/cubic map or any other chaotic map. The derivative at any instance of the activation function is similar to the Gaussian probability distribution with a varying, time-dependent standard deviation. Consequently, when the temporal term changes with time, the activation function fluctuates, leading to dynamical behaviour in the output. The new activation function is able to successfully map the chaotic data. Further research is required to investigate the spatio-temporal activation function in a multilayered feed forward neural network and its ability to capture chaos using logistic/cubic map.
{'timestamp': '2020-09-21T02:17:38', 'yymm': '2009', 'arxiv_id': '2009.08931', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08931'}
arxiv
\section*{Main comment} \addcontentsline{toc}{section}{Main comment} Glenn Shafer's paper is a powerful appeal for a wider use of betting ideas and intuitions in statistics. He admits that p-values will never be completely replaced by betting scores, and I discuss it further in Appendix~\ref{app:A} (one of the two online appendices that I have prepared to meet the word limit). Both p-values and betting scores generalize Cournot's principle \cite{Shafer:2007-local}, but they do it in their different ways, and both ways are interesting and valuable. Other authors have referred to betting scores as Bayes factors \cite{Shafer/etal:2011} and e-values \cite{Vovk/Wang:arXiv1912a-local,Grunwald/etal:arXiv1906}. For simple null hypotheses, betting scores and Bayes factors indeed essentially coincide \cite[Section 1, interpretation 3]{Grunwald/etal:arXiv1906}, but for composite null hypotheses they are different notions, and using ``Bayes factor'' to mean ``betting score'' is utterly confusing to Bayesians \cite{Robert:2011-local}. However, the Bayesian connection still allows us to apply Jeffreys's \cite[Appendix B]{Jeffreys:1961} rule of thumb to betting scores; namely, a p-value of 5\% is roughly equivalent to a betting score of $10^{1/2}$, and a p-value of 1\% to a betting score of 10. This agrees beautifully with Shafer's rule (6), which gives, to two decimal places: \begin{itemize} \item for $p=5\%$, $3.47$ instead of Jeffreys's $3.16$ (slight overshoot); \item for $p=1\%$, $9$ instead of Jeffreys's $10$ (slight undershoot). \end{itemize} The term ``e-values'' emphasizes the fundamental role of expectation in the definition of betting scores (somewhat similar to the role of probability in the definition of p-values). It appears that the natural habitat for ``betting scores'' is game-theoretic while for ``e-values'' it is measure-theoretic \cite{Shafer:personal}; therefore, I will say ``e-values'' in the online appendices (Appendix~\ref{app:A} and \cite{Vovk:B}), which are based on measure-theoretic probability. In the second online appendix \cite{Vovk:B} I give a new example showing that betting scores are not just about communication; they may allow us to solve real statistical and scientific problems (more examples will be given by my co-author Ruodu Wang). David Cox \cite{Cox:1975} discovered that splitting data at random not only allows flexible testing of statistical hypotheses but also achieves high efficiency. A serious objection to the method is that different people analyzing the same data may get very different answers (thus violating ``inferential reproducibility'' \cite{Goodman/etal:2016,Held/Schwab:2020}). Using e-values instead of p-values remedies the situation. \subsection*{Acknowledgments} Thanks to Ruodu Wang for useful discussions and for sharing with me his much more extensive list of advantages of e-values. This research has been partially supported by Amazon, Astra Zeneca, and Stena Line.
{'timestamp': '2020-09-21T02:17:38', 'yymm': '2009', 'arxiv_id': '2009.08933', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08933'}
arxiv
\subsection{Implementation Details} \paragraph{Neural Network Architecture Details} We use a two layer feedforward neural network of 256 and 256 hidden nodes respectively. Rectified linear units~(ReLU) are put after each layer for both the actor and critic except the last layer. For the last layer of the actor network, a tanh function is used as the activation function to squash the action range within $[-1,1]$. \emph{GRAC} then multiplies the output of the tanh function by \emph{max action} to transform [-1,1] into [-\emph{max action}, \emph{max action}]. The actor network outputs the mean and sigma of a Gaussian distribution. \paragraph{CEM Implementation} Our CEM implementation is based on the CEM algorithm described in Pourchot~\etal~\cite{pourchot2018cemrl}. \setcounter{algorithm}{1} \begin{algorithm}[H] {Input: Q-function Q(s,a); size of population $N_{pop}$; size of elite $N_{elite}$ where $N_{elite} \leq N_{pop}$; max iteration of CEM $N_{cem}$.}\\ {Initialize the mean $\mu$ and covariance matrix $\Sigma$ from actor network predictions.} \begin{algorithmic}[1] \For {$i=1...,N_{\text{cem}}$} \State Draw the current population set $\{a_{pop} \}$ of size $N_{pop}$ from $\mathcal{N}(\mu, \Sigma)$. \State Receive the $Q$ values $\{q_{pop}\} = \{Q(s,a) | a \in \{a_{pop}\} \}$. \State Sort $\{q_{pop}\}$ in descending order. \State Select top $N_{elite}$ Q values and choose their corresponding $a_{pop}$ as elite $\{a_{elite}\}$. \State Calculate the mean $\mu$ and covariance matrix $\Sigma$ of the set $\{ a_{elite} \}$. \EndFor \end{algorithmic} {Output: The top one elite in the final iteration.} \caption{CEM} \label{alg:cem} \end{algorithm} \paragraph{Additional Detail on Algorithm 1: GRAC} The actor network outputs the mean and sigma of a Gaussian distribution. In Line 2 of Alg.1, the actor has to select action $a$ based on the state $s$. In the test stage, the actor directly uses the predicted mean as output action $a$. In the training stage, the actor first samples an action $\hat{a}$ from the predicted Gaussian distribution $\pi_{\phi}(s)$, then \emph{GRAC} runs \emph{CEM} to find a second action $\tilde{a}=\emph{CEM}(Q(s,\cdot;\theta_2),\pi_{\phi}(\cdot | s)$). \emph{GRAC} uses $a=\argmax_{\{\tilde{a},\hat{a}\}}\{\min_{j=1,2} Q(s,\tilde{a};\theta_j), \min_{j=1,2} Q(s,\hat{a};\theta_j)\}$ as the final action. \subsection{Appendix on Experiments} \subsubsection{Hyperparameters used} Table~\ref{tab:hyper} and Table~\ref{tab:hyper_env} list the hyperparameters used in the experiments. $[a,b]$ denotes a linear schedule from $a$ to $b$ during the training process. \begin{table}[H] \centering \begin{tabular}{@{}p{0.3\linewidth}p{0.15\linewidth}} \hline \hline Parameters & Values \\ \hline \hline discount $\gamma$ & 0.99\\ \hline replay buffer size & 1e6\\ \hline batch size & 256 \\ \hline optimizer & Adam~\cite{kingma2014adam}\\ \hline learning rate & 3e-4\\ \hline $N_{\text{cem}}$ & 2\\ \hline $N_{\text{pop}}$ & 25\\ \hline $N_{\text{elite}}$ & 5\\ \hline\hline \end{tabular} \caption{Hyperparameter Table} \label{tab:hyper} \end{table} \begin{table}[H] \centering \begin{tabular}{@{}p{0.17\linewidth}p{0.12\linewidth} p{0.11\linewidth} p{0.11\linewidth} p{0.15\linewidth} p{0.14\linewidth}} \hline \hline Environments & ActionDim & $K$ in Alg.1 & $\alpha$ in Alg.1 & CemLossWeight & RewardScale \\ \hline Ant-v2 & 8 & 20 & [0.7,~85] & 1.0/ActionDim & 1.0\\ Hopper-v2 & 3 & 20 & [0.85,~0.95] & 0.3/ActionDim & 1.0\\ HalfCheetah-v2 & 6 & 50 & [0.7,~0.85] & 1.0/ActionDim &0.5\\ Humanoid-v2 & 17 & 20 & [0.7,~0.85] & 1.0/ActionDim & 1.0\\ Swimmer-v2 & 2 & 20 & [0.5,~0.75] & 1.0/ActionDim & 1.0\\ Walker2d-v2 & 6 & 20 & [0.8,~0.9] & 0.3//ActionDim & 1.0\\ \hline\hline \end{tabular} \caption{Environment Specific Parameters} \label{tab:hyper_env} \end{table} \subsubsection{Additional Learning Curves} \label{appendsec:experiment} Figure 5 shows the learning curves for policy improvement with evolution strategy. \begin{figure}[htb!] \centering \begin{tabular}{ccc} \begin{minipage}{.3\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_ant.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_hopper.pdf} \par\small{(b)~Returns on Hopper-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_humanoid.pdf} \par\small{(c)~Returns on Humanoid-v2} \end{minipage} \end{tabular} \begin{tabular}{ccc} \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_halfcheetah.pdf} \par\small{(d)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_swimmer.pdf} \par\small{(e)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_walker2d.pdf} \par\small{(f)~Returns on Walker2d-v2} \end{minipage}\\ \end{tabular} \caption{Learning curves for the OpenAI gym continuous control tasks. The \emph{GRAC} actor network uses a combination of two actor loss functions, denoted as QLoss and CEMLoss. \emph{QLoss Only} represents the actor network only trained with QLoss. \emph{CEM Loss Only} represents the actor network only trained with CEMLoss. In general \emph{GRAC} achieves a better performance compared to either using \emph{CEMLoss} or \emph{QLoss}.} \end{figure} Figure 6 shows the learning curves for ablation Study of Self-Regularized TD Learning. \begin{figure}[htb!] \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_ant.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Ant-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_halfcheetah.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on HalfCheetah-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_humanoid.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Humanoid-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Humanoid-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_walker2d.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Walker2d-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Walker2d-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_swimmer.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Swimmer-v2} \end{minipage} \end{tabular} \caption{Learning curves and average $Q_1$ values ($y^{\prime}_1$ in Alg. 1 of the main paper). \emph{DDPG} w/o target network quickly diverges as seen by the unrealistically high Q values. \emph{DDPG} is stable but often progresses slower. If we remove the target network and add the proposed target regularization, we both maintain stability and achieve a faster or comparable learning rate.} \end{figure} \subsubsection{Hyperparameter Sensitivity for the Termination Condition of Critic Network Training}\label{appendsubsec:termination} We also run experiments to examine how sensitive \emph{GRAC} is to some hyperparameters such as $K$ and $\alpha$ listed in Alg.1. The critic networks will be updated until the critic loss has decreased to $\alpha$ times the original loss, or at most $K$ iterations, before proceeding to update the actor network. In practice, we decrease $\alpha$ in the training process. Fig. 3 shows five learning curves on Ant-v2 running with five different hyperparameter values. We find that a moderate value of $K=10$ is enough to stabilize the training process, and increasing $K$ further does not have significant influence on training, shown on the right of Fig. 3. $\alpha$ is usually within the range of $[0.7,0.9]$ and most tasks are not sensitive to minor changes. However on the task of Swimmer-v2, we find that $\alpha$ needs to be small enough ($<0.7$) to prevent divergence. In practice, without appropriate $K$ and $\alpha$ values, divergence usually happens within the first 50k training steps, thus it is quick to select appropriate values for $K$ and $\alpha$. \begin{figure*}[ht!] \centering \begin{tabular}{cc} \begin{minipage}{.45\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_1.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.45\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_2.pdf} \par\small{(b)~Returns on Ant-v2} \end{minipage} \end{tabular} \caption{Learning curves for the OpenAI gym Ant-v2 environment. $K$ denotes the maximum number of iterations. $\alpha$ denotes the remaining percent of loss value when terminating the iteration. In practice, we decrease $\alpha$ in the training process. $\text{alpha} a\text{\_}b$ denotes the initial value $a$ and final value $b$ for $\alpha$.}\label{fig:results} \end{figure*} \subsection{Theorems and Proofs} \label{appendsec:theorems} For the sake of clarity, we make the following technical assumption about the function approximation capacity of neural networks that we use to approximate the action distribution. \textbf{State separation assumption:} The neural network chosen to approximate the policy family $\Pi$ is expressive enough to approximate the action distribution for each state $\pi(s,\cdot)$ separately. \setcounter{theorem}{0} \subsubsection{Theorem 1: \textbf{$Q$-loss Policy Improvement}} \label{appendsubsec:theorem1} \begin{theorem} Starting from the current policy $\pi$, we update the policy to maximize the objective $J_\pi = \E_{(s,a) \sim \rho_\pi(s,a)} Q^{\pi}(s,a)$. The maximization converges to a critical point denoted as $\pi_{new}$. Then the induced Q function, $Q^{\pi_{new}}$, satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 1] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately, for each state we are maximizing $\E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a)$. Therefore, we have $\forall s, \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. \begin{equation} \begin{array}{rl} Q^{\pi}(s,a) &= r(s,a) + \gamma \E_{s^{\prime}}V^{\pi}(s^{\prime}) \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} Q^{\pi}(s^{\prime}, a^{\prime}) \\ &= r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} [r(s^{\prime}, a^{\prime}) + \gamma \E_{s^{\prime \prime}} V^{\pi}(s^{\prime \prime})] \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} r(s^{\prime}, a^{\prime}) + \gamma^2 \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} \E_{s^{\prime \prime}} \E_{a^{\prime \prime} \sim \pi_{new}} Q^{\pi}(s^{\prime \prime}, a^{\prime \prime}) \\ &= \ldots \quad \mbox{(repeatedly unroll Q function )} \\ &\leq Q^{\pi_{new}}(s,a) \end{array} \end{equation} \end{proof} \subsubsection{Theorem 2: \textbf{\emph{CEM} Policy Improvement}} \label{appendsubsec:theorem2} \begin{theorem} We assume that the \emph{CEM} process is able to find the optimal action of the state-action value function, $a^*(s) = \argmax_{a}Q^{\pi}(s,a)$, where $Q^{\pi}$ is the Q function induced by the current policy $\pi$. By iteratively applying the update $ \E_{(s,a) \sim \rho_\pi(s,a)} [Q(s,a^*)-Q(s,a)]_{+}\nabla \log\pi(a^*|s)$, the policy converges to $\pi_{new}$. Then $Q^{\pi_{new}}$ satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 2] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately. Then, for each state $s$, the policy $\pi_{new}$ will converge to a delta function at $a^*(s)$. Therefore we have $\forall s, \max_a Q^{\pi}(s,a) = \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. Then, following Eq. (1) we have $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a)$ \end{proof} \subsubsection{Theorem 3: \textbf{Max-Min Double Q-learning Convergence}} \label{appendsubsec:theorem3} \begin{theorem} We keep two tabular value estimates $Q_{1}$ and $Q_{2}$, and update via \begin{equation} \begin{array}{rl} Q_{t+1, 1}(s,a) &= Q_{t,1}(s,a) + \alpha_t(s,a) (y_t-Q_{t,1}(s,a))\\ Q_{t+1, 2}(s,a) &= Q_{t,2}(s,a) + \alpha_t(s,a) (y_t-Q_{t,2}(s,a)), \end{array} \end{equation} where $\alpha_t(s,a)$ is the learning rate and $y_t$ is the target: \begin{equation} \begin{array}{cl} y_t & = r_t(s_t, a_t) + \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{1, 2 \}} Q_{t,i}(s_{t+1}, a') \\ a^{\pi} & \sim \pi(s_{t+1})\\ a^* & = argmax_{a'} Q_{t,2}(s_{t+1}, a') \\ \end{array} \end{equation} We assume that the MDP is finite and tabular and the variance of rewards are bounded, and $\gamma \in [0,1]$. We assume each state action pair is sampled an infinite number of times and both $Q_{1}$ and $Q_{2}$ receive an infinite number of updates. We further assume the learning rates satisfy $\alpha_t(s,a) \in [0,1]$, $\sum_t \alpha_t(s,a) = \infty$, $\sum_t [\alpha_t(s,a)]^2 < \infty$ with probability 1 and $\alpha_t(s,a)=0, \forall (s,a) \neq (s_t, a_t)$. Finally we assume \emph{CEM} is able to find the optimal action $a^*(s) = \argmax_{a'}Q(s,a';\theta_2)$. Then Max-Min Double Q-learning will converge to the optimal value function $Q^*$ with probability $1$. \end{theorem} \begin{proof}[Proof of Theorem 3] This proof will closely follow Appendix A of \cite{fujimoto2018addressing}. We will first prove that $Q_2$ converges to the optimal Q value $Q^*$. Following notations of \cite{fujimoto2018addressing}, we have \begin{equation*} \begin{array}{rl} F_t(s_t,a_t) \triangleq& y_t(s_t,a_t) - Q^*(s_t, a_t) \\ =& r_t + \gamma \max_{a^{\prime} \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a^{\prime}) - Q^*(s_t, a_t) \\ =& F_t^Q(s_t, a_t) + c_t \end{array} \end{equation*} Where \begin{eqnarray*} F_t^Q(s_t, a_t) &=& r_t + \gamma Q_{t,2}(s_{t+1}, a^*) - Q^*(s_t, a_t) \\ &=& r_t + \gamma \max_{a^{\prime}} Q_{t,2}(s_{t+1}, a^{\prime}) -Q^*(s_t,a_t) \\ c_t &=& \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a') - \gamma Q_{t, 2}(s_{t+1}, a^*) \end{eqnarray*} $F^Q_t$ is associated with the optimum Bellman operator. It is well known that the optimum Bellman operator is a contractor, We need to prove $c_t$ converges to 0. Based on the update rules (Eq. (A2)), it is easy to prove that for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0. This implies that $\Delta_t(s, a^\pi) = Q_{t,1}(s,a^\pi) - Q_{t,2}(s,a^\pi)$ converges to 0 and $\Delta_t(s, a^*) = Q_{t, 1}(s,a^*) - Q_{t, 2}(s,a^*)$ converges to 0. Therefore, $\min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a) - Q_{t, 2}(s,a) \leq 0$ and the left hand side converges to zero, for $a \in {a^\pi, a^*}$. Since we have $Q_{t, 2}(s, a^*) >= Q_{t, 2}(s, a^\pi)$, then \[ \min_{i \in \{1, 2\}} Q_{t, i}(s, a^*) \leq \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a') \leq Q_{t, 2}(s,a^*) \] Therefore $c_t = \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{ i \in \{ 1, 2 \}} Q_{t, i}(s, a') - Q_{t, 2}(s,a^*)$ converges to 0. And we proved $Q_{t, 2}$ converges to $Q^*$. Since for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0, $Q_{t, 1}$ also converges to $Q^*$. \end{proof} \subsection{Self-Regularized TD Learning}\label{sec:target} Reinforcement learning is prone to instability and divergence when a nonlinear function approximator such as a neural network is used to represent the Q function~\cite{tsitsiklis1997analysis}. Mnih~\etal\cite{mnih2015human} identified several reasons for this. One is the correlation between the current action-values and the target value. Updates to $Q(s_t,a_t)$ often also increase $Q(s_{t+1},a^{*}_{t+1})$ where $a^{*}_{t+1}$ is the optimal next action. Hence, these updates also increase the target value $y_t$ which may lead to oscillations or the divergence of the policy. More formally, given transitions $(s_t,a_t,r_t,s_{t+1})$ sampled from the replay buffer distribution $\mathcal{B}$, the Q network can be trained by minimising the loss functions $\mathcal{L}(\theta_i)$ at iteration $i$: \begin{equation} \mathcal{L}(\theta_i) = \E_{(s_t,a_t) \sim \mathcal{B}}\|(Q(s_t,a_t; \theta_i) - y_i)\|^2 \end{equation} where for now let us assume $y_i= r_t + \gamma\max_{a}Q(s_{t+1},a;\theta_i)$ to be the target for iteration $i$ computed based on the current Q network parameters $\theta_i$. ${a}^{*}_{t+1}=\argmax_{a}Q(s_{t+1},a)$. If we update the parameter $\theta_{i+1}$ to reduce the loss $\mathcal{L}(\theta_i)$, it changes both $Q(s_t,a_t;\theta_{i+1})$ and $Q(s_{t+1},a_{t+1}^{*};\theta_{i+1})$. Assuming an increase in both values, then the new target value $y_{i+1} = r_t + \gamma Q(s_{t+1},a^*_{t+1}; \theta_{i+1})$ for the next iteration will also increase leading to an explosion of the Q function. We demonstrated this behavior in an ablation experiment with results in Fig.~\ref{fig:abl1}. We also show how maintaining a separate target network~\cite{mnih2015human} with frozen parameters $\theta^-$ to compute $y_{i+1} = r_t + \gamma Q(s_{t+1},a^*_{t+1}; \theta^-)$ delays the update of the target and therefore leads to more stable learning of the Q function. However, delaying the function updates also comes with the price of slowing down the learning process. We propose a self-Regularized TD-learning approach to minimize the TD-error while also keeping the change of $Q(s_{t+1},a^*_{t+1})$ small. This regularization mitigates the divergence issue~\cite{tsitsiklis1997analysis}, and no longer requires a target network that would otherwise slow down the learning process. Let $y^{\prime}_i = Q(s_{t+1},a_{t+1}^{*}; \theta_i)$, and $y_i=r_t + \gamma y^{\prime}_i$. We define the learning objective as \begin{equation} \min_{\theta} \|Q(s_t,a_t;\theta) - y_i\|^2 + \|Q(s_{t+1},a^{*}_{t+1};\theta) - y^\prime_i\|^2 \end{equation} where the first term is the original TD-Learning objective and the second term is the regularization term penalizing large updates to $Q(s_{t+1}, a^*_{t+1})$. Note that when the current Q network updates its parameters $\theta$, both $Q(s_t,a_t)$ and $Q(s_ {t+1},a^{*}_{t+1})$ change. Hence, the target value $y_i$ will also change which is different from the approach of keeping a frozen target network for a few iterations. We will demonstrate in our experiments that this self-regularized TD-Learning approach removes the delays in the update of the target value thereby achieves faster and stable learning. \subsection{Self-Guided Policy Improvement with Evolution Strategies}\label{sec:cem_a} The policy, known as the actor, can be updated through a combination of two parts. The first part, which we call Q-loss policy update, improves the policy through local gradients of the current Q function, while the second part, which we call \emph{CEM} policy update, finds a high-value action via \emph{CEM} in a broader neighborhood of the Q function landscape, and update the action distribution to concentrate towards this high-value action. We describe the two parts formally below. Given states $s_t$ sampled from the replay buffer, the Q-loss policy update maximizes the objective \begin{equation} J_{\pi}(\phi) = \E_{s_t \sim \mathcal{B},\hat{a}_t \sim \pi}[Q(s_t, \hat{a}_t)], \end{equation} where $\hat{a}_t$ is sampled from the current policy $\pi(\cdot | s_t)$. The gradient is taken through the reparameterization trick. We reparameterize the policy using a neural network transformation as described in Haarnoja~\etal~\cite{haarnoja2018soft}, \begin{equation} \hat{a}_t = f_{\phi}(\epsilon_t | s_t) \end{equation} where $\epsilon_t$ is an input noise vector, sampled from a fixed distribution, such as a standard multivariate Normal distribution. Then the gradient of $J_\pi(\phi)$ is: \begin{equation} \nabla J_{\pi}(\phi) = \E_{s_t \sim \mathcal{B}, \epsilon_t \sim \mathcal{N}}[\frac{\partial Q(s_t,f_{\phi}(\epsilon_t | s_t))} {\partial f} \frac{\partial f_\phi(\epsilon_t | s_t)}{\partial \phi}] \end{equation} For the CEM policy update, given a minibatch of states $s_t$, we first find a high-value action $\bar{a}_t$ for each state by running \emph{CEM} on the current Q function, $\bar{a}_t = \text{\emph{CEM}}(Q(s_t,\cdot), \pi(\cdot | s_t))$. Then the policy is updated to increase the probability of this high-value action. The guided update on the parameter $\phi$ of $\pi$ at iteration $i$ is \begin{equation} \E_{s_t \sim \mathcal{B}, \hat{a}_t \sim \pi} [Q(s_t,\bar{a}_t) - Q(s_t,\hat{a}_t)]_{+} \nabla_{\phi} \log\pi_i(\bar{a}_t|s_t). \end{equation} We used $Q(s_t, \hat{a}_t)$ as a baseline term, since its expectation over actions $\hat{a}_t$ will give us the normal baseline $V(s_t)$: \begin{equation} \E_{s_t\sim \mathcal{B}} [Q(s_t,\bar{a}_t)-V(s_t)] \nabla_{\phi} \log\pi_i(\bar{a}_t|s_t) \end{equation} In our implementation, we only perform an update if the improvement on the $Q$ function, $Q(s_t,\bar{a}_t)-Q(s_t,\hat{a}_t)$, is non-negative, to guard against the occasional cases where \emph{CEM} fails to find a better action. Combining both parts of updates, the final update rule on the parameter $\phi_i$ of policy $\pi_i$ is \[ \phi_{i+1} = \phi_{i} - \lambda \nabla_{\phi} J_{\pi_i}(\phi_{i} ) - \lambda \E_{s_t \sim \mathcal{B}, \hat{a}_t \sim \pi_i} [Q(s_t,\bar{a}_t) - Q(s_t,\hat{a}_t)]_{+} \nabla_{\phi} \log\pi_i(\bar{a}_t|s_t) \] where $\lambda$ is the step size. We can prove that if the Q function has converged to $Q^{\pi}$, the state-action value function induced by the current policy, then both the Q-loss policy update and the \emph{CEM} policy update will be guaranteed to improve the current policy. We formalize this result in Theorem 1 and Theorem 2, and prove them in Appendix 3.1 and 3.2. \begin{theorem} \textbf{$Q$-loss Policy Improvement} Starting from the current policy $\pi$, we maximize the objective $J_\pi = \E_{(s,a) \sim \rho_\pi(s,a)} Q^{\pi}(s,a)$. The maximization converges to a critical point denoted as $\pi_{new}$. Then the induced Q function, $Q^{\pi_{new}}$, satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{theorem} \textbf{\emph{CEM} Policy Improvement} Assuming the \emph{CEM} process is able to find the optimal action of the state-action value function, $a^*(s) = \argmax_{a}Q^{\pi}(s,a)$, where $Q^{\pi}$ is the Q function induced by the current policy $\pi$. By iteratively applying the update $ \E_{(s,a) \sim \rho_\pi(s,a)} [Q(s,a^*)-Q(s,a)]_{+}\nabla \log\pi(a^*|s)$, the policy converges to $\pi_{new}$. Then $Q^{\pi_{new}}$ satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \subsection{Max-min Double Q-Learning}\label{sec:cem_c} Q-learning~\cite{Watkins:89} is known to suffer from overestimation~\cite{thrun1993issues}. Hasselt~\etal~\cite{hasselt2010double} proposed Double-Q learning which uses two Q functions with independent sets of weights to mitigate the overestimation problem. Fujimoto~\etal~\cite{fujimoto2018addressing} proposed Clipped Double Q-learning with two Q function denoted as $Q(s,a;\theta_1)$ and $Q(s,a;\theta_2)$, or $Q_1$ and $Q_2$ in short. Given a transition $(s_t,a_t,r_t,s_{t+1})$, Clipped Double Q-learning uses the minimum between the two estimates of the Q functions when calculating the target value in TD-error~\cite{sutton1998introduction}: \begin{equation} y= r_t + \gamma\min_{j=1,2} Q(s_{t+1},\hat{a}_{t+1};\theta_j) \label{eqn:clipped} \end{equation} where $\hat{a}_{t+1}$ is the predicted next action. Fujimoto~\etal~\cite{fujimoto2018addressing} mentioned that such an update rule may induce an underestimation bias. In addition, $\hat{a}_{t+1}=\pi_{\phi}(s_{t+1})$ is the prediction of the actor network. The actor network's parameter ${\phi}$ is optimized according to the gradients of $Q_1$. In other words, $\hat{a}_{t+1}$ tends be selected according to the $Q_1$ network which consistently increases the discrepancy between the two Q-functions. In practice, we observe that the discrepancy between the two estimates of the Q-function, $|Q_1 - Q_2|$, can increase dramatically leading to an unstable learning process. An example is shown in Fig.~\ref{fig:abl2} where $Q(s_{t+1},\hat{a}_{t+1};\theta_1)$ is always bigger than $Q(s_{t+1},\hat{a}_{t+1};\theta_2)$. We introduce \emph{Max-min Double Q-Learning} to reduce the discrepancy between the Q-functions. We first select $\hat{a}_{t+1}$ according to the actor network $\pi_{\phi}(s_{t+1})$. Then we run \emph{CEM} to search the landscape of $Q_2$ within a broad neighborhood of $\hat{a}_{t+1}$ to return a second action $\tilde{a}_{t+1}$. Note that \emph{CEM} selects an action $\tilde{a}_{t+1}$ that maximises $Q_2$ while the actor network selects an action $\hat{a}_{t+1}$ that maximises $Q_1$. We gather four different Q-values: $Q(s_{t+1},\hat{a}_{t+1};\theta_1)$, $Q(s_{t+1},\hat{a}_{t+1};\theta_2)$, $Q(s_{t+1},\tilde{a}_{t+1};\theta_1)$, and $Q(s_{t+1},\tilde{a}_{t+1};\theta_2)$. We then run a max-min operation to compute the target value that cancels the biases induced by $\hat{a}_{t+1}$ and $\tilde{a}_{t+1}$. \begin{equation} \label{eq:maxmin} \begin{aligned} y & = r_t + \gamma \max\{\min_{j=1,2} Q(s_{t+1},\hat{a}_{t+1};\theta_j), \min_{j=1,2} Q(s_{t+1},\tilde{a}_{t+1};\theta_j)\} \end{aligned} \end{equation} The inner min-operation $\min_{j=1,2} Q(s_{t+1},\hat{a}_{t+1};\theta_j)$ is adopted from Eq.~\ref{eqn:clipped} and mitigates overestimation~\cite{thrun1993issues}. The outer max operation helps to reduce the difference between $Q_1$ and $Q_2$. In addition, the max operation provides a better approximation of the Bellman optimality operator~\cite{sutton1998introduction}. We visualize $Q_1$ and $Q_2$ during the learning process in Fig.~\ref{fig:abl2}. The following theorem formalizes the convergence of the proposed Max-min Double Q-Learning approach in the finite MDP setting. We prove the theorem in Appendix 3.3. \begin{theorem} \begin{equation} \begin{array}{rl} Q_{t+1, 1}(s,a) &= Q_{t,1}(s,a) + \alpha_t(s,a) (y_t-Q_{t,1}(s,a))\\ Q_{t+1, 2}(s,a) &= Q_{t,2}(s,a) + \alpha_t(s,a) (y_t-Q_{t,2}(s,a)), \end{array} \end{equation} where $\alpha_t(s,a)$ is the learning rate and $y_t$ is the target: \begin{equation} \begin{array}{cl} y_t & = r_t(s_t, a_t) + \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{1, 2 \}} Q_{t,i}(s_{t+1}, a') \\ a^{\pi} & \sim \pi(s_{t+1})\\ a^* & = argmax_{a'} Q_{t,2}(s_{t+1}, a') \\ \end{array} \end{equation} We assume that the MDP is finite and tabular and the variance of rewards are bounded, and $\gamma \in [0,1]$. We assume each state action pair is sampled an infinite number of times and both $Q_{1}$ and $Q_{2}$ receive an infinite number of updates. We further assume the learning rates satisfy $\alpha_t(s,a) \in [0,1]$, $\sum_t \alpha_t(s,a) = \infty$, $\sum_t [\alpha_t(s,a)]^2 < \infty$ with probability 1 and $\alpha_t(s,a)=0, \forall (s,a) \neq (s_t, a_t)$. Finally we assume \emph{CEM} is able to find the optimal action $a^*(s) = \argmax_{a'}Q(s,a';\theta_2)$. Then Max-Min Double Q-learning will converge to the optimal value function $Q^*$ with probability $1$. \end{theorem} \subsection{Comparative Evaluation} We present \emph{GRAC}, a self-guided and self-regularized actor-critic algorithm as summarized in Algorithm~\ref{alg:alg1}. To evaluate {\em GRAC}, we measure its performance on the suite of MuJoCo continuous control tasks~\cite{todorov2012mujoco}, interfaced through OpenAI Gym~\cite{brockman2016openai}. We compare our method with \emph{DDPG}~\cite{lillicrap2015continuous}, \emph{TD3}~\cite{fujimoto2018addressing}, \emph{TRPO}~\cite{schulman2015trust}, and \emph{SAC}~\cite{haarnoja2018soft}. We use the source code released by the original authors and adopt the same hyperparameters reported in the original papers. Hyperparameters for all experiments are in Appendix 2.1. Results are shown in Figure \ref{fig:compare_results}. {\em GRAC} outperforms or performs comparably to all other algorithms in both final performance and learning speed across all tasks. \begin{figure*}[ht!] \centering \includegraphics[width=.85\linewidth]{imgs/fig_1_all_returns_0.pdf} \begin{tabular}{ccc} \begin{minipage}{.2\textwidth} \centering \par\small{(a)~Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Hopper-v2} \end{minipage} & \begin{minipage}{.2\linewidth} \centering \par\small{(c)~Humanoid-v2} \end{minipage} \end{tabular} \includegraphics[width=.85\linewidth]{imgs/fig_1_all_returns_1.pdf} \begin{tabular}{ccc} \begin{minipage}{.2\linewidth} \centering \par\small{(d)~HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(e)~Swimmer-v2} \end{minipage} & \begin{minipage}{.2\linewidth} \centering \par\small{(f)~Walker2d-v2} \end{minipage}\\ \end{tabular} \caption{Learning curves for the OpenAI gym continuous control tasks. For each task, we train 8 instances of each algorithm, using 8 different seeds. Evaluations are performed every 5000 interactions with the environment. Each evaluation reports the return (total reward), averaged over 10 episodes. For each training seed, we use a different seed for evaluation, which results in different start states. The solid curves and shaded regions represent the mean and standard deviation, respectively, of the average return over 8 seeds. All curves are smoothed with window size 10 for visual clarity. \emph{GRAC} (orange) learns faster than other methods across all tasks. \emph{GRAC} achieves comparable result to the state-of-the-art methods on the Ant-v2 task and outperforms prior methods on the other five tasks including the complex high-dimensional Humanoid-v2.}\label{fig:compare_results} \end{figure*} \subsection{Ablation Study} In this section, we present ablation studies to understand the contribution of each proposed component: Self-Regularized TD-Learning~(Section~\ref{sec:target}), Self-Guided Policy Improvment~(Section~\ref{sec:cem_a}), and Max-min Double Q-Learning~(Section~\ref{sec:cem_c}). We present our results in Fig.~\ref{fig:table2} in which we compare the performance of {\em GRAC} with alternatives, each removing one component from GRAC. Additional learning curves can be found in Appendix 2.2. We also run experiments to examine how sensitive GRAC is to some hyperparameters such as $\alpha$ and $K$ listed in Alg.~\ref{alg:alg1}, and the results can be found in Appendix 2.4. \paragraph{Self-Regularized TD Learning} To verify the effectiveness of the proposed self-regularized TD-learning method, we apply our method to \emph{DDPG} (DDPG w/o target network w/ target regularization). We compare against two baselines: the original \emph{DDPG} and \emph{DDPG} without target networks for both actor and critic (\emph{DDPG w/o target network}). We choose DDPG, because it does not have additional components such as Double Q-Learning, which may complicate the analysis of this comparison. In Fig.~\ref{fig:abl1}, we visualize the average returns, and average $Q_1$ values over training batchs (${y^\prime}_1$ in Alg.\ref{alg:alg1}). The $Q_1$ values of \emph{DDPG w/o target network} changes dramatically which leads to poor average returns. \emph{DDPG} maintains stable Q values but makes slow progress. Our proposed \emph{DDPG} w/o target network w/ target regularization maintains stable Q values and learns considerably faster. This demonstrates the effectiveness of our method and its potentials to be applied to a wide range of DRL methods. Due to page limit, we only include results on Hopper-v2. The results on other tasks are in Appendix 2.3. All tasks exhibit a similar phenomenon. \begin{figure}[hb!] \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_0.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Hopper-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Hopper-v2} \end{minipage} \end{tabular} \caption{Learning curves and average $Q_1$ values ($y^{\prime}_1$ in Alg.~\ref{alg:alg1}) on Hopper-v2. \emph{DDPG} w/o target network quickly diverges as seen by the unrealistically high Q values. \emph{DDPG} is stable but progresses slowly. If we remove the target network and add the proposed target regularization, we both maintain stability and achieve faster learning than \emph{DDPG}.}\label{fig:abl1} \end{figure} \paragraph{Policy Improvement with Evolution Strategies} The GRAC actor network uses a combination of two actor loss functions, denoted as \emph{QLoss} and \emph{CEMLoss}. \emph{QLoss} refers to the unbiased gradient estimators which extends the \emph{DDPG}-style policy gradients~\cite{lillicrap2015continuous} to stochastic policies. \emph{CEMLoss} represents the policy improvement guided by the action found with the zero-order optmization method CEM. We run another two ablation experiments on all six control tasks and compare it with our original policy training method denoted as \emph{GRAC}. As seen in Fig.\ref{fig:table2}, in general \emph{GRAC} achieves a better performance compared to either using \emph{CEMLoss} or \emph{QLoss}. The significance of the improvements varies within the six control tasks. For example, \emph{CEMLoss} plays a dominant role in Swimmer while \emph{QLoss} has a major effect in HalfCheetah. It suggests that \emph{CEMLoss} and \emph{QLoss} are complementary. \begin{figure} \centering \includegraphics[width=0.8\textwidth]{imgs/fig_table.pdf} \caption{Final average returns, normalized w.r.t {\em GRAC} for all tasks. For each task, we train each ablation setting with 4 seeds, and average the last 10 evaluations of each seed (40 evaluations in total). Actor updates without CEMLoss (\emph{GRAC w/o CEMLoss}) and actor updates w.r.t minimum of both Q networks (\emph{GRAC w/o CriticCEM w/ minQUpdate}) achieves slightly better performance on Walker2d-v2 and Hopper-v2. GRAC achieves the best performance on 4 out of 6 tasks, especially on more challenging tasks with higher-dimensional state and action spaces (Humanoid-v2, Ant-v2, HalfCheetah-v2). This suggests that individual components of GRAC complement each other. } \label{fig:table2} \end{figure} \paragraph{Max-min Double Q-Learning} We additionally verify the effectiveness of the proposed Max-min Double Q-Learning method. We run an ablation experiment by replacing Max-min by Clipped Double Q-learing~\cite{fujimoto2018addressing} denoted as \emph{GRAC w/o CriticCEM}. In Fig.~\ref{fig:abl2}, we visualize the learning curves of the average return, $Q_1$ ($y^{\prime}_1$ in Alg.~\ref{alg:alg1}), and $Q_1-Q_2$ ($y^{\prime}_1-y^{\prime}_2$ in Alg.~\ref{alg:alg1}). \emph{GRAC} achieves high performance while maintaining a smoothly increasing Q function. Note that the difference between Q functions, $Q_1-Q_2$, remains around zero for \emph{GRAC}. \emph{GRAC w/o CriticCEM} shows high variance and drastic changes in the learned $Q_1$ value. In addition, $Q_1$ and $Q_2$ do not always agree. Such unstable Q values result in a performance crash during the learning process. Instead of Max-min Double Q Learning, another way to address the gap between $Q_1$ and $Q_2$ is to perform actor updates on the minimum of $Q_1$ and $Q_2$ networks (as seen in SAC). Replacing Max-min Double Q Learning with this trick achieves lower performance than \emph{GRAC} in more challenging tasks such as HalfCheetah-v2, Ant-v2, and Humanoid-v2 (See \emph{GRAC w/o CriticCEM w/ minQUpdate} in Fig.\ref{fig:table2}). \begin{figure}[ht!] \centering \includegraphics[width=0.8\linewidth]{imgs/fig_3_abl_critic_cem_0.pdf} \begin{tabular}{ccc} \begin{minipage}{.3\textwidth} \begin{flushright} \par\small{(a)~Returns on Ant-v2} \end{flushright} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par \small{(b)~Average of $Q_1$ over training batch on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \begin{flushleft} \par\small{(c)~Average of $Q_1-Q_2$ over training batch on Ant-v2} \end{flushleft} \end{minipage} \end{tabular} \caption{ Learning curves (left), average $Q_1$ values (middle), and average of the difference between $Q_1$ and $Q_2$ (right) on Ant-v2. Average Q values are computes as minibatch average of $y^{\prime}_1$ and $y^{\prime}_2$, defined in Alg.~\ref{alg:alg1}. \emph{GRAC w/o CriticCEM} represents replacing Max-min Double Q-Learning with Clipped Double Q-Learning. Without Max-min double Q-Learning to balance the magnitude of $Q_1$ and $Q_2$, $Q_1$ blows up significantly compared to $Q_2$, leading to divergence. }\label{fig:abl2} \end{figure} \section{Notation Table} \documentclass{article} \PassOptionsToPackage{numbers, compress}{natbib} \usepackage{neurips_2020} \usepackage{amsmath} \usepackage{amssymb} \usepackage{enumitem} \DeclareMathOperator*{\argmax}{arg\,max} \DeclareMathOperator*{\argmin}{arg\,min} \DeclareMathOperator{\E}{\mathbb{E}} \newtheorem{theorem}{Theorem} \newtheorem{thm}{Theorem} \usepackage{xcolor} \newcommand\jean[1]{\textcolor{red}{J: #1}} \newcommand\lin[1]{\textcolor{blue}{L: #1}} \newcommand\yifan[1]{\textcolor{purple}{Y: #1}} \newcommand\mengyuan[1]{\textcolor{green}{MY: #1}} \newcommand\SUN[1]{\textcolor{blue}{SUN: #1}} \usepackage{graphicx} \usepackage{mathrsfs} \usepackage{float} \usepackage{algorithmicx} \usepackage{algorithm,algpseudocode} \usepackage{algorithm} \usepackage{amsthm,amsmath,amsfonts,verbatim} \usepackage[bookmarks=true]{hyperref} \hypersetup{ colorlinks=true, urlcolor=black, } \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{hyperref} \usepackage{url} \usepackage{booktabs} \usepackage{amsfonts} \usepackage{nicefrac} \usepackage{microtype} \usepackage{caption} \captionsetup[figure]{font=footnotesize} \captionsetup[table]{font=footnotesize} \defA\arabic{equation}{A\arabic{equation}} \title{Self-Guided and Self-Regularized Actor-Critic: Appendix} \begin{document} \maketitle \section{Implementation Details} \subsection{Neural Network Architecture Details} We use a two layer feedforward neural network of 256 and 256 hidden nodes respectively. Rectified linear units~(ReLU) are put after each layer for both the actor and critic except the last layer. For the last layer of the actor network, a tanh function is used as the activation function to squash the action range within $[-1,1]$. \emph{GRAC} then multiplies the output of the tanh function by \emph{max action} to transform [-1,1] into [-\emph{max action}, \emph{max action}]. The actor network outputs the mean and sigma of a Gaussian distribution. \subsection{CEM Implementation} Our CEM implementation is based on the CEM algorithm described in Pourchot~\etal~\cite{pourchot2018cemrl}. \setcounter{algorithm}{1} \begin{algorithm}[H] \Require{Input: Q-function Q(s,a); size of population $N_{pop}$; size of elite $N_{elite}$ where $N_{elite} \leq N_{pop}$; max iteration of CEM $N_{cem}$.}\\ \Initialization{Initialize the mean $\mu$ and covariance matrix $\Sigma$ from actor network predictions.} \begin{algorithmic}[1] \For {$i=1...,N_{\text{cem}}$} \State Draw the current population set $\{a_{pop} \}$ of size $N_{pop}$ from $\mathcal{N}(\mu, \Sigma)$. \State Receive the $Q$ values $\{q_{pop}\} = \{Q(s,a) | a \in \{a_{pop}\} \}$. \State Sort $\{q_{pop}\}$ in descending order. \State Select top $N_{elite}$ Q values and choose their corresponding $a_{pop}$ as elite $\{a_{elite}\}$. \State Calculate the mean $\mu$ and covariance matrix $\Sigma$ of the set $\{ a_{elite} \}$. \EndFor \end{algorithmic} \Output{Output: The top one elite in the final iteration.} \caption{CEM} \label{alg:cem} \end{algorithm} \subsection{Additional Detail on Algorithm 1: GRAC} The actor network outputs the mean and sigma of a Gaussian distribution. In Line 2 of Alg.1, the actor has to select action $a$ based on the state $s$. In the test stage, the actor directly uses the predicted mean as output action $a$. In the training stage, the actor first samples an action $\hat{a}$ from the predicted Gaussian distribution $\pi_{\phi}(s)$, then \emph{GRAC} runs \emph{CEM} to find a second action $\tilde{a}=\emph{CEM}(Q(s,\cdot;\theta_2),\pi_{\phi}(\cdot | s)$). \emph{GRAC} uses $a=\argmax_{\{\tilde{a},\hat{a}\}}\{\min_{j=1,2} Q(s,\tilde{a};\theta_j), \min_{j=1,2} Q(s,\hat{a};\theta_j)\}$ as the final action. \section{Appendix on Experiments} \subsection{Hyperparameters used} Table~\ref{tab:hyper} and Table~\ref{tab:hyper_env} list the hyperparameters used in the experiments. $[a,b]$ denotes a linear schedule from $a$ to $b$ during the training process. \begin{table}[H] \centering \begin{tabular}{@{}p{0.3\linewidth}p{0.15\linewidth}} \hline \hline Parameters & Values \\ \hline \hline discount $\gamma$ & 0.99\\ \hline replay buffer size & 1e6\\ \hline batch size & 256 \\ \hline optimizer & Adam~\cite{kingma2014adam}\\ \hline learning rate in critic & 3e-4\\ \hline learning rate in actor & 2e-4\\ \hline $N_{\text{cem}}$ & 2\\ \hline $N_{\text{pop}}$ & 256\\ \hline $N_{\text{elite}}$ & 5\\ \hline\hline \end{tabular} \caption{Hyperparameter Table} \label{tab:hyper} \end{table} \begin{table}[H] \centering \begin{tabular}{@{}p{0.17\linewidth}p{0.12\linewidth} p{0.11\linewidth} p{0.11\linewidth} p{0.15\linewidth} p{0.14\linewidth}} \hline \hline Environments & ActionDim & $K$ in Alg.1 & $\alpha$ in Alg.1 & CemLossWeight & Reward Scale \\ \hline Ant-v2 & 8 & 20 & [0.7,~85] & 1.0/ActionDim & 1.0 \\ Hopper-v2 & 3 & 20 & [0.85,~0.95] & 0.3/ActionDim & 1.0\\ HalfCheetah-v2 & 6 & 50 & [0.7,~0.85] & 1.0/ActionDim & 0.5\\ Humanoid-v2 & 17 & 20 & [0.7,~0.85] & 1.0/ActionDim & 1.0\\ Swimmer-v2 & 2 & 20 & [0.5,~0.75] & 1.0/ActionDim & 1.0\\ Walker2d-v2 & 6 & 20 & [0.8,~0.9] & 0.3//ActionDim & 1.0\\ \hline\hline \end{tabular} \caption{Environment Specific Parameters} \label{tab:hyper_env} \end{table} \subsection{Additional Learning Curves for Policy Improvement with Evolution Strategy} \label{appendsec:experiment} \begin{figure}[H] \centering \begin{tabular}{ccc} \begin{minipage}{.3\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_ant.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_hopper.pdf} \par\small{(b)~Returns on Hopper-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_humanoid.pdf} \par\small{(c)~Returns on Humanoid-v2} \end{minipage} \end{tabular} \begin{tabular}{ccc} \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_halfcheetah.pdf} \par\small{(d)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_swimmer.pdf} \par\small{(e)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_walker2d.pdf} \par\small{(f)~Returns on Walker2d-v2} \end{minipage}\\ \end{tabular} \caption{Learning curves for the OpenAI gym continuous control tasks. The \emph{GRAC} actor network uses a combination of two actor loss functions, denoted as QLoss and CEMLoss. \emph{QLoss Only} represents the actor network only trained with QLoss. \emph{CEM Loss Only} represents the actor network only trained with CEMLoss. In general \emph{GRAC} achieves a better performance compared to either using \emph{CEMLoss} or \emph{QLoss}.} \end{figure} \subsection{Additional Learning Curves for Ablation Study of Self-Regularized TD Learning} \begin{figure}[H] \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_ant.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Ant-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_halfcheetah.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on HalfCheetah-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_humanoid.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Humanoid-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Humanoid-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_walker2d.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Walker2d-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Walker2d-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_swimmer.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Swimmer-v2} \end{minipage} \end{tabular} \caption{Learning curves and average $Q_1$ values ($y^{\prime}_1$ in Alg. 1 of the main paper). \emph{DDPG} w/o target network quickly diverges as seen by the unrealistically high Q values. \emph{DDPG} is stable but often progresses slower. If we remove the target network and add the proposed target regularization, we both maintain stability and achieve a faster or comparable learning rate.} \end{figure} \subsection{Hyperparameter Sensitivity for the Termination Condition of Critic Network Training}\label{appendsubsec:termination} We also run experiments to examine how sensitive \emph{GRAC} is to some hyperparameters such as $K$ and $\alpha$ listed in Alg.1. The critic networks will be updated until the critic loss has decreased to $\alpha$ times the original loss, or at most $K$ iterations, before proceeding to update the actor network. In practice, we decrease $\alpha$ in the training process. Fig. 3 shows five learning curves on Ant-v2 running with five different hyperparameter values. We find that a moderate value of $K=10$ is enough to stabilize the training process, and increasing $K$ further does not have significant influence on training, shown on the right of Fig. 3. $\alpha$ is usually within the range of $[0.7,0.9]$ and most tasks are not sensitive to minor changes. However on the task of Swimmer-v2, we find that $\alpha$ needs to be small enough ($<0.7$) to prevent divergence. In practice, without appropriate $K$ and $\alpha$ values, divergence usually happens within the first 50k training steps, thus it is quick to select appropriate values for $K$ and $\alpha$. \begin{figure*}[ht!] \centering \begin{tabular}{cc} \begin{minipage}{.45\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_1.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.45\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_2.pdf} \par\small{(b)~Returns on Ant-v2} \end{minipage} \end{tabular} \caption{Learning curves for the OpenAI gym Ant-v2 environment. $K$ denotes the maximum number of iterations. $\alpha$ denotes the remaining percent of loss value when terminating the iteration. In practice, we decrease $\alpha$ in the training process. $\text{alpha} a\text{\_}b$ denotes the initial value $a$ and final value $b$ for $\alpha$.}\label{fig:results} \end{figure*} \section{Theorems and Proofs} \label{appendsec:theorems} For the sake of clarity, we make the following technical assumption about the function approximation capacity of neural networks that we use to approximate the action distribution. \textbf{State separation assumption:} The neural network chosen to approximate the policy family $\Pi$ is expressive enough to approximate the action distribution for each state $\pi(s,\cdot)$ separately. \subsection{Theorem 1: \textbf{$Q$-loss Policy Improvement}} \label{appendsubsec:theorem1} \begin{theorem} Starting from the current policy $\pi$, we update the policy to maximize the objective $J_\pi = \E_{(s,a) \sim \rho_\pi(s,a)} Q^{\pi}(s,a)$. The maximization converges to a critical point denoted as $\pi_{new}$. Then the induced Q function, $Q^{\pi_{new}}$, satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 1] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately, for each state we are maximizing $\E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a)$. Therefore, we have $\forall s, \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. \begin{equation} \begin{array}{rl} Q^{\pi}(s,a) &= r(s,a) + \gamma \E_{s^{\prime}}V^{\pi}(s^{\prime}) \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} Q^{\pi}(s^{\prime}, a^{\prime}) \\ &= r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} [r(s^{\prime}, a^{\prime}) + \gamma \E_{s^{\prime \prime}} V^{\pi}(s^{\prime \prime})] \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} r(s^{\prime}, a^{\prime}) + \gamma^2 \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} \E_{s^{\prime \prime}} \E_{a^{\prime \prime} \sim \pi_{new}} Q^{\pi}(s^{\prime \prime}, a^{\prime \prime}) \\ &= \ldots \quad \mbox{(repeatedly unroll Q function )} \\ &\leq Q^{\pi_{new}}(s,a) \end{array} \end{equation} \end{proof} \subsection{Theorem 2: \textbf{\emph{CEM} Policy Improvement}} \label{appendsubsec:theorem2} \begin{theorem} We assume that the \emph{CEM} process is able to find the optimal action of the state-action value function, $a^*(s) = \argmax_{a}Q^{\pi}(s,a)$, where $Q^{\pi}$ is the Q function induced by the current policy $\pi$. By iteratively applying the update $ \E_{(s,a) \sim \rho_\pi(s,a)} [Q(s,a^*)-Q(s,a)]_{+}\nabla \log\pi(a^*|s)$, the policy converges to $\pi_{new}$. Then $Q^{\pi_{new}}$ satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 2] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately. Then, for each state $s$, the policy $\pi_{new}$ will converge to a delta function at $a^*(s)$. Therefore we have $\forall s, \max_a Q^{\pi}(s,a) = \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. Then, following Eq. (1) we have $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a)$ \end{proof} \subsection{Theorem 3: \textbf{Max-Min Double Q-learning Convergence}} \label{appendsubsec:theorem3} \begin{theorem} We keep two tabular value estimates $Q_{1}$ and $Q_{2}$, and update via \begin{equation} \begin{array}{rl} Q_{t+1, 1}(s,a) &= Q_{t,1}(s,a) + \alpha_t(s,a) (y_t-Q_{t,1}(s,a))\\ Q_{t+1, 2}(s,a) &= Q_{t,2}(s,a) + \alpha_t(s,a) (y_t-Q_{t,2}(s,a)), \end{array} \end{equation} where $\alpha_t(s,a)$ is the learning rate and $y_t$ is the target: \begin{equation} \begin{array}{cl} y_t & = r_t(s_t, a_t) + \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{1, 2 \}} Q_{t,i}(s_{t+1}, a') \\ a^{\pi} & \sim \pi(s_{t+1})\\ a^* & = argmax_{a'} Q_{t,2}(s_{t+1}, a') \\ \end{array} \end{equation} We assume that the MDP is finite and tabular and the variance of rewards are bounded, and $\gamma \in [0,1]$. We assume each state action pair is sampled an infinite number of times and both $Q_{1}$ and $Q_{2}$ receive an infinite number of updates. We further assume the learning rates satisfy $\alpha_t(s,a) \in [0,1]$, $\sum_t \alpha_t(s,a) = \infty$, $\sum_t [\alpha_t(s,a)]^2 < \infty$ with probability 1 and $\alpha_t(s,a)=0, \forall (s,a) \neq (s_t, a_t)$. Finally we assume \emph{CEM} is able to find the optimal action $a^*(s) = \argmax_{a'}Q(s,a';\theta_2)$. Then Max-Min Double Q-learning will converge to the optimal value function $Q^*$ with probability $1$. \end{theorem} \begin{proof}[Proof of Theorem 3] This proof will closely follow Appendix A of \cite{fujimoto2018addressing}. We will first prove that $Q_2$ converges to the optimal Q value $Q^*$. Following notations of \cite{fujimoto2018addressing}, we have \begin{equation*} \begin{array}{rl} F_t(s_t,a_t) \triangleq& y_t(s_t,a_t) - Q^*(s_t, a_t) \\ =& r_t + \gamma \max_{a^{\prime} \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a^{\prime}) - Q^*(s_t, a_t) \\ =& F_t^Q(s_t, a_t) + c_t \end{array} \end{equation*} Where \begin{eqnarray*} F_t^Q(s_t, a_t) &=& r_t + \gamma Q_{t,2}(s_{t+1}, a^*) - Q^*(s_t, a_t) \\ &=& r_t + \gamma \max_{a^{\prime}} Q_{t,2}(s_{t+1}, a^{\prime}) -Q^*(s_t,a_t) \\ c_t &=& \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a') - \gamma Q_{t, 2}(s_{t+1}, a^*) \end{eqnarray*} $F^Q_t$ is associated with the optimum Bellman operator. It is well known that the optimum Bellman operator is a contractor, We need to prove $c_t$ converges to 0. Based on the update rules (Eq. (A2)), it is easy to prove that for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0. This implies that $\Delta_t(s, a^\pi) = Q_{t,1}(s,a^\pi) - Q_{t,2}(s,a^\pi)$ converges to 0 and $\Delta_t(s, a^*) = Q_{t, 1}(s,a^*) - Q_{t, 2}(s,a^*)$ converges to 0. Therefore, $\min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a) - Q_{t, 2}(s,a) \leq 0$ and the left hand side converges to zero, for $a \in {a^\pi, a^*}$. Since we have $Q_{t, 2}(s, a^*) >= Q_{t, 2}(s, a^\pi)$, then \[ \min_{i \in \{1, 2\}} Q_{t, i}(s, a^*) \leq \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a') \leq Q_{t, 2}(s,a^*) \] Therefore $c_t = \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{ i \in \{ 1, 2 \}} Q_{t, i}(s, a') - Q_{t, 2}(s,a^*)$ converges to 0. And we proved $Q_{t, 2}$ converges to $Q^*$. Since for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0, $Q_{t, 1}$ also converges to $Q^*$. \end{proof} \section{Introduction} \input{tex/intro.tex} \section{Related Work} \input{tex/related.tex} \section{Preliminaries} \input{tex/pre.tex} \section{Technical Approach} \input{tex/tech.tex} \section{Experiments} \input{tex/exp.tex} \section{Conclusion} \input{tex/con.tex} \section{Broader Impact} \input{tex/impact.tex} \section{Introduction} \input{tex/intro.tex} \section{Related Work} \input{tex/related.tex} \section{Preliminaries} \input{tex/pre.tex} \section{Technical Approach} \input{tex/tech.tex} \section{Experiments} \input{tex/exp.tex} \section{Conclusion} \input{tex/con.tex} \section{Broader Impact} \input{tex/impact.tex} \subsection{Implementation Details} \paragraph{Neural Network Architecture Details} We use a two layer feedforward neural network of 256 and 256 hidden nodes respectively. Rectified linear units~(ReLU) are put after each layer for both the actor and critic except the last layer. For the last layer of the actor network, a tanh function is used as the activation function to squash the action range within $[-1,1]$. \emph{GRAC} then multiplies the output of the tanh function by \emph{max action} to transform [-1,1] into [-\emph{max action}, \emph{max action}]. The actor network outputs the mean and sigma of a Gaussian distribution. \paragraph{CEM Implementation} Our CEM implementation is based on the CEM algorithm described in Pourchot~\etal~\cite{pourchot2018cemrl}. \setcounter{algorithm}{1} \begin{algorithm}[H] {Input: Q-function Q(s,a); size of population $N_{pop}$; size of elite $N_{elite}$ where $N_{elite} \leq N_{pop}$; max iteration of CEM $N_{cem}$.}\\ {Initialize the mean $\mu$ and covariance matrix $\Sigma$ from actor network predictions.} \begin{algorithmic}[1] \For {$i=1...,N_{\text{cem}}$} \State Draw the current population set $\{a_{pop} \}$ of size $N_{pop}$ from $\mathcal{N}(\mu, \Sigma)$. \State Receive the $Q$ values $\{q_{pop}\} = \{Q(s,a) | a \in \{a_{pop}\} \}$. \State Sort $\{q_{pop}\}$ in descending order. \State Select top $N_{elite}$ Q values and choose their corresponding $a_{pop}$ as elite $\{a_{elite}\}$. \State Calculate the mean $\mu$ and covariance matrix $\Sigma$ of the set $\{ a_{elite} \}$. \EndFor \end{algorithmic} {Output: The top one elite in the final iteration.} \caption{CEM} \label{alg:cem} \end{algorithm} \paragraph{Additional Detail on Algorithm 1: GRAC} The actor network outputs the mean and sigma of a Gaussian distribution. In Line 2 of Alg.1, the actor has to select action $a$ based on the state $s$. In the test stage, the actor directly uses the predicted mean as output action $a$. In the training stage, the actor first samples an action $\hat{a}$ from the predicted Gaussian distribution $\pi_{\phi}(s)$, then \emph{GRAC} runs \emph{CEM} to find a second action $\tilde{a}=\emph{CEM}(Q(s,\cdot;\theta_2),\pi_{\phi}(\cdot | s)$). \emph{GRAC} uses $a=\argmax_{\{\tilde{a},\hat{a}\}}\{\min_{j=1,2} Q(s,\tilde{a};\theta_j), \min_{j=1,2} Q(s,\hat{a};\theta_j)\}$ as the final action. \subsection{Appendix on Experiments} \subsubsection{Hyperparameters used} Table~\ref{tab:hyper} and Table~\ref{tab:hyper_env} list the hyperparameters used in the experiments. $[a,b]$ denotes a linear schedule from $a$ to $b$ during the training process. \begin{table}[H] \centering \begin{tabular}{@{}p{0.3\linewidth}p{0.15\linewidth}} \hline \hline Parameters & Values \\ \hline \hline discount $\gamma$ & 0.99\\ \hline replay buffer size & 1e6\\ \hline batch size & 256 \\ \hline optimizer & Adam~\cite{kingma2014adam}\\ \hline learning rate & 3e-4\\ \hline $N_{\text{cem}}$ & 2\\ \hline $N_{\text{pop}}$ & 25\\ \hline $N_{\text{elite}}$ & 5\\ \hline\hline \end{tabular} \caption{Hyperparameter Table} \label{tab:hyper} \end{table} \begin{table}[H] \centering \begin{tabular}{@{}p{0.17\linewidth}p{0.12\linewidth} p{0.11\linewidth} p{0.11\linewidth} p{0.15\linewidth} p{0.14\linewidth}} \hline \hline Environments & ActionDim & $K$ in Alg.1 & $\alpha$ in Alg.1 & CemLossWeight & RewardScale \\ \hline Ant-v2 & 8 & 20 & [0.7,~85] & 1.0/ActionDim & 1.0\\ Hopper-v2 & 3 & 20 & [0.85,~0.95] & 0.3/ActionDim & 1.0\\ HalfCheetah-v2 & 6 & 50 & [0.7,~0.85] & 1.0/ActionDim &0.5\\ Humanoid-v2 & 17 & 20 & [0.7,~0.85] & 1.0/ActionDim & 1.0\\ Swimmer-v2 & 2 & 20 & [0.5,~0.75] & 1.0/ActionDim & 1.0\\ Walker2d-v2 & 6 & 20 & [0.8,~0.9] & 0.3//ActionDim & 1.0\\ \hline\hline \end{tabular} \caption{Environment Specific Parameters} \label{tab:hyper_env} \end{table} \subsubsection{Additional Learning Curves} \label{appendsec:experiment} Figure 5 shows the learning curves for policy improvement with evolution strategy. \begin{figure}[htb!] \centering \begin{tabular}{ccc} \begin{minipage}{.3\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_ant.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_hopper.pdf} \par\small{(b)~Returns on Hopper-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_humanoid.pdf} \par\small{(c)~Returns on Humanoid-v2} \end{minipage} \end{tabular} \begin{tabular}{ccc} \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_halfcheetah.pdf} \par\small{(d)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_swimmer.pdf} \par\small{(e)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_walker2d.pdf} \par\small{(f)~Returns on Walker2d-v2} \end{minipage}\\ \end{tabular} \caption{Learning curves for the OpenAI gym continuous control tasks. The \emph{GRAC} actor network uses a combination of two actor loss functions, denoted as QLoss and CEMLoss. \emph{QLoss Only} represents the actor network only trained with QLoss. \emph{CEM Loss Only} represents the actor network only trained with CEMLoss. In general \emph{GRAC} achieves a better performance compared to either using \emph{CEMLoss} or \emph{QLoss}.} \end{figure} Figure 6 shows the learning curves for ablation Study of Self-Regularized TD Learning. \begin{figure}[htb!] \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_ant.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Ant-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_halfcheetah.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on HalfCheetah-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_humanoid.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Humanoid-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Humanoid-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_walker2d.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Walker2d-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Walker2d-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_swimmer.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Swimmer-v2} \end{minipage} \end{tabular} \caption{Learning curves and average $Q_1$ values ($y^{\prime}_1$ in Alg. 1 of the main paper). \emph{DDPG} w/o target network quickly diverges as seen by the unrealistically high Q values. \emph{DDPG} is stable but often progresses slower. If we remove the target network and add the proposed target regularization, we both maintain stability and achieve a faster or comparable learning rate.} \end{figure} \subsubsection{Hyperparameter Sensitivity for the Termination Condition of Critic Network Training}\label{appendsubsec:termination} We also run experiments to examine how sensitive \emph{GRAC} is to some hyperparameters such as $K$ and $\alpha$ listed in Alg.1. The critic networks will be updated until the critic loss has decreased to $\alpha$ times the original loss, or at most $K$ iterations, before proceeding to update the actor network. In practice, we decrease $\alpha$ in the training process. Fig. 3 shows five learning curves on Ant-v2 running with five different hyperparameter values. We find that a moderate value of $K=10$ is enough to stabilize the training process, and increasing $K$ further does not have significant influence on training, shown on the right of Fig. 3. $\alpha$ is usually within the range of $[0.7,0.9]$ and most tasks are not sensitive to minor changes. However on the task of Swimmer-v2, we find that $\alpha$ needs to be small enough ($<0.7$) to prevent divergence. In practice, without appropriate $K$ and $\alpha$ values, divergence usually happens within the first 50k training steps, thus it is quick to select appropriate values for $K$ and $\alpha$. \begin{figure*}[ht!] \centering \begin{tabular}{cc} \begin{minipage}{.45\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_1.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.45\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_2.pdf} \par\small{(b)~Returns on Ant-v2} \end{minipage} \end{tabular} \caption{Learning curves for the OpenAI gym Ant-v2 environment. $K$ denotes the maximum number of iterations. $\alpha$ denotes the remaining percent of loss value when terminating the iteration. In practice, we decrease $\alpha$ in the training process. $\text{alpha} a\text{\_}b$ denotes the initial value $a$ and final value $b$ for $\alpha$.}\label{fig:results} \end{figure*} \subsection{Theorems and Proofs} \label{appendsec:theorems} For the sake of clarity, we make the following technical assumption about the function approximation capacity of neural networks that we use to approximate the action distribution. \textbf{State separation assumption:} The neural network chosen to approximate the policy family $\Pi$ is expressive enough to approximate the action distribution for each state $\pi(s,\cdot)$ separately. \setcounter{theorem}{0} \subsubsection{Theorem 1: \textbf{$Q$-loss Policy Improvement}} \label{appendsubsec:theorem1} \begin{theorem} Starting from the current policy $\pi$, we update the policy to maximize the objective $J_\pi = \E_{(s,a) \sim \rho_\pi(s,a)} Q^{\pi}(s,a)$. The maximization converges to a critical point denoted as $\pi_{new}$. Then the induced Q function, $Q^{\pi_{new}}$, satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 1] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately, for each state we are maximizing $\E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a)$. Therefore, we have $\forall s, \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. \begin{equation} \begin{array}{rl} Q^{\pi}(s,a) &= r(s,a) + \gamma \E_{s^{\prime}}V^{\pi}(s^{\prime}) \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} Q^{\pi}(s^{\prime}, a^{\prime}) \\ &= r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} [r(s^{\prime}, a^{\prime}) + \gamma \E_{s^{\prime \prime}} V^{\pi}(s^{\prime \prime})] \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} r(s^{\prime}, a^{\prime}) + \gamma^2 \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} \E_{s^{\prime \prime}} \E_{a^{\prime \prime} \sim \pi_{new}} Q^{\pi}(s^{\prime \prime}, a^{\prime \prime}) \\ &= \ldots \quad \mbox{(repeatedly unroll Q function )} \\ &\leq Q^{\pi_{new}}(s,a) \end{array} \end{equation} \end{proof} \subsubsection{Theorem 2: \textbf{\emph{CEM} Policy Improvement}} \label{appendsubsec:theorem2} \begin{theorem} We assume that the \emph{CEM} process is able to find the optimal action of the state-action value function, $a^*(s) = \argmax_{a}Q^{\pi}(s,a)$, where $Q^{\pi}$ is the Q function induced by the current policy $\pi$. By iteratively applying the update $ \E_{(s,a) \sim \rho_\pi(s,a)} [Q(s,a^*)-Q(s,a)]_{+}\nabla \log\pi(a^*|s)$, the policy converges to $\pi_{new}$. Then $Q^{\pi_{new}}$ satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 2] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately. Then, for each state $s$, the policy $\pi_{new}$ will converge to a delta function at $a^*(s)$. Therefore we have $\forall s, \max_a Q^{\pi}(s,a) = \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. Then, following Eq. (1) we have $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a)$ \end{proof} \subsubsection{Theorem 3: \textbf{Max-Min Double Q-learning Convergence}} \label{appendsubsec:theorem3} \begin{theorem} We keep two tabular value estimates $Q_{1}$ and $Q_{2}$, and update via \begin{equation} \begin{array}{rl} Q_{t+1, 1}(s,a) &= Q_{t,1}(s,a) + \alpha_t(s,a) (y_t-Q_{t,1}(s,a))\\ Q_{t+1, 2}(s,a) &= Q_{t,2}(s,a) + \alpha_t(s,a) (y_t-Q_{t,2}(s,a)), \end{array} \end{equation} where $\alpha_t(s,a)$ is the learning rate and $y_t$ is the target: \begin{equation} \begin{array}{cl} y_t & = r_t(s_t, a_t) + \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{1, 2 \}} Q_{t,i}(s_{t+1}, a') \\ a^{\pi} & \sim \pi(s_{t+1})\\ a^* & = argmax_{a'} Q_{t,2}(s_{t+1}, a') \\ \end{array} \end{equation} We assume that the MDP is finite and tabular and the variance of rewards are bounded, and $\gamma \in [0,1]$. We assume each state action pair is sampled an infinite number of times and both $Q_{1}$ and $Q_{2}$ receive an infinite number of updates. We further assume the learning rates satisfy $\alpha_t(s,a) \in [0,1]$, $\sum_t \alpha_t(s,a) = \infty$, $\sum_t [\alpha_t(s,a)]^2 < \infty$ with probability 1 and $\alpha_t(s,a)=0, \forall (s,a) \neq (s_t, a_t)$. Finally we assume \emph{CEM} is able to find the optimal action $a^*(s) = \argmax_{a'}Q(s,a';\theta_2)$. Then Max-Min Double Q-learning will converge to the optimal value function $Q^*$ with probability $1$. \end{theorem} \begin{proof}[Proof of Theorem 3] This proof will closely follow Appendix A of \cite{fujimoto2018addressing}. We will first prove that $Q_2$ converges to the optimal Q value $Q^*$. Following notations of \cite{fujimoto2018addressing}, we have \begin{equation*} \begin{array}{rl} F_t(s_t,a_t) \triangleq& y_t(s_t,a_t) - Q^*(s_t, a_t) \\ =& r_t + \gamma \max_{a^{\prime} \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a^{\prime}) - Q^*(s_t, a_t) \\ =& F_t^Q(s_t, a_t) + c_t \end{array} \end{equation*} Where \begin{eqnarray*} F_t^Q(s_t, a_t) &=& r_t + \gamma Q_{t,2}(s_{t+1}, a^*) - Q^*(s_t, a_t) \\ &=& r_t + \gamma \max_{a^{\prime}} Q_{t,2}(s_{t+1}, a^{\prime}) -Q^*(s_t,a_t) \\ c_t &=& \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a') - \gamma Q_{t, 2}(s_{t+1}, a^*) \end{eqnarray*} $F^Q_t$ is associated with the optimum Bellman operator. It is well known that the optimum Bellman operator is a contractor, We need to prove $c_t$ converges to 0. Based on the update rules (Eq. (A2)), it is easy to prove that for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0. This implies that $\Delta_t(s, a^\pi) = Q_{t,1}(s,a^\pi) - Q_{t,2}(s,a^\pi)$ converges to 0 and $\Delta_t(s, a^*) = Q_{t, 1}(s,a^*) - Q_{t, 2}(s,a^*)$ converges to 0. Therefore, $\min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a) - Q_{t, 2}(s,a) \leq 0$ and the left hand side converges to zero, for $a \in {a^\pi, a^*}$. Since we have $Q_{t, 2}(s, a^*) >= Q_{t, 2}(s, a^\pi)$, then \[ \min_{i \in \{1, 2\}} Q_{t, i}(s, a^*) \leq \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a') \leq Q_{t, 2}(s,a^*) \] Therefore $c_t = \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{ i \in \{ 1, 2 \}} Q_{t, i}(s, a') - Q_{t, 2}(s,a^*)$ converges to 0. And we proved $Q_{t, 2}$ converges to $Q^*$. Since for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0, $Q_{t, 1}$ also converges to $Q^*$. \end{proof} \subsection{Self-Regularized TD Learning}\label{sec:target} Reinforcement learning is prone to instability and divergence when a nonlinear function approximator such as a neural network is used to represent the Q function~\cite{tsitsiklis1997analysis}. Mnih~\etal\cite{mnih2015human} identified several reasons for this. One is the correlation between the current action-values and the target value. Updates to $Q(s_t,a_t)$ often also increase $Q(s_{t+1},a^{*}_{t+1})$ where $a^{*}_{t+1}$ is the optimal next action. Hence, these updates also increase the target value $y_t$ which may lead to oscillations or the divergence of the policy. More formally, given transitions $(s_t,a_t,r_t,s_{t+1})$ sampled from the replay buffer distribution $\mathcal{B}$, the Q network can be trained by minimising the loss functions $\mathcal{L}(\theta_i)$ at iteration $i$: \begin{equation} \mathcal{L}(\theta_i) = \E_{(s_t,a_t) \sim \mathcal{B}}\|(Q(s_t,a_t; \theta_i) - y_i)\|^2 \end{equation} where for now let us assume $y_i= r_t + \gamma\max_{a}Q(s_{t+1},a;\theta_i)$ to be the target for iteration $i$ computed based on the current Q network parameters $\theta_i$. ${a}^{*}_{t+1}=\argmax_{a}Q(s_{t+1},a)$. If we update the parameter $\theta_{i+1}$ to reduce the loss $\mathcal{L}(\theta_i)$, it changes both $Q(s_t,a_t;\theta_{i+1})$ and $Q(s_{t+1},a_{t+1}^{*};\theta_{i+1})$. Assuming an increase in both values, then the new target value $y_{i+1} = r_t + \gamma Q(s_{t+1},a^*_{t+1}; \theta_{i+1})$ for the next iteration will also increase leading to an explosion of the Q function. We demonstrated this behavior in an ablation experiment with results in Fig.~\ref{fig:abl1}. We also show how maintaining a separate target network~\cite{mnih2015human} with frozen parameters $\theta^-$ to compute $y_{i+1} = r_t + \gamma Q(s_{t+1},a^*_{t+1}; \theta^-)$ delays the update of the target and therefore leads to more stable learning of the Q function. However, delaying the function updates also comes with the price of slowing down the learning process. We propose a self-Regularized TD-learning approach to minimize the TD-error while also keeping the change of $Q(s_{t+1},a^*_{t+1})$ small. This regularization mitigates the divergence issue~\cite{tsitsiklis1997analysis}, and no longer requires a target network that would otherwise slow down the learning process. Let $y^{\prime}_i = Q(s_{t+1},a_{t+1}^{*}; \theta_i)$, and $y_i=r_t + \gamma y^{\prime}_i$. We define the learning objective as \begin{equation} \min_{\theta} \|Q(s_t,a_t;\theta) - y_i\|^2 + \|Q(s_{t+1},a^{*}_{t+1};\theta) - y^\prime_i\|^2 \end{equation} where the first term is the original TD-Learning objective and the second term is the regularization term penalizing large updates to $Q(s_{t+1}, a^*_{t+1})$. Note that when the current Q network updates its parameters $\theta$, both $Q(s_t,a_t)$ and $Q(s_ {t+1},a^{*}_{t+1})$ change. Hence, the target value $y_i$ will also change which is different from the approach of keeping a frozen target network for a few iterations. We will demonstrate in our experiments that this self-regularized TD-Learning approach removes the delays in the update of the target value thereby achieves faster and stable learning. \subsection{Self-Guided Policy Improvement with Evolution Strategies}\label{sec:cem_a} The policy, known as the actor, can be updated through a combination of two parts. The first part, which we call Q-loss policy update, improves the policy through local gradients of the current Q function, while the second part, which we call \emph{CEM} policy update, finds a high-value action via \emph{CEM} in a broader neighborhood of the Q function landscape, and update the action distribution to concentrate towards this high-value action. We describe the two parts formally below. Given states $s_t$ sampled from the replay buffer, the Q-loss policy update maximizes the objective \begin{equation} J_{\pi}(\phi) = \E_{s_t \sim \mathcal{B},\hat{a}_t \sim \pi}[Q(s_t, \hat{a}_t)], \end{equation} where $\hat{a}_t$ is sampled from the current policy $\pi(\cdot | s_t)$. The gradient is taken through the reparameterization trick. We reparameterize the policy using a neural network transformation as described in Haarnoja~\etal~\cite{haarnoja2018soft}, \begin{equation} \hat{a}_t = f_{\phi}(\epsilon_t | s_t) \end{equation} where $\epsilon_t$ is an input noise vector, sampled from a fixed distribution, such as a standard multivariate Normal distribution. Then the gradient of $J_\pi(\phi)$ is: \begin{equation} \nabla J_{\pi}(\phi) = \E_{s_t \sim \mathcal{B}, \epsilon_t \sim \mathcal{N}}[\frac{\partial Q(s_t,f_{\phi}(\epsilon_t | s_t))} {\partial f} \frac{\partial f_\phi(\epsilon_t | s_t)}{\partial \phi}] \end{equation} For the CEM policy update, given a minibatch of states $s_t$, we first find a high-value action $\bar{a}_t$ for each state by running \emph{CEM} on the current Q function, $\bar{a}_t = \text{\emph{CEM}}(Q(s_t,\cdot), \pi(\cdot | s_t))$. Then the policy is updated to increase the probability of this high-value action. The guided update on the parameter $\phi$ of $\pi$ at iteration $i$ is \begin{equation} \E_{s_t \sim \mathcal{B}, \hat{a}_t \sim \pi} [Q(s_t,\bar{a}_t) - Q(s_t,\hat{a}_t)]_{+} \nabla_{\phi} \log\pi_i(\bar{a}_t|s_t). \end{equation} We used $Q(s_t, \hat{a}_t)$ as a baseline term, since its expectation over actions $\hat{a}_t$ will give us the normal baseline $V(s_t)$: \begin{equation} \E_{s_t\sim \mathcal{B}} [Q(s_t,\bar{a}_t)-V(s_t)] \nabla_{\phi} \log\pi_i(\bar{a}_t|s_t) \end{equation} In our implementation, we only perform an update if the improvement on the $Q$ function, $Q(s_t,\bar{a}_t)-Q(s_t,\hat{a}_t)$, is non-negative, to guard against the occasional cases where \emph{CEM} fails to find a better action. Combining both parts of updates, the final update rule on the parameter $\phi_i$ of policy $\pi_i$ is \[ \phi_{i+1} = \phi_{i} - \lambda \nabla_{\phi} J_{\pi_i}(\phi_{i} ) - \lambda \E_{s_t \sim \mathcal{B}, \hat{a}_t \sim \pi_i} [Q(s_t,\bar{a}_t) - Q(s_t,\hat{a}_t)]_{+} \nabla_{\phi} \log\pi_i(\bar{a}_t|s_t) \] where $\lambda$ is the step size. We can prove that if the Q function has converged to $Q^{\pi}$, the state-action value function induced by the current policy, then both the Q-loss policy update and the \emph{CEM} policy update will be guaranteed to improve the current policy. We formalize this result in Theorem 1 and Theorem 2, and prove them in Appendix 3.1 and 3.2. \begin{theorem} \textbf{$Q$-loss Policy Improvement} Starting from the current policy $\pi$, we maximize the objective $J_\pi = \E_{(s,a) \sim \rho_\pi(s,a)} Q^{\pi}(s,a)$. The maximization converges to a critical point denoted as $\pi_{new}$. Then the induced Q function, $Q^{\pi_{new}}$, satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{theorem} \textbf{\emph{CEM} Policy Improvement} Assuming the \emph{CEM} process is able to find the optimal action of the state-action value function, $a^*(s) = \argmax_{a}Q^{\pi}(s,a)$, where $Q^{\pi}$ is the Q function induced by the current policy $\pi$. By iteratively applying the update $ \E_{(s,a) \sim \rho_\pi(s,a)} [Q(s,a^*)-Q(s,a)]_{+}\nabla \log\pi(a^*|s)$, the policy converges to $\pi_{new}$. Then $Q^{\pi_{new}}$ satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \subsection{Max-min Double Q-Learning}\label{sec:cem_c} Q-learning~\cite{Watkins:89} is known to suffer from overestimation~\cite{thrun1993issues}. Hasselt~\etal~\cite{hasselt2010double} proposed Double-Q learning which uses two Q functions with independent sets of weights to mitigate the overestimation problem. Fujimoto~\etal~\cite{fujimoto2018addressing} proposed Clipped Double Q-learning with two Q function denoted as $Q(s,a;\theta_1)$ and $Q(s,a;\theta_2)$, or $Q_1$ and $Q_2$ in short. Given a transition $(s_t,a_t,r_t,s_{t+1})$, Clipped Double Q-learning uses the minimum between the two estimates of the Q functions when calculating the target value in TD-error~\cite{sutton1998introduction}: \begin{equation} y= r_t + \gamma\min_{j=1,2} Q(s_{t+1},\hat{a}_{t+1};\theta_j) \label{eqn:clipped} \end{equation} where $\hat{a}_{t+1}$ is the predicted next action. Fujimoto~\etal~\cite{fujimoto2018addressing} mentioned that such an update rule may induce an underestimation bias. In addition, $\hat{a}_{t+1}=\pi_{\phi}(s_{t+1})$ is the prediction of the actor network. The actor network's parameter ${\phi}$ is optimized according to the gradients of $Q_1$. In other words, $\hat{a}_{t+1}$ tends be selected according to the $Q_1$ network which consistently increases the discrepancy between the two Q-functions. In practice, we observe that the discrepancy between the two estimates of the Q-function, $|Q_1 - Q_2|$, can increase dramatically leading to an unstable learning process. An example is shown in Fig.~\ref{fig:abl2} where $Q(s_{t+1},\hat{a}_{t+1};\theta_1)$ is always bigger than $Q(s_{t+1},\hat{a}_{t+1};\theta_2)$. We introduce \emph{Max-min Double Q-Learning} to reduce the discrepancy between the Q-functions. We first select $\hat{a}_{t+1}$ according to the actor network $\pi_{\phi}(s_{t+1})$. Then we run \emph{CEM} to search the landscape of $Q_2$ within a broad neighborhood of $\hat{a}_{t+1}$ to return a second action $\tilde{a}_{t+1}$. Note that \emph{CEM} selects an action $\tilde{a}_{t+1}$ that maximises $Q_2$ while the actor network selects an action $\hat{a}_{t+1}$ that maximises $Q_1$. We gather four different Q-values: $Q(s_{t+1},\hat{a}_{t+1};\theta_1)$, $Q(s_{t+1},\hat{a}_{t+1};\theta_2)$, $Q(s_{t+1},\tilde{a}_{t+1};\theta_1)$, and $Q(s_{t+1},\tilde{a}_{t+1};\theta_2)$. We then run a max-min operation to compute the target value that cancels the biases induced by $\hat{a}_{t+1}$ and $\tilde{a}_{t+1}$. \begin{equation} \label{eq:maxmin} \begin{aligned} y & = r_t + \gamma \max\{\min_{j=1,2} Q(s_{t+1},\hat{a}_{t+1};\theta_j), \min_{j=1,2} Q(s_{t+1},\tilde{a}_{t+1};\theta_j)\} \end{aligned} \end{equation} The inner min-operation $\min_{j=1,2} Q(s_{t+1},\hat{a}_{t+1};\theta_j)$ is adopted from Eq.~\ref{eqn:clipped} and mitigates overestimation~\cite{thrun1993issues}. The outer max operation helps to reduce the difference between $Q_1$ and $Q_2$. In addition, the max operation provides a better approximation of the Bellman optimality operator~\cite{sutton1998introduction}. We visualize $Q_1$ and $Q_2$ during the learning process in Fig.~\ref{fig:abl2}. The following theorem formalizes the convergence of the proposed Max-min Double Q-Learning approach in the finite MDP setting. We prove the theorem in Appendix 3.3. \begin{theorem} \begin{equation} \begin{array}{rl} Q_{t+1, 1}(s,a) &= Q_{t,1}(s,a) + \alpha_t(s,a) (y_t-Q_{t,1}(s,a))\\ Q_{t+1, 2}(s,a) &= Q_{t,2}(s,a) + \alpha_t(s,a) (y_t-Q_{t,2}(s,a)), \end{array} \end{equation} where $\alpha_t(s,a)$ is the learning rate and $y_t$ is the target: \begin{equation} \begin{array}{cl} y_t & = r_t(s_t, a_t) + \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{1, 2 \}} Q_{t,i}(s_{t+1}, a') \\ a^{\pi} & \sim \pi(s_{t+1})\\ a^* & = argmax_{a'} Q_{t,2}(s_{t+1}, a') \\ \end{array} \end{equation} We assume that the MDP is finite and tabular and the variance of rewards are bounded, and $\gamma \in [0,1]$. We assume each state action pair is sampled an infinite number of times and both $Q_{1}$ and $Q_{2}$ receive an infinite number of updates. We further assume the learning rates satisfy $\alpha_t(s,a) \in [0,1]$, $\sum_t \alpha_t(s,a) = \infty$, $\sum_t [\alpha_t(s,a)]^2 < \infty$ with probability 1 and $\alpha_t(s,a)=0, \forall (s,a) \neq (s_t, a_t)$. Finally we assume \emph{CEM} is able to find the optimal action $a^*(s) = \argmax_{a'}Q(s,a';\theta_2)$. Then Max-Min Double Q-learning will converge to the optimal value function $Q^*$ with probability $1$. \end{theorem} \subsection{Comparative Evaluation} We present \emph{GRAC}, a self-guided and self-regularized actor-critic algorithm as summarized in Algorithm~\ref{alg:alg1}. To evaluate {\em GRAC}, we measure its performance on the suite of MuJoCo continuous control tasks~\cite{todorov2012mujoco}, interfaced through OpenAI Gym~\cite{brockman2016openai}. We compare our method with \emph{DDPG}~\cite{lillicrap2015continuous}, \emph{TD3}~\cite{fujimoto2018addressing}, \emph{TRPO}~\cite{schulman2015trust}, and \emph{SAC}~\cite{haarnoja2018soft}. We use the source code released by the original authors and adopt the same hyperparameters reported in the original papers. Hyperparameters for all experiments are in Appendix 2.1. Results are shown in Figure \ref{fig:compare_results}. {\em GRAC} outperforms or performs comparably to all other algorithms in both final performance and learning speed across all tasks. \begin{figure*}[ht!] \centering \includegraphics[width=.85\linewidth]{imgs/fig_1_all_returns_0.pdf} \begin{tabular}{ccc} \begin{minipage}{.2\textwidth} \centering \par\small{(a)~Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Hopper-v2} \end{minipage} & \begin{minipage}{.2\linewidth} \centering \par\small{(c)~Humanoid-v2} \end{minipage} \end{tabular} \includegraphics[width=.85\linewidth]{imgs/fig_1_all_returns_1.pdf} \begin{tabular}{ccc} \begin{minipage}{.2\linewidth} \centering \par\small{(d)~HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(e)~Swimmer-v2} \end{minipage} & \begin{minipage}{.2\linewidth} \centering \par\small{(f)~Walker2d-v2} \end{minipage}\\ \end{tabular} \caption{Learning curves for the OpenAI gym continuous control tasks. For each task, we train 8 instances of each algorithm, using 8 different seeds. Evaluations are performed every 5000 interactions with the environment. Each evaluation reports the return (total reward), averaged over 10 episodes. For each training seed, we use a different seed for evaluation, which results in different start states. The solid curves and shaded regions represent the mean and standard deviation, respectively, of the average return over 8 seeds. All curves are smoothed with window size 10 for visual clarity. \emph{GRAC} (orange) learns faster than other methods across all tasks. \emph{GRAC} achieves comparable result to the state-of-the-art methods on the Ant-v2 task and outperforms prior methods on the other five tasks including the complex high-dimensional Humanoid-v2.}\label{fig:compare_results} \end{figure*} \subsection{Ablation Study} In this section, we present ablation studies to understand the contribution of each proposed component: Self-Regularized TD-Learning~(Section~\ref{sec:target}), Self-Guided Policy Improvment~(Section~\ref{sec:cem_a}), and Max-min Double Q-Learning~(Section~\ref{sec:cem_c}). We present our results in Fig.~\ref{fig:table2} in which we compare the performance of {\em GRAC} with alternatives, each removing one component from GRAC. Additional learning curves can be found in Appendix 2.2. We also run experiments to examine how sensitive GRAC is to some hyperparameters such as $\alpha$ and $K$ listed in Alg.~\ref{alg:alg1}, and the results can be found in Appendix 2.4. \paragraph{Self-Regularized TD Learning} To verify the effectiveness of the proposed self-regularized TD-learning method, we apply our method to \emph{DDPG} (DDPG w/o target network w/ target regularization). We compare against two baselines: the original \emph{DDPG} and \emph{DDPG} without target networks for both actor and critic (\emph{DDPG w/o target network}). We choose DDPG, because it does not have additional components such as Double Q-Learning, which may complicate the analysis of this comparison. In Fig.~\ref{fig:abl1}, we visualize the average returns, and average $Q_1$ values over training batchs (${y^\prime}_1$ in Alg.\ref{alg:alg1}). The $Q_1$ values of \emph{DDPG w/o target network} changes dramatically which leads to poor average returns. \emph{DDPG} maintains stable Q values but makes slow progress. Our proposed \emph{DDPG} w/o target network w/ target regularization maintains stable Q values and learns considerably faster. This demonstrates the effectiveness of our method and its potentials to be applied to a wide range of DRL methods. Due to page limit, we only include results on Hopper-v2. The results on other tasks are in Appendix 2.3. All tasks exhibit a similar phenomenon. \begin{figure}[hb!] \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_0.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Hopper-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Hopper-v2} \end{minipage} \end{tabular} \caption{Learning curves and average $Q_1$ values ($y^{\prime}_1$ in Alg.~\ref{alg:alg1}) on Hopper-v2. \emph{DDPG} w/o target network quickly diverges as seen by the unrealistically high Q values. \emph{DDPG} is stable but progresses slowly. If we remove the target network and add the proposed target regularization, we both maintain stability and achieve faster learning than \emph{DDPG}.}\label{fig:abl1} \end{figure} \paragraph{Policy Improvement with Evolution Strategies} The GRAC actor network uses a combination of two actor loss functions, denoted as \emph{QLoss} and \emph{CEMLoss}. \emph{QLoss} refers to the unbiased gradient estimators which extends the \emph{DDPG}-style policy gradients~\cite{lillicrap2015continuous} to stochastic policies. \emph{CEMLoss} represents the policy improvement guided by the action found with the zero-order optmization method CEM. We run another two ablation experiments on all six control tasks and compare it with our original policy training method denoted as \emph{GRAC}. As seen in Fig.\ref{fig:table2}, in general \emph{GRAC} achieves a better performance compared to either using \emph{CEMLoss} or \emph{QLoss}. The significance of the improvements varies within the six control tasks. For example, \emph{CEMLoss} plays a dominant role in Swimmer while \emph{QLoss} has a major effect in HalfCheetah. It suggests that \emph{CEMLoss} and \emph{QLoss} are complementary. \begin{figure} \centering \includegraphics[width=0.8\textwidth]{imgs/fig_table.pdf} \caption{Final average returns, normalized w.r.t {\em GRAC} for all tasks. For each task, we train each ablation setting with 4 seeds, and average the last 10 evaluations of each seed (40 evaluations in total). Actor updates without CEMLoss (\emph{GRAC w/o CEMLoss}) and actor updates w.r.t minimum of both Q networks (\emph{GRAC w/o CriticCEM w/ minQUpdate}) achieves slightly better performance on Walker2d-v2 and Hopper-v2. GRAC achieves the best performance on 4 out of 6 tasks, especially on more challenging tasks with higher-dimensional state and action spaces (Humanoid-v2, Ant-v2, HalfCheetah-v2). This suggests that individual components of GRAC complement each other. } \label{fig:table2} \end{figure} \paragraph{Max-min Double Q-Learning} We additionally verify the effectiveness of the proposed Max-min Double Q-Learning method. We run an ablation experiment by replacing Max-min by Clipped Double Q-learing~\cite{fujimoto2018addressing} denoted as \emph{GRAC w/o CriticCEM}. In Fig.~\ref{fig:abl2}, we visualize the learning curves of the average return, $Q_1$ ($y^{\prime}_1$ in Alg.~\ref{alg:alg1}), and $Q_1-Q_2$ ($y^{\prime}_1-y^{\prime}_2$ in Alg.~\ref{alg:alg1}). \emph{GRAC} achieves high performance while maintaining a smoothly increasing Q function. Note that the difference between Q functions, $Q_1-Q_2$, remains around zero for \emph{GRAC}. \emph{GRAC w/o CriticCEM} shows high variance and drastic changes in the learned $Q_1$ value. In addition, $Q_1$ and $Q_2$ do not always agree. Such unstable Q values result in a performance crash during the learning process. Instead of Max-min Double Q Learning, another way to address the gap between $Q_1$ and $Q_2$ is to perform actor updates on the minimum of $Q_1$ and $Q_2$ networks (as seen in SAC). Replacing Max-min Double Q Learning with this trick achieves lower performance than \emph{GRAC} in more challenging tasks such as HalfCheetah-v2, Ant-v2, and Humanoid-v2 (See \emph{GRAC w/o CriticCEM w/ minQUpdate} in Fig.\ref{fig:table2}). \begin{figure}[ht!] \centering \includegraphics[width=0.8\linewidth]{imgs/fig_3_abl_critic_cem_0.pdf} \begin{tabular}{ccc} \begin{minipage}{.3\textwidth} \begin{flushright} \par\small{(a)~Returns on Ant-v2} \end{flushright} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par \small{(b)~Average of $Q_1$ over training batch on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \begin{flushleft} \par\small{(c)~Average of $Q_1-Q_2$ over training batch on Ant-v2} \end{flushleft} \end{minipage} \end{tabular} \caption{ Learning curves (left), average $Q_1$ values (middle), and average of the difference between $Q_1$ and $Q_2$ (right) on Ant-v2. Average Q values are computes as minibatch average of $y^{\prime}_1$ and $y^{\prime}_2$, defined in Alg.~\ref{alg:alg1}. \emph{GRAC w/o CriticCEM} represents replacing Max-min Double Q-Learning with Clipped Double Q-Learning. Without Max-min double Q-Learning to balance the magnitude of $Q_1$ and $Q_2$, $Q_1$ blows up significantly compared to $Q_2$, leading to divergence. }\label{fig:abl2} \end{figure} \section{Notation Table} \documentclass{article} \PassOptionsToPackage{numbers, compress}{natbib} \usepackage{neurips_2020} \usepackage{amsmath} \usepackage{amssymb} \usepackage{enumitem} \DeclareMathOperator*{\argmax}{arg\,max} \DeclareMathOperator*{\argmin}{arg\,min} \DeclareMathOperator{\E}{\mathbb{E}} \newtheorem{theorem}{Theorem} \newtheorem{thm}{Theorem} \usepackage{xcolor} \newcommand\jean[1]{\textcolor{red}{J: #1}} \newcommand\lin[1]{\textcolor{blue}{L: #1}} \newcommand\yifan[1]{\textcolor{purple}{Y: #1}} \newcommand\mengyuan[1]{\textcolor{green}{MY: #1}} \newcommand\SUN[1]{\textcolor{blue}{SUN: #1}} \usepackage{graphicx} \usepackage{mathrsfs} \usepackage{float} \usepackage{algorithmicx} \usepackage{algorithm,algpseudocode} \usepackage{algorithm} \usepackage{amsthm,amsmath,amsfonts,verbatim} \usepackage[bookmarks=true]{hyperref} \hypersetup{ colorlinks=true, urlcolor=black, } \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{hyperref} \usepackage{url} \usepackage{booktabs} \usepackage{amsfonts} \usepackage{nicefrac} \usepackage{microtype} \usepackage{caption} \captionsetup[figure]{font=footnotesize} \captionsetup[table]{font=footnotesize} \defA\arabic{equation}{A\arabic{equation}} \title{Self-Guided and Self-Regularized Actor-Critic: Appendix} \begin{document} \maketitle \section{Implementation Details} \subsection{Neural Network Architecture Details} We use a two layer feedforward neural network of 256 and 256 hidden nodes respectively. Rectified linear units~(ReLU) are put after each layer for both the actor and critic except the last layer. For the last layer of the actor network, a tanh function is used as the activation function to squash the action range within $[-1,1]$. \emph{GRAC} then multiplies the output of the tanh function by \emph{max action} to transform [-1,1] into [-\emph{max action}, \emph{max action}]. The actor network outputs the mean and sigma of a Gaussian distribution. \subsection{CEM Implementation} Our CEM implementation is based on the CEM algorithm described in Pourchot~\etal~\cite{pourchot2018cemrl}. \setcounter{algorithm}{1} \begin{algorithm}[H] \Require{Input: Q-function Q(s,a); size of population $N_{pop}$; size of elite $N_{elite}$ where $N_{elite} \leq N_{pop}$; max iteration of CEM $N_{cem}$.}\\ \Initialization{Initialize the mean $\mu$ and covariance matrix $\Sigma$ from actor network predictions.} \begin{algorithmic}[1] \For {$i=1...,N_{\text{cem}}$} \State Draw the current population set $\{a_{pop} \}$ of size $N_{pop}$ from $\mathcal{N}(\mu, \Sigma)$. \State Receive the $Q$ values $\{q_{pop}\} = \{Q(s,a) | a \in \{a_{pop}\} \}$. \State Sort $\{q_{pop}\}$ in descending order. \State Select top $N_{elite}$ Q values and choose their corresponding $a_{pop}$ as elite $\{a_{elite}\}$. \State Calculate the mean $\mu$ and covariance matrix $\Sigma$ of the set $\{ a_{elite} \}$. \EndFor \end{algorithmic} \Output{Output: The top one elite in the final iteration.} \caption{CEM} \label{alg:cem} \end{algorithm} \subsection{Additional Detail on Algorithm 1: GRAC} The actor network outputs the mean and sigma of a Gaussian distribution. In Line 2 of Alg.1, the actor has to select action $a$ based on the state $s$. In the test stage, the actor directly uses the predicted mean as output action $a$. In the training stage, the actor first samples an action $\hat{a}$ from the predicted Gaussian distribution $\pi_{\phi}(s)$, then \emph{GRAC} runs \emph{CEM} to find a second action $\tilde{a}=\emph{CEM}(Q(s,\cdot;\theta_2),\pi_{\phi}(\cdot | s)$). \emph{GRAC} uses $a=\argmax_{\{\tilde{a},\hat{a}\}}\{\min_{j=1,2} Q(s,\tilde{a};\theta_j), \min_{j=1,2} Q(s,\hat{a};\theta_j)\}$ as the final action. \section{Appendix on Experiments} \subsection{Hyperparameters used} Table~\ref{tab:hyper} and Table~\ref{tab:hyper_env} list the hyperparameters used in the experiments. $[a,b]$ denotes a linear schedule from $a$ to $b$ during the training process. \begin{table}[H] \centering \begin{tabular}{@{}p{0.3\linewidth}p{0.15\linewidth}} \hline \hline Parameters & Values \\ \hline \hline discount $\gamma$ & 0.99\\ \hline replay buffer size & 1e6\\ \hline batch size & 256 \\ \hline optimizer & Adam~\cite{kingma2014adam}\\ \hline learning rate in critic & 3e-4\\ \hline learning rate in actor & 2e-4\\ \hline $N_{\text{cem}}$ & 2\\ \hline $N_{\text{pop}}$ & 256\\ \hline $N_{\text{elite}}$ & 5\\ \hline\hline \end{tabular} \caption{Hyperparameter Table} \label{tab:hyper} \end{table} \begin{table}[H] \centering \begin{tabular}{@{}p{0.17\linewidth}p{0.12\linewidth} p{0.11\linewidth} p{0.11\linewidth} p{0.15\linewidth} p{0.14\linewidth}} \hline \hline Environments & ActionDim & $K$ in Alg.1 & $\alpha$ in Alg.1 & CemLossWeight & Reward Scale \\ \hline Ant-v2 & 8 & 20 & [0.7,~85] & 1.0/ActionDim & 1.0 \\ Hopper-v2 & 3 & 20 & [0.85,~0.95] & 0.3/ActionDim & 1.0\\ HalfCheetah-v2 & 6 & 50 & [0.7,~0.85] & 1.0/ActionDim & 0.5\\ Humanoid-v2 & 17 & 20 & [0.7,~0.85] & 1.0/ActionDim & 1.0\\ Swimmer-v2 & 2 & 20 & [0.5,~0.75] & 1.0/ActionDim & 1.0\\ Walker2d-v2 & 6 & 20 & [0.8,~0.9] & 0.3//ActionDim & 1.0\\ \hline\hline \end{tabular} \caption{Environment Specific Parameters} \label{tab:hyper_env} \end{table} \subsection{Additional Learning Curves for Policy Improvement with Evolution Strategy} \label{appendsec:experiment} \begin{figure}[H] \centering \begin{tabular}{ccc} \begin{minipage}{.3\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_ant.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_hopper.pdf} \par\small{(b)~Returns on Hopper-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_humanoid.pdf} \par\small{(c)~Returns on Humanoid-v2} \end{minipage} \end{tabular} \begin{tabular}{ccc} \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_halfcheetah.pdf} \par\small{(d)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_swimmer.pdf} \par\small{(e)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_abl_actor_loss_return_walker2d.pdf} \par\small{(f)~Returns on Walker2d-v2} \end{minipage}\\ \end{tabular} \caption{Learning curves for the OpenAI gym continuous control tasks. The \emph{GRAC} actor network uses a combination of two actor loss functions, denoted as QLoss and CEMLoss. \emph{QLoss Only} represents the actor network only trained with QLoss. \emph{CEM Loss Only} represents the actor network only trained with CEMLoss. In general \emph{GRAC} achieves a better performance compared to either using \emph{CEMLoss} or \emph{QLoss}.} \end{figure} \subsection{Additional Learning Curves for Ablation Study of Self-Regularized TD Learning} \begin{figure}[H] \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_ant.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Ant-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_halfcheetah.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on HalfCheetah-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on HalfCheetah-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_humanoid.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Humanoid-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Humanoid-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_walker2d.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Walker2d-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Walker2d-v2} \end{minipage} \end{tabular} \centering \begin{tabular}{cc} \begin{minipage}{.55\textwidth} \centering \includegraphics[width=\linewidth]{imgs/fig_2_abl_three_loss_swimmer.pdf} \end{minipage} \end{tabular} \begin{tabular}{cc} \begin{minipage}{.3\textwidth} \centering \par\small{(a)~Returns on Swimmer-v2} \end{minipage} & \begin{minipage}{.3\linewidth} \centering \par\small{(b)~Average of $Q_1$ over training batch on Swimmer-v2} \end{minipage} \end{tabular} \caption{Learning curves and average $Q_1$ values ($y^{\prime}_1$ in Alg. 1 of the main paper). \emph{DDPG} w/o target network quickly diverges as seen by the unrealistically high Q values. \emph{DDPG} is stable but often progresses slower. If we remove the target network and add the proposed target regularization, we both maintain stability and achieve a faster or comparable learning rate.} \end{figure} \subsection{Hyperparameter Sensitivity for the Termination Condition of Critic Network Training}\label{appendsubsec:termination} We also run experiments to examine how sensitive \emph{GRAC} is to some hyperparameters such as $K$ and $\alpha$ listed in Alg.1. The critic networks will be updated until the critic loss has decreased to $\alpha$ times the original loss, or at most $K$ iterations, before proceeding to update the actor network. In practice, we decrease $\alpha$ in the training process. Fig. 3 shows five learning curves on Ant-v2 running with five different hyperparameter values. We find that a moderate value of $K=10$ is enough to stabilize the training process, and increasing $K$ further does not have significant influence on training, shown on the right of Fig. 3. $\alpha$ is usually within the range of $[0.7,0.9]$ and most tasks are not sensitive to minor changes. However on the task of Swimmer-v2, we find that $\alpha$ needs to be small enough ($<0.7$) to prevent divergence. In practice, without appropriate $K$ and $\alpha$ values, divergence usually happens within the first 50k training steps, thus it is quick to select appropriate values for $K$ and $\alpha$. \begin{figure*}[ht!] \centering \begin{tabular}{cc} \begin{minipage}{.45\textwidth} \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_1.pdf} \centering \par\small{(a)~Returns on Ant-v2} \end{minipage} & \begin{minipage}{.45\linewidth} \centering \includegraphics[width=.85\linewidth]{imgs/fig_4_hyperparameter_2.pdf} \par\small{(b)~Returns on Ant-v2} \end{minipage} \end{tabular} \caption{Learning curves for the OpenAI gym Ant-v2 environment. $K$ denotes the maximum number of iterations. $\alpha$ denotes the remaining percent of loss value when terminating the iteration. In practice, we decrease $\alpha$ in the training process. $\text{alpha} a\text{\_}b$ denotes the initial value $a$ and final value $b$ for $\alpha$.}\label{fig:results} \end{figure*} \section{Theorems and Proofs} \label{appendsec:theorems} For the sake of clarity, we make the following technical assumption about the function approximation capacity of neural networks that we use to approximate the action distribution. \textbf{State separation assumption:} The neural network chosen to approximate the policy family $\Pi$ is expressive enough to approximate the action distribution for each state $\pi(s,\cdot)$ separately. \subsection{Theorem 1: \textbf{$Q$-loss Policy Improvement}} \label{appendsubsec:theorem1} \begin{theorem} Starting from the current policy $\pi$, we update the policy to maximize the objective $J_\pi = \E_{(s,a) \sim \rho_\pi(s,a)} Q^{\pi}(s,a)$. The maximization converges to a critical point denoted as $\pi_{new}$. Then the induced Q function, $Q^{\pi_{new}}$, satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 1] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately, for each state we are maximizing $\E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a)$. Therefore, we have $\forall s, \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. \begin{equation} \begin{array}{rl} Q^{\pi}(s,a) &= r(s,a) + \gamma \E_{s^{\prime}}V^{\pi}(s^{\prime}) \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} Q^{\pi}(s^{\prime}, a^{\prime}) \\ &= r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} [r(s^{\prime}, a^{\prime}) + \gamma \E_{s^{\prime \prime}} V^{\pi}(s^{\prime \prime})] \\ &\leq r(s,a) + \gamma \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} r(s^{\prime}, a^{\prime}) + \gamma^2 \E_{s^{\prime}} \E_{a^{\prime} \sim \pi_{new}} \E_{s^{\prime \prime}} \E_{a^{\prime \prime} \sim \pi_{new}} Q^{\pi}(s^{\prime \prime}, a^{\prime \prime}) \\ &= \ldots \quad \mbox{(repeatedly unroll Q function )} \\ &\leq Q^{\pi_{new}}(s,a) \end{array} \end{equation} \end{proof} \subsection{Theorem 2: \textbf{\emph{CEM} Policy Improvement}} \label{appendsubsec:theorem2} \begin{theorem} We assume that the \emph{CEM} process is able to find the optimal action of the state-action value function, $a^*(s) = \argmax_{a}Q^{\pi}(s,a)$, where $Q^{\pi}$ is the Q function induced by the current policy $\pi$. By iteratively applying the update $ \E_{(s,a) \sim \rho_\pi(s,a)} [Q(s,a^*)-Q(s,a)]_{+}\nabla \log\pi(a^*|s)$, the policy converges to $\pi_{new}$. Then $Q^{\pi_{new}}$ satisfies $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a).$ \end{theorem} \begin{proof}[Proof of Theorem 2] Under the state separation assumption, the action distribution for each state, $\pi(s, \cdot)$, can be updated separately. Then, for each state $s$, the policy $\pi_{new}$ will converge to a delta function at $a^*(s)$. Therefore we have $\forall s, \max_a Q^{\pi}(s,a) = \E_{a \sim \pi_{new}(s,\cdot)} Q^{\pi}(s,a) \geq \E_{a \sim \pi(s,\cdot)} Q^{\pi}(s,a) = V^{\pi}(s)$. Then, following Eq. (1) we have $\forall (s,a), Q^{\pi_{new}}(s,a) \geq Q^{\pi}(s,a)$ \end{proof} \subsection{Theorem 3: \textbf{Max-Min Double Q-learning Convergence}} \label{appendsubsec:theorem3} \begin{theorem} We keep two tabular value estimates $Q_{1}$ and $Q_{2}$, and update via \begin{equation} \begin{array}{rl} Q_{t+1, 1}(s,a) &= Q_{t,1}(s,a) + \alpha_t(s,a) (y_t-Q_{t,1}(s,a))\\ Q_{t+1, 2}(s,a) &= Q_{t,2}(s,a) + \alpha_t(s,a) (y_t-Q_{t,2}(s,a)), \end{array} \end{equation} where $\alpha_t(s,a)$ is the learning rate and $y_t$ is the target: \begin{equation} \begin{array}{cl} y_t & = r_t(s_t, a_t) + \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{1, 2 \}} Q_{t,i}(s_{t+1}, a') \\ a^{\pi} & \sim \pi(s_{t+1})\\ a^* & = argmax_{a'} Q_{t,2}(s_{t+1}, a') \\ \end{array} \end{equation} We assume that the MDP is finite and tabular and the variance of rewards are bounded, and $\gamma \in [0,1]$. We assume each state action pair is sampled an infinite number of times and both $Q_{1}$ and $Q_{2}$ receive an infinite number of updates. We further assume the learning rates satisfy $\alpha_t(s,a) \in [0,1]$, $\sum_t \alpha_t(s,a) = \infty$, $\sum_t [\alpha_t(s,a)]^2 < \infty$ with probability 1 and $\alpha_t(s,a)=0, \forall (s,a) \neq (s_t, a_t)$. Finally we assume \emph{CEM} is able to find the optimal action $a^*(s) = \argmax_{a'}Q(s,a';\theta_2)$. Then Max-Min Double Q-learning will converge to the optimal value function $Q^*$ with probability $1$. \end{theorem} \begin{proof}[Proof of Theorem 3] This proof will closely follow Appendix A of \cite{fujimoto2018addressing}. We will first prove that $Q_2$ converges to the optimal Q value $Q^*$. Following notations of \cite{fujimoto2018addressing}, we have \begin{equation*} \begin{array}{rl} F_t(s_t,a_t) \triangleq& y_t(s_t,a_t) - Q^*(s_t, a_t) \\ =& r_t + \gamma \max_{a^{\prime} \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a^{\prime}) - Q^*(s_t, a_t) \\ =& F_t^Q(s_t, a_t) + c_t \end{array} \end{equation*} Where \begin{eqnarray*} F_t^Q(s_t, a_t) &=& r_t + \gamma Q_{t,2}(s_{t+1}, a^*) - Q^*(s_t, a_t) \\ &=& r_t + \gamma \max_{a^{\prime}} Q_{t,2}(s_{t+1}, a^{\prime}) -Q^*(s_t,a_t) \\ c_t &=& \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s_{t+1}, a') - \gamma Q_{t, 2}(s_{t+1}, a^*) \end{eqnarray*} $F^Q_t$ is associated with the optimum Bellman operator. It is well known that the optimum Bellman operator is a contractor, We need to prove $c_t$ converges to 0. Based on the update rules (Eq. (A2)), it is easy to prove that for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0. This implies that $\Delta_t(s, a^\pi) = Q_{t,1}(s,a^\pi) - Q_{t,2}(s,a^\pi)$ converges to 0 and $\Delta_t(s, a^*) = Q_{t, 1}(s,a^*) - Q_{t, 2}(s,a^*)$ converges to 0. Therefore, $\min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a) - Q_{t, 2}(s,a) \leq 0$ and the left hand side converges to zero, for $a \in {a^\pi, a^*}$. Since we have $Q_{t, 2}(s, a^*) >= Q_{t, 2}(s, a^\pi)$, then \[ \min_{i \in \{1, 2\}} Q_{t, i}(s, a^*) \leq \max_{a' \in \{a^{\pi}, a^* \}} \min_{i \in \{ 1, 2 \}} Q_{t, i}(s, a') \leq Q_{t, 2}(s,a^*) \] Therefore $c_t = \gamma \max_{a' \in \{a^{\pi}, a^* \}} \min_{ i \in \{ 1, 2 \}} Q_{t, i}(s, a') - Q_{t, 2}(s,a^*)$ converges to 0. And we proved $Q_{t, 2}$ converges to $Q^*$. Since for any tuple $(s, a)$, $\Delta_t(s, a) = Q_{t, 1}(s,a) - Q_{t, 2}(s,a)$ converges to 0, $Q_{t, 1}$ also converges to $Q^*$. \end{proof}
{'timestamp': '2020-09-21T02:18:36', 'yymm': '2009', 'arxiv_id': '2009.08973', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08973'}
arxiv
\section{Introduction} In industry, we often find combinatorial optimisation problems that are non-trivial and NP-hard, which means that in practice, they cannot be solved in polynomial time. Examples of such problems are production process planning or scheduling in single- or multi-objective domains. One of the most common is the Permutation Flow Shop Scheduling Problem (PFSP) \cite{ltgaPopulationSizing,productionSchedulingIeee}. The objective of PFSP is to optimise production quality. A solution in PFSP defines an order in which the production tasks (jobs) are put on the plan by a scheduler. PSFP is considered in single- \cite{ltgaPopulationSizing,productionSchedulingIeee}, multi- \cite{productionSchedulingMO,productionMOrealNumber} and many-objective versions \cite{productionSchedulingManyO}. For some of the problems that emerge from industry optimisation, real numbers are employed to encode a solution \cite{productionMOrealNumber,productionYorkRealNumbers}. For others, sets of discrete values (including binary values) can be used \cite{productionDiscrete,paintsOrig}.\par In this paper, we consider a problem of manufacturing process planning in factories producing bulk commodities. Such a process is comprised of manufacturing recipe selection and resource allocation. The main optimisation objective of this case study is to increase production line utilisation and, consequently, to decrease the total production time (makespan) of batch production by executing an appropriate number of recipes producing ordered amounts of commodities. The extension beyond the typical covering problem is that the amount of the commodities produced should be as close to the ordered ones as possible (i.e., the surpluses should be minimised). The considered problem is an instance of multi-objective optimisation and, as such, is referred to as the multi-objective bulk commodity production problem (MOBCPP) in this paper. This problem is practical and, being an extension of a classic covering problem, belongs to the NP-hard class \cite{Garey1990}. MOBCPP is a multi-objective problem. In multi-objective optimisation we consider $m$ objective functions $f_i(x), i \in \{0,1,\ldots,m-1\}$. Without loss of generality, we may state that the values of all these functions are to be minimised. In this paper, we only consider problems with solutions encoded by $l$ discrete (binary) variables. Thus, a solution $x$ is a binary vector $x=(x_0,x_1,\ldots,x_{l-1})$. For each $x$, the objective value vector is $f(x) = (f_0(x),f_1(x),\ldots,f_{m-1}(x))$.\par A method in multi-objective optimisation is expected to return a Pareto front \cite{MoGomeaGecco,EliteArchive}. A Pareto front is a set of non-dominated solutions. A solution $x^0$ \textit{dominates} a solution $x^1$ if and only if $f_i(x^0) \leq f_i(x^1)$ $\forall{i}\in \{0,1,\ldots,m-1\}$ and $f(x^0)\neq f(x^1)$. A solution that is not dominated by any other solution is a Pareto-optimal solution. A Pareto-optimal set $\mathcal{P}_S$ is a set of all Pareto-optimal solutions. The Pareto-optimal front $\mathcal{P}_F$ is a set of objective value vectors of all Pareto-optimal solutions. The number of Pareto-optimal solutions may be large for many problems (in continuous optimisation it is often infinite). Therefore, usually, it is sufficient to find a good approximation of $\mathcal{P}_F$.\par \begin{comment} The recipes can be executed on different compatible resources. Various recipes can be used to produce the same commodity. Consequently, the decision problem includes the selection of the multisubset (i.e.\ a combination with repetitions) of the recipes and their allocation to compatible resources, such that the appropriate amount of goods are produced with the minimal surplus in the shortest possible time. As such, the problem resembles, to a certain degree, FJSP with process plan flexibility (FJSP-PPF) \cite{Ozguven2010} or the earlier-formulated ``JSP with alternative process plans" \cite{Thomalla2001}. However, none of the papers known to the authors considers process planning by recipe multisubset selection to satisfy both the criteria of the shortest makespan and the minimal surplus of the ordered commodities. \end{comment} If the scale of problem instances is large, metaheuristics may be employed as effective and efficient solvers \cite{paintsOrig,muppetsBaldwinEon,productionYorkRealNumbers,ltgaPopulationSizing}. Evolutionary methods are capable of supporting high-quality solutions consuming a reasonable amount of computation resources. In some practical problems, there are more than one contradicting objectives to optimise. For such problems, instead of a single solution, a set of so-called Pareto optimal solutions is sought. For each of these solutions, improving a single objective causes worsening at least one other objective.\par Many methods have been proposed for multi-objective optimisation, for instance, the well-known NSGA-II \cite{nsga2} that employs mechanisms to bias the evolutionary search towards $\mathcal{P}_F$ and preserves the diversity of the final Pareto front approximation. Another proposition is the Multi-Objective Evolutionary Algorithm based on Decomposition (MOEA/D) \cite{moead,Zhou2011,Ma2014b,Ma2014,Ma2016}. The idea behind MOEA/D is to divide a Pareto front and exchange information only between individuals that optimise a similar part of $\mathcal{P}_F$. One of the key advantages of MOEA/D when compared to NSGA-II is that it does not require the computation of so-called crowding distance that is computationally expensive. NSGA-II and MOEA/D are typical reference methods in multi-objective optimisation \cite{MoGomeaSwarm}, so they are also employed as the baseline in this paper.\par Solutions for the considered MOBCPP problem are binary-coded. Thus, solution space is a discrete one. The methods that employ linkage learning are particularly effective in the optimisation of problems characterised by such solution spaces. This observation applies to both: theoretical \cite{muppets,3lo,MoGomeaSwarm,ltga} and practical problems \cite{ltgaPopulationSizing,subpopInitLL,mupMemo}. It is also shown that methods employing linkage learning may significantly outperform the other that do not use such techniques \cite{muppets,mohBOA,MoGomeaSwarm,mupMemo}. One of the recent propositions dedicated to solving multi-objective problems is the Multi-objective Gene-pool Optimal Mixing Evolutionary Algorithm (MO-GOMEA) \cite{MoGomeaGecco,MoGomeaSwarm}. MO-GOMEA is based on the concept of the Linkage Tree Genetic Algorithm (LTGA) \cite{ltga,ltgaGomeaNaming,ltgaPopulationSizing}. LTGA is a Genetic Algorithm (GA) that employs linkage learning techniques \cite{3lo,P3Original,ltga,dsmga2} to improve its effectiveness. Similarly to LTGA in the single-objective domains, MO-GOMEA has significantly outperformed competing methods (including NSGA-II and MOEA/D) in multi-objective optimisation \cite{MoGomeaGecco,MoGomeaSwarm}. Among all, to obtain high-quality results, MO-GOMEA clusters the population and processes the subpopulations separately. Therefore, it is capable of optimising different Pareto front parts separately, with the use of linkage that is supposed to describe the features of each Pareto front part. \par According to \cite{linkageQuality}, the methods that employ linkage learning are dependent on the quality of the linkage they use. If the quality of linkage is too low, linkage-based methods perform similarly to their competitors that do not consider gene-dependencies. In \cite{linkLearningDetermined}, the authors check the dependency between the method's effectiveness and the linkage learning model. They show that if the problem structure is complex (there are many gene dependencies) \cite{watsonHiff,watsonHiffPPSNfirst}, it is favourable to learn linkage during the method execution rather than obtaining the linkage in the pre-optimisation step. Finally, in \cite{3lo}, the authors show that to assure the method's effectiveness, the linkage should be of high quality, but it also should be diverse. To obtain this, they propose a method that utilises a multi-population approach. Note that the multi-population approaches are usually employed to increase population diversity \cite{subpopInitLL,muppets,mupMemo}, but they may also be useful in obtaining a diverse linkage \cite{3lo}. Note that the lack of linkage learning diversity may be a likely reason for a poor performance of LTGA shown in \cite{linkageLearningIsBad}. The research considering the influence of linkage quality on the methods' performance is in its early stage. For instance, it requires further investigation of the reasons why linkage diversity is important to effectively solve problems with complex structure (including so-called overlapping building blocks, which is a typical feature of practical problems) \cite{3lo}. Nevertheless, the objective of this paper is to use the conclusions of the research that has been already made in this area, and to apply these conclusions as intuitions that shall guide us to proposing an effective method for solving the MOBCPP problem. If the intuitions are precise, such a method shall also be effective in solving typical benchmarks employed in a multi-objective optimisation.\par As stated before, MO-GOMEA is a state-of-the-art method for multi-objective optimisation. However, despite its high effectiveness, it also has some disadvantages. First, it requires a clusterisation of the population. The number of required clusters is adjusted automatically at runtime. However, if the number of clusters is too low or too high, the method may become ineffective \cite{MoGomeaGecco}. Second, although LTGA (the single-objective base of MO-GOMEA) is highly effective in single-objective optimisation for problems with so-called overlapping blocks, it is outperformed by Parameter-less Population Pyramid (P3) \cite{3lo,P3Original,fP3,afP3}. P3 is another state-of-the-art method in single-objective optimisation. The problems with overlapping blocks contain blocks of highly-dependent genes. However, some of the genes in these blocks are also dependent on the genes from other blocks \cite{3lo,P3Original,fP3,afP3}. The feature of inter-block dependencies is typical for practical problems \cite{watsonHiff,watsonHiffPPSNfirst}.\par In this paper, we propose a Multi-objective Parameter-less Population Pyramid (MO-P3) to solve the MOBCPP problem effectively. The motivations behind proposing this method are as follows. In contrast to LTGA, P3 maintains numerous different linkages at the same time that should be beneficial for practical problems \cite{3lo}. MO-P3 uses this linkage diversity to omit the necessity of population clusterisation. P3 is a relatively recent method proposition that effectively solves single-objective problems with overlapping blocks. For such problems, P3 has been shown to be significantly more effective than LTGA and Dependency Structure Matrix Genetic Algorithm II (DSMGA-II) \cite{dsmga2}. Since practical problems often contain blocks that overlap \cite{watsonHiff,watsonHiffPPSNfirst}, P3 seems to be a good starting point for solving the practical multi-objective problem considered in this paper. At each MO-P3 iteration, a new individual is added to the population and updated with the use of collected linkages and the rest of the population, similarly to P3. However, in MO-P3, each new individual is assigned a weight vector that directs the search towards a chosen part of the Pareto front. Such a feature may be found similar to the MOEA/D behaviour.\par The extensive experimental work described in this paper shows that for the considered practical problem, MO-P3 yields results of a higher quality than NSGA-II and MOEA/D. MO-P3 also yields slightly better results than MO-GOMEA. However, its main advantage over MO-GOMEA is that MO-P3 obtains high-quality results significantly faster for MOBCPP (considering both fitness evaluations and computation time). We also present the MO-P3 performance on typical benchmarks. Except for one of them, MO-P3 outperforms all competing methods. Therefore, MO-P3 may be found useful in solving multi-objective problems. Thus, the contribution of this paper is threefold. First, we propose a method dedicated to solving a hard and industrially-relevant practical problem. Second, we fill the gap in the field of Evolutionary Computation that is the lack of a P3-based method dedicated to solving multi-objective problems. Finally, we show that MO-P3 is highly competitive when a typical benchmark set is considered, so we can clearly state that our contribution goes beyond the original problem we set out to solve, and that we propose a new and effective method for multi-objective discrete optimisation.\par The rest of this paper is organised as follows. In the next section, we present the related work that includes linkage learning, the presentation of the state-of-the-art methods employing linkage, the issue of Pareto front clusterisation and MO-GOMEA. In Section \ref{sec:problemDef}, we define the MOBCPP problem. In the fourth section, we describe the proposed MO-P3 approach in detail. Sections \ref{sec:exp:paints} and \ref{sec:exp:benchmarks} report the results obtained for MOBCPP and the benchmark problems, respectively. The results are discussed in the seventh section. Finally, the last section points the future research directions and concludes this paper. \section{Related Work} \label{sec:relWork} In this section, we present the research related to our propositions. Therefore, in the first subsection, we discuss in detail the issue of linkage learning and linkage learning techniques employed by methods considered in this paper. In Section \ref{sec:relWork:dsmMethods}, we show the details of modern evolutionary methods. These methods are single-objective, but one of them is the base of our proposition and another one is the base of the main competing method considered in this paper. In the fifth subsection, we present the latest advances in discrete multi-objective optimisation. Finally, in the last two subsections, we present MOEA/D in more detail and review previous research related to manufacturing scheduling using multi-objective GAs. \subsection{Linkage Learning} \label{sec:relWork:ll} Linkage learning is one of the techniques that are used to detect features of a problem to be optimised. Such knowledge is used during runtime to improve its effectiveness and efficiency. In this section, we present the general linkage classifications and more recent techniques employed by state-of-the-art methods in evolutionary computation. In this paper we concentrate on linkage learning techniques dedicated for discrete domains. However, problem decomposition was found useful also in continuous domains \cite{ieeeSurvey}. \subsubsection{General Description and Classifications} \label{sec:relWork:ll:general} Linkage is a piece of information that describes possible dependencies between genes. If such knowledge is accurate and used properly, it may significantly increase the effectiveness of an evolutionary method. In recent years, many different techniques were proposed to obtain linkage. These techniques may be classified with regard to their features. For instance, linkage learning techniques may be classified on the base of: how good and bad linkage are distinguished, how linkage is represented and how linkage is stored \cite{llClassification}. If a method uses only a fitness value to differentiate between a good and bad linkage, it employs a \textit{unimetric way}, which is typical for older Genetic Algorithms (GAs), but some relatively modern methods also adopt it \cite{muppets,muppetsActive}. Nevertheless, current state-of-the-art methods (e.g., Parameter-less Population Pyramid (P3) \cite{P3Original}, Dependency Structure Matrix Genetic Algorithm (DSMGA-II) \cite{dsmga2}, Linkage Tree Genetic Algorithm (LTGA) \cite{ltga}) employ a multi-metric approach, which means that they use more measures than pure fitness to find the linkage of high quality. If the linkage is represented by dedicated structures (e.g., trees, graphs, matrices or other), such representation is called \textit{virtual}. The linkage represented by the position of the gene in a genotype is called \textit{physical} \cite{muppets}. Finally, the linkage may be stored in one central database or it may be distributed in the population (i.e., each individual may carry its own linkage information).\par More recent linkage classification was proposed in \cite{DSMorig} and was supplemented in \cite{omidvar,muppetsBaldwinEon}. It considers five different ways of linkage generation. The first class uses a perturbation and analyses the subsequent fitness changes \cite{omidvar}. Another way to generate linkage is to evolve the order of the genes in the chromosome, which is referred to as \textit{interaction adaptation} \cite{muppets}. An evolutionary method may also build probabilistic models like the Estimation of Distribution Algorithms \cite{mohBOA}. Surprisingly, linkage generated randomly, in some situations, may also improve the method's effectiveness \cite{linkageRandom}. Finally, the last class (proposed in \cite{muppetsBaldwinEon}) is a comparison of evolution results. The methods employing this technique compare the individuals that resulted from different evolutionary processes to obtain linkage. Similar classification of linkage techniques that are employed in Cooperative Coevolution may be found in \cite{linkageClassificationCC}. \subsubsection{Dependency Structure Matrix} \label{sec:relWork:ll:dsm} The Dependency Structure Matrix (DSM) is a square matrix that stores the dependencies occurring between the components (genes). This structure is derived from information theory~\cite{dsmga2} and is applied in evolutionary methods to describe gene dependencies. The problem size $n$, where $n$ is a number of genes, determines the size of DSM. Each element $d_{i, j} \in R$ of $\mathrm{DSM} = [d_{i, j}]_{n \times n}$ indicates how significantly the $i^{th}$ and $j^{th}$ genes are dependent on each other. Usually, mutual information~\cite{mutualInformation} is used as the dependency measure. It is defined as \begin{equation} \label{eq:mutualInformation} I(X, Y) = \sum_{x \in X} \sum_{y \in Y} p(x, y) \ln\frac{p(x,y)}{p(x)p(y)} \geq 0, \end{equation} where $X$ and $Y$ are random variables. The value of mutual information is proportional to the dependency strength between the pair of genes. If $X$ and $Y$ are independent, the value of $I(X,Y)$ is low, because \begin{equation} p(x,y) = p(x)p(y) \implies \ln{\frac{p(x,y)}{p(x)p(y)}} = \ln{1} = 0. \end{equation} It is also assumed that $\ln{\frac{p(x,y)}{p(x)p(y)}}$ equals $0$ when $p(x,y)$, $p(x)$ or $p(y)$ is equal to $0$ as well. \begin{table} \caption{Population of individuals to demonstrate the DSM creation procedure} \centering% \label{tab:populationDSM} \begin{tabular}{ccccc} \hline \multirow{2}{*} {\textbf{Population}} & \multicolumn{4}{c}{\textbf{Genotype}} \\ & $G_1$ & $G_2$ & $G_3$ & $G_4$ \\ \hline $1^{st}$ individual & 0 & 1 & 0 & 1 \\ $2^{nd}$ individual & 0 & 1 & 0 & 1 \\ $3^{rd}$ individual & 1 & 1 & 1 & 1 \\ $4^{th}$ individual & 1 & 1 & 0 & 1 \\ $5^{th}$ individual & 0 & 0 & 1 & 1 \\ \hline \end{tabular} \end{table} To demonstrate the process of DSM creation, we use the population of $5$ binary-coded individuals presented in Table~\ref{tab:populationDSM}, where $G_i$ denotes the $i^{th}$ gene. Formula~(\ref{eq:mutualInformation}) represents the mutual information that can be calculated for any pair of random variables. Particularly, it can be used to measure the dependency between any two genes. Thus, a binary-adjusted version of formula~(\ref{eq:mutualInformation}) may be defined as \begin{equation} \label{eq:mutualInformationGenes} I(G_i, G_j) = \sum_{g_i \in G_i} \sum_{g_j \in G_j} p_{i,j}(g_i, g_j) \ln\frac{p_{i,j}(g_i, g_j)}{p_i(g_i)p_j(g_j)}, \end{equation} where $g_i$ and $g_j$ indicate the possible values of the $i^{th}$ ($G_i$) and $j^{th}$ ($G_j$) genes, respectively. For instance, if an optimisation problem is binary then $g_i \in \{0, 1\} = G_i$ and $g_j \in \{0, 1\} = G_j$. To calculate the probabilities presented in formula~(\ref{eq:mutualInformationGenes}), all individuals in a population are taken into consideration. The $p_{i,j}(g_i, g_j)$ value denotes the joint probability that a value of the $i^{th}$ gene is $g_i$ and the $j^{th}$ gene has value $g_j$ simultaneously. Moreover, $p_i(g_i)$ is used to indicate the probability that a value of the $i^{th}$ gene is $g_i$. Table~\ref{tab:DSM} presents DSM obtained for the population shown in Table~\ref{tab:populationDSM}. All DSM entries presented in Table~\ref{tab:DSM} have been calculated using formula~(\ref{eq:mutualInformationGenes}). \begin{table} \caption{DSM for the population presented in Table~\ref{tab:populationDSM}} \centering \label{tab:DSM} \begin{tabular}{ccccc} \hline \textbf{} & $G_1$ & $G_2$ & $G_3$ & $G_4$ \\ \hline $G_1$ & X & 0.12 & 0.00 & 0.00 \\ $G_2$ & 0.12 & X & 0.22 & 0.00 \\ $G_3$ & 0.00 & 0.22 & X & 0.00 \\ $G_4$ & 0.00 & 0.00 & 0.00 & X \\ \hline \end{tabular} \end{table} DSM-based linkage learning may lead to excellent results and is employed by leading methods in the field of discrete optimisation \cite{P3Original,ltga,psDSMGA2,dsmga2}. For some problems, it facilitates finding a high-quality linkage \cite{ltga}, which is crucial to solve the problem. Additionally, it aids updating the linkage information during runtime, which is key when addressing problems with complex structure \cite{linkLearningDetermined}. Such a structure may be commonly found in practical problems \cite{watsonHiff,watsonHiffPPSNfirst}.\par As presented in \cite{linkageQuality}, not all problem types are easy to decompose for a DSM-based linkage learning. Recently, Linkage Learning based on Local Optimisation (3LO) was proposed in \cite{3lo}. 3LO is an empirical linkage learning technique, which means that the dependencies \textit{predicted} by other linkage learning techniques are replaced based on an empirical check. Thanks to the idea behind it, 3LO is proven not to report any \textit{false linkage}. The \textit{false linkage} takes place when two independent genes are pointed as being dependent by a linkage learning technique. A drawback of 3LO is its computational cost. Therefore, the methods using it perform worse when overlapping problems need to be solved \cite{3lo}. This observation justifies the choice of a DSM-using method as the base of our proposition. \subsubsection{Linkage Trees} \label{sec:relWork:ll:linkTree} DSM has been created to find linkage and it contains only pairwise gene-dependency values. Therefore, a clustering algorithm is employed to merge pairs of genes into larger groups. Different techniques of DSM utilisation were proposed~\cite{dsmga2, dsmga2e, ltga, P3Original}. The only technique employed by methods considered in this paper is the linkage tree construction algorithm and hence it is described in details below. Nevertheless, at the end of this section, we also give some insights into other DSM utilisation techniques.\par To construct a linkage tree, the distance $D(G_i, G_j)$ between the $i^{th}$ and $j^{th}$ genes is calculated using mutual information (formula~(\ref{eq:mutualInformationGenes})) and joint entropy: \begin{equation} \label{eq:distanceMeause} D(G_i, G_j) = \frac{H(G_i, G_j) - I(G_i, G_j)}{H(G_i, G_j)}, \end{equation} where \begin{equation} \label{eq:entropy} H(G_i, G_j) = - \sum_{g_i \in G_i} \sum_{g_j \in G_j} p_{i,j}(g_i, g_j) \ln{p_{i,j}(g_i, g_j)}. \end{equation} Note that $H(G_i, G_j)$ equal $0$ implies that distance $D(G_i, G_j)$ is $0$ as well. In Table~\ref{tab:distances}, we report values of gene distances computed for the population presented in Table~\ref{tab:populationDSM}. \begin{table} \caption{Distances between genes for the population presented in Table~\ref{tab:populationDSM}} \centering \label{tab:distances} \begin{tabular}{ccccc} \hline \textbf{} & $G_1$ & $G_2$ & $G_3$ & $G_4$ \\ \hline $G_1$ & X & 0.88 & 1.00 & 1.00 \\ $G_2$ & 0.88 & X & 0.76 & 1.00 \\ $G_3$ & 1.00 & 0.76 & X & 1.00 \\ $G_4$ & 1.00 & 1.00 & 1.00 & X \\ \hline \end{tabular} \end{table} A linkage tree consists of the nodes corresponding to the clusters which group the genes that are considered to be dependent on one another. During linkage tree construction, the two most related clusters are joined. Initially, the clusters containing one consecutive single gene are created. Thus, the linkage tree construction algorithm creates $n$ single-gene clusters, where $n$ is the given optimisation problem size. Then, the merging operation is repeated until only one cluster (consisting of all genes) remains. Formula~(\ref{eq:distanceMeause}) is used to calculate the distance between two clusters which contain only a single gene. If one of the clusters contains more than one gene, the following reduction formula is used: \begin{equation} D(C_k, (C_i \cup C_j)) = \frac{|C_i|}{|C_i| + |C_j|} D(C_k, C_i) + \frac{|C_j|}{|C_i| + |C_j|} D(C_k, C_j), \end{equation} where $|C_i|$, $|C_j|$ and $|C_k|$ indicate the sizes of clusters $C_i$, $C_j$ and $C_k$, respectively. According to Table~\ref{tab:distances}, the distance between clusters $\{G_1\}$ and $\{G_2, G_3\}$ is calculated as follows: \begin{equation} \begin{aligned} D(\{G_1\}, (\{G_2\} \cup \{G_3\})) &= \frac{|\{G_1\}|}{|\{G_2\}| + |\{G_3\}|} D(\{G_1\}, \{G_2\}) \\ &+ \frac{|\{G_3\}|}{|\{G_2\}| + |\{G_3\}|} D(\{G_1\}, \{G_3\}) \\ &= \frac{0.88}{2} + \frac{1}{2} = 0.94. \end{aligned} \end{equation} The process of the linkage tree creation for DSM given in Table~\ref{tab:populationDSM} is presented step by step in Figure~\ref{fig:linkageTreeCreation}. To simplify the diagram, indication $G_i$ has been replaced by number $i$. For instance, in Figure~\ref{fig:linkageTreeCreation}, we use $1$ instead of $G_1$. \begin{figure} \centering \includegraphics[width=0.75\linewidth]{linkage_tree_creation.png} \caption{Subsequent steps of the linkage tree creation process for the population from Table~\ref{tab:populationDSM}} \label{fig:linkageTreeCreation} \end{figure} Linkage trees are employed by Linkage Tree Genetic Algorithm (LTGA) \cite{ltga}, also denoted as Linkage Tree Gene-pool Optimal Mixing Evolutionary Algorithm (LT-GOMEA) \cite{ltgaGomeaNaming}. Another method that employs linkage trees is Parameter-less Population Pyramid (P3) \cite{P3Original,fP3}. Both methods are described in the next subsection.\par Another way of using DSM is creation of an incremental linkage set. The incremental linkage set consists of sequences of gene starting indexes. During the process of gene-sequence creation, a single gene index is selected randomly. Then, the index that has the strongest relation to the last gene in the sequence and is not included in the sequence is added to the sequence. Incremental linkage sets are employed by Dependency Structure Matrix Genetic Algorithm II (DSMGA-II) \cite{dsmga2} and Two-edge Dependency Structure Matrix Genetic Algorithm II (DMSGA-IIe) \cite{dsmga2e} that are presented in the next section. \subsection{DSM-using Methods} \label{sec:relWork:dsmMethods} In this section, we present different methods that employ DSM and information theory for linkage discovery. \subsubsection{Linkage Tree Genetic Algorithm} \label{sec:relWork:dsmMethods:ltga} Linkage trees have been employed by Linkage Tree Genetic Algorithm (LTGA)~\cite{ltga, ltgaPopulationSizing}, one of the first methods using DSM which has been shown to be highly effective. LTGA is a population-based method that uses the linkage tree construction algorithm described in Section \ref{sec:relWork:ll:linkTree}. Recently, LTGA has been improved and renamed to Linkage Tree Gene-pool Optimal Mixing Evolutionary Algorithm (LT-GOMEA) \cite{ltgaPopulationSizing}. \par Instead of crossover, LTGA uses the operator called optimal mixing (OM). During OM, two individuals (called \textit{source} and \textit{donor}) and a cluster (a node from a linkage tree) are involved. The genes from the donor individual that are marked by the cluster replace the appropriate genes in the source individual. The operation is reversed if the fitness of the source decreases. Otherwise, the source remains modified. All individuals in the population are mixed using OM. During OM, all clusters except the linkage tree root are considered. The donor is selected randomly for each cluster. If, after OM, an individual remains unmodified, OM is executed for this individual once again with the best-found individual as the donor. This step is called the force improvements (FI) phase. The second situation in which FI is executed takes place when the best-found individual has not been improved for a certain number of iterations. \par As an example of OM, let us consider a 6-bit binary problem. The genotype of a source individual is $110011$, and its fitness is 6. The first considered cluster marks genes 1,2, and 5, and the donor individual is $010101$. After mixing, the genotype of the donor individual will be $010001$, and its fitness will decrease to 4. Therefore, the change introduced by mixing is rejected (we wish to maximise the fitness). The second considered cluster marks genes 2 and 3, and the randomly chosen donor individual for this cluster is $000111$. After mixing, the donor's genotype will be $000101$, and its fitness will be 6. Since fitness has not decreased, the change is preserved. The third cluster marks genes from 2 to 5, and the individual chosen for this cluster is $111111$. After mixing, the genotype of the donor will be $011111$, and its fitness will be 7. Therefore, the change will be preserved. The operation of OM will continue in the manner shown above until all the clusters that do not cover the whole genotype will be considered.\par LTGA requires one parameter, namely the population size. Finding its appropriate value for a particular test case via tuning may be difficult. Therefore, a population-sizing scheme for LTGA was proposed in~\cite{ltgaPopulationSizing}. LTGA employing this scheme is denoted as LT-GOMEA. LT-GOMEA maintains multiple LTGA instances with different population sizes. The first LTGA instance contains only one individual. During LT-GOMEA execution, new LTGA instances with a doubled population size are added at every $4^{th}$ iteration. Some of the LTGA instances may be found useless and deleted, which limits their number. A single LTGA instance is found useless if all of its individuals are the same or its average population fitness is worse than the average fitness of at least one LTGA with a larger population size. Additionally, all LTGA instances with a smaller population than the LTGA instance found useless are treated as useless as well. All LTGA instances are isolated from each other. Only during the FI phase, the globally best individual (found by any LTGA instance) is used as a donor. Additionally, LT-GOMEA introduces two changes to LTGA. First, LT-GOMEA computes DSM on the base of the whole population, while LTGA uses only a half of the population. Second, during the OM operation, LT-GOMEA considers linkage tree clusters in a random order, while LTGA uses them in the order of their creation. These two changes are supposed to increase the quality of linkage and remove the potential bias that may influence the method for a particular problem, respectively.\par \subsubsection{Parameter-less Population Pyramid} \label{sec:relWork:dsmMethods:p3} Parameter-less Population Pyramid (P3)~\cite{P3Original} uses the same linkage tree construction algorithm and the OM operator as LTGA. However, the population structure is significantly different from any other GA-based method. P3 maintains its population in a pyramid-like structure divided into subpopulations called \textit{levels}. Every individual in the population is unique. The population size is not limited and increases during runtime.\par The general P3 procedure can be described in the following way. At every iteration, a new individual is created randomly and initially optimised by First Improvement Hill Climber (FIHC)~\cite{P3Original}. FIHC is a local search algorithm operating on vector $\overrightarrow{x}$ of $n$ decision variables, $\overrightarrow{x}=[x_1, \ldots , x_n]$. Initially, FIHC randomly chooses a gene order. For each gene $x_i$, all available values are checked until a fitness improvement is found. If so, then the original $x_i$ value is replaced. This procedure is executed until no gene is changed during a FIHC iteration. After the optimisation is done by FIHC, the new individual climbs up the pyramid. With the use of OM, it is mixed with all individuals of a single level. The bottom pyramid levels are considered first. If a fitness of the new individual is improved during this operation, a new individual is added to the pyramid level. If a successful OM involves an individual from the top-level, a new \textit{level} (subpopulation) is added to the pyramid. The overall idea of P3 work is presented in Figure \ref{fig:p3FlowChart}.\par \begin{figure} \centering \includegraphics[width=0.9\linewidth]{p3_flowchart.png} \caption{P3 idea visualization} \label{fig:p3FlowChart} \end{figure} \subsubsection{Dependency Structure Matrix Genetic Algorithm II} \label{sec:relWork:dsmMethods:dsmga2} Dependency Structure Matrix Genetic Algorithm II is another method that employs DSM-based linkage learning \cite{dsmga2}. However, unlike P3 or LTGA, it uses an incremental linkage set (ILS) instead of a linkage tree. ILS is a sequence of gene indexes. The process of ILS building starts from a single gene index and adds a new one with the strongest connection to the previously added gene (in terms of the DSM weights) that has not been included in the sequence yet. Similarly to LTGA, DSMGA-II maintains a single population with a fixed number of individuals. Two operators are used: restricted mixing and back mixing. Restricted mixing is used to process a single individual. First, an incremental linkage set is created, starting from a random gene index. Then, the consecutive genes are flipped according to the incremental linkage set. The operation is maintained until a better fitness is obtained or until the same fitness is obtained, but the modified individual is absent in the population. If all the genes have been flipped but the fitness of the modified individuals is worse than that of the starting individual, the changes done by restricted mixing are rejected. However, if restricted mixing leads to a change (i.e., the new individual has a higher or the same fitness but with a genotype that does not exist in the population), the back mixing operation is triggered. During back mixing, the change introduced by restricted mixing is injected into other individuals. The injection is preserved if it improves fitness and rejected otherwise.\par DSMGA-II has been shown to be effective when solving theoretical \cite{dsmga2} and practical problems \cite{steinerTrees}. Recently, its parameter-less version that employs a population-sizing scheme (denoted as psDSMGA-II) has been proposed in \cite{psDSMGA2}. Although psDSMGA-II improves the effectiveness of the original DSMGA-II, its main disadvantage is the same as for its predecessor: it is less effective in solving the problems with overlapping building blocks in comparison with LT-GOMEA or P3 \cite{afP3,psDSMGA2}. \subsection{Linkage Diversity} \label{sec:relWork:linkageDiversity} P3 is effective for solving hard computational problems \cite{P3Original,fP3,afP3}. Compared to LT-GOMEA, P3 performs significantly better when the problem to be solved has highly overlapping blocks (e.g., NK fitness landscapes) \cite{afP3}. This feature is important in practice because it is typical for real-life problems \cite{watsonHiffPPSNfirst,OverlappingSimon}. To the best of our knowledge, no detailed analysis of P3 superiority over LT-GOMEA and DSMGA-II in solving problems that overlap has been performed and published yet. Below, we propose an explanation of this superiority.\par Let us introduce the deceptive function of unitation~\cite{decFunc}. Formula (\ref{eq:dec3}) defines the deceptive function of order $k$, the solution is binary-coded (i.e., is a string of $0$s and $1$s). \begin{equation} \label{eq:dec3} \mathit{dec(u)}= \begin{cases} k - 1 - u & \text{if } u < k\\ k & \text{if } u = k \end{cases}, \end{equation} where $u$ is a sum of gene values (so called \textit{unitation}) and $k$ is the deceptive function size. The optimal solution of the order-3 deceptive function is $111$, while the suboptimum is $000$. Let us consider the concatenation of three order-3 deceptive functions, where the first three bits refer to the first function (building block), the second three bits refer to the second function and so on. The optimal solution to this problem is $111 111 111$. However, most of the population of typical GA-based methods is deceived to the $000 000 000$ solution. If this problem is sufficiently large, it may become intractable. On the other hand, deceptive functions' concatenations are easy to be solved if the problem nature (the perfect linkage) is known \cite{grayWhitley}. In the given example, the perfect linkage that groups the dependent gene indexes is $(1,2,3)$, $(4,5,6)$ and $(7,8,9)$. Such linkage may be represented by a single linkage tree (Figure \ref{fig:perfectLinkageTree}). \begin{figure} \centering \includegraphics[width=0.5\linewidth]{separable_problem_perfect_link.png} \caption{Linkage tree that represents a perfect linkage for the concatenation of three order-3 deceptive functions} \label{fig:perfectLinkageTree} \end{figure} \begin{figure} \centering \includegraphics[width=0.3\linewidth]{posDependencies.png} \caption{Block positions dependencies for the problem constructed from the concatenation of three order-3 deceptive functions without overlap and with overlap $o=1$} \label{fig:posDependencies} \end{figure} Let us now consider the problem of overlapping deceptive functions that is an example of a problem with overlapping blocks. The size of overlap is defined by $o\in\{0,1,\ldots,k-1\}$, where $k$ is a length of all the considered blocks. The first block is defined on the first $k$ positions of the genotype. All blocks except the first one are defined on the last $o$ positions of the preceding block and the next $k-o$ positions. For instance, the positions referring to the second block start at the $(k-o+1)^{th}$ position and finish at the $(2\cdot k-o)^{th}$ position. The examples of deceptive blocks concatenations with and without overlap are given in Figure \ref{fig:posDependencies}. \begin{figure}[h] \subfloat[Perfect linkage for the first block on positions $\{1,2,3\}$]{% \includegraphics[width=0.3\linewidth]{overlap_problem_perfect_link_1st_block}} \label{fig:linkageForOverlap_a}\hfill \subfloat[Perfect linkage for the last block on positions $\{3,4,5\}$]{% \includegraphics[width=0.3\linewidth]{overlap_problem_perfect_link_2nd_block}} \label{fig:linkageForOverlap_b}\hfill \subfloat[Perfect linkage for the last block on positions $\{5,6,7\}$]{% \includegraphics[width=0.3\linewidth]{overlap_problem_perfect_link_3rd_block}} \label{fig:linkageForOverlap_c}\hfill \caption{Possible linkage trees for three order-3 deceptive functions concatenation with overlap $o=1$} \label{fig:linkageForOverlap} \end{figure} In Figure \ref{fig:linkageForOverlap}, we present possible linkage trees for the concatenation of three order-3 deceptive functions with the $o=1$ overlap. Note that although all the linkage trees are correct, each of them marks only one of the blocks. If the blocks overlap, it is impossible to mark all blocks with a single tree. Therefore, maintaining and using several different linkages at the same time may be beneficial when solving problems with overlaps This observation is confirmed by the results presented in \cite{3lo}. The proposed reasoning is valid only under the assumption that a single linkage tree (even if it is correct) may not be enough to solve the problem with overlaps. To the best of our knowledge, the study that analyses the need for linkage diversity has not been proposed yet, but the results presented in the literature seem to support the above claim \cite{3lo,P3Original,fP3,afP3,psDSMGA2}. The comparison between the original DSMGA-II and DSMGA-II with population-sizing (psDSMGA) show that psDSMGA-II significantly outperforms its predecessor for overlapping problems \cite{dsmga2PopulationSizing}. A similar observation can be made for LTGA and LT-GOMEA comparison \cite{P3Original,afP3}. Population-sizing was proposed to eliminate the necessity of tuning and defining the population size parameter (see Section \ref{sec:relWork:dsmMethods:ltga}). However, as a side effect, population-sizing leads to the maintenance of more than one LTGA/DSMGA-II population. All these populations maintain separate linkages and communicate with each other via the global-best individual. Thus, the globally best individual may be updated by OM in which the donor may be any individual from any LTGA/DSMGA-II population. Depending on the population, a different linkage is used. The above reasoning leads to the conclusion that population-sizing, as a side-effect, introduces a linkage diversity (limited but it is still better than none) and this linkage diversity seems to lead to the results' quality improvement for problems with overlapping building blocks.\par \begin{figure} \centering \includegraphics[width=0.95\linewidth]{p3_example.png} \caption{The example of linkage diversity employment in P3} \label{fig:linkDiversP3Example} \end{figure} \subsection{The significance of Linkage Quality and Diversity} \label{sec:relWork:linkageDiversityExample} As presented in \cite{linkageQuality}, the quality of the linkage may be the key to solve hard computational problems. To show the significance of using a diverse linkage, let us analyze an example shown in Figure \ref{fig:linkDiversP3Example}. We consider a problem, built from three order-3 deceptive functions with overlap $o=1$, presented in the lower part of Figure \ref{fig:posDependencies}. The P3-like population is divided into three levels. The linkage information of the first, second, and third level corresponds to the Linkage Trees presented in Figure \ref{fig:linkageForOverlap} (a), (b), and (c), respectively. We assume that, among all, the pyramid contains the following individuals: \begin{itemize} \item Individual $1110000$ (optimal for the first block), on the first level \item Individual $0011100$ (optimal for the second block), on the second level \item Individual $0000111$ (optimal for the third block), on the third level \end{itemize} In the example pictured in Figure \ref{fig:linkDiversP3Example}, we analyze a single iteration of P3, in which we try to add a new individual to the pyramid with the genotype $0000000$. It is possible that after OM with the individuals on the first level, the new individual will receive the optimal value for the first block (after that, the genotype of the new individual will be $1110000$). If during the OM with the second and third level, the new individual will receive the optimal value for the second and the third block, respectively, then the final genotype of the new individual will be optimal (built only from $1$s). Note that it is possible to obtain an optimal individual because P3 employs many different linkages that mark various parts of the genotype.\par Let us now consider the same population of individuals but grouped in a single population (such population contains individuals $1110000$, $0011100$, and $0000111$). We assume that the linkage corresponds to the Linkage Tree presented in Figure \ref{fig:linkageForOverlap} (b). Note that in such a situation, it is impossible to obtain the optimal individual using OM. It is possible to insert the second block of $1$s from individual $0011100$ to individuals $1110000$, $0000111$, and obtain individuals $1111100$, $0011111$, respectively. However, using the Linkage Tree from Figure \ref{fig:linkageForOverlap} (b), it is impossible to pass the first and the third block of $1$s successfully, without destroying the other blocks. Note that it is impossible to separately insert $1$s for genes 1, 2, 6, and 7 – the fitness value of $1011111$, $0111111$, $1111101$, and $0111110$ is $6$ and is lower than the fitness value of $0011111$ and $1111100$ that is 7. Thus, an operation converting a single $0$ into $1$, for individuals $0011111$ and $1111100$, will be rejected by OM.\par For problems encoded with a large number of genes and with a high amount of overlaps, the dependencies between genes will be significantly more complex. Thus, it is intuitive that, in such cases, it is preferable to use more diverse linkage information. LT-GOMEA uses a population-sizing mechanism. Thus, it also maintains many subpopulations, and therefore, it also maintains many linkages. However, based on the research results presented in \cite{linkageQuality}, the number of levels in the pyramid is usually significantly higher than the number of subpopulations maintained by LT-GOMEA. Thus, when P3 and LT-GOMEA are applied to solve the problem, we may expect that P3 will use a more diverse linkage than LT-GOMEA. Therefore, P3 is more suitable to solve overlapping problems.\par In this paper, as a competing method, we also consider NSGA-II that employs a standard crossover operator and no linkage learning mechanisms. Let us consider the probability to successfully insert the first block of three $1$s from individual $1110000$ to individuals $0011100$ and $0011111$. We consider the uniform crossover that is independent of the gene order. The assumption that genetic operators should be independent of gene order seems intuitive and is typical for modern evolutionary algorithms \cite{3lo}. The probability of successful insertion of the first block of $1$s to individual $0011100$ is $2^{-4}$ (we need to exchange genes 1 and 2, and we shall not exchange genes 4 and 5). However, if we wish to insert the same block of $1$s to individual $0011111$, the probability will be $2^{-6}$. Moreover, the probability to successfully exchange a particular building block without destroying the other blocks will decrease quickly with the increase of the problem size. Therefore, the typical crossover operators that do not use linkage learning will not be effective when strong inter-gene dependencies exist. As shown above, the diverse linkage maintained by P3 may be highly useful when overlapping problems are being solved. However, the pyramid-like form of the P3 population has some drawbacks. For instance, when the number of levels is large (eg., over 30), it may be hard to exchange some building blocks, even if appropriate linkage and appropriate blocks exist in the population. This issue has been detected for non-overlapping problems, and the modifications of P3 to address this issue were proposed in \cite{fP3,afP3}. \subsection{Pareto Front Clusterisation} \label{sec:relWork:clusterisation} The goal of multi-objective optimisation is to obtain a Pareto front that covers or is relatively close to the optimal Pareto front. Thus, to measure the quality of a Pareto front, its proximity and diversity are often compared with the optimal Pareto front \cite{frontQualityMeasurement}. To obtain a diverse and high-quality Pareto front, evolutionary methods tend to preserve the overall population diversity, often emphasising the diversity in the objective space. This may be achieved by employing the crowding distance like in NSGA-II \cite{nsga2} or a density measure like in SPEA2 \cite{spea2}. Nevertheless, such operators may not be sufficient to obtain good quality results for hard optimisation problems. Therefore, linkage learning techniques may be useful to recognise the problem's nature and exchange appropriate solution parts during the optimisation process \cite{MoGomeaGecco,MoGomeaSwarm}. However, for different Pareto front parts, the problem's features may be significantly different. For instance, for the practical problem considered in this paper, the solution minimising the production makespan may be significantly different from the solution minimising production surpluses. Similar observations can be made for other practical problems \cite{MoGomeaSwarm}. Therefore, some of the evolutionary methods that are employed for the multi-objective optimisation split the population into clusters, usually based on the objective space \cite{mohBOA,clusterizationBosman}. \subsection{Multi-objective Gene-pool Optimal Mixing Evolutionary Algorithm} \label{sec:relWork:moGomea} MO-GOMEA is a multi-objective version of LTGA (see Section \ref{sec:relWork:dsmMethods:ltga}). Except for the concept of LTGA, it employs other ideas, like Pareto front clusterisation and elitist archive. MO-GOMEA is a parameter-less method, which is an important feature for practical purposes.\par MO-GOMEA uses a so-called \textit{elitist archive}. The elitist archive is a separate population where non-dominated solutions are stored. Maintaining such a buffer is beneficial for multi-objective evolutionary algorithms because, during the search, some non-dominated solutions may be discarded due to the stochastic nature of the search \cite{MoGomeaSwarm}. In some optimisation problems, the Pareto front may contain an infinite (or too large to store) number of solutions \cite{ElitistArchive2}. Thus, if a new non-dominated solution is found, it shall be added to the elitist archive if it dominates at least one solution from the elitist archive or if it increases the diversity of the archive in the solution space \cite{ElitistArchive2}.\par At each method iteration, MO-GOMEA clusters its population with the use of \textit{k}-leader-means clustering \cite{clusterizationBosman}. The population is divided into \textit{k} clusters containing \textit{c} solutions. In MO-GOMEA $c = \frac{2}{k}\cdot|\mathcal{P}_F|$; such a size of \textit{c} causes the clusters to overlap and avoid the situation in which some individuals do not belong to any cluster. Each cluster is a subpopulation that is later processed by LTGA. The only difference is that since the problem is multi-objective, the source solution is found improved if, after the optimal mixing, the altered source solution dominates its previous version or it can be added to the elitist archive. MO-GOMEA requires specifying two parameters: the population size and the number of clusters. To overcome this issue, it employs the so-called interleaved multi-start scheme (IMS) \cite{MoGomeaSwarm} that is equivalent to the population-sizing scheme described in Section \ref{sec:relWork:dsmMethods:ltga}.\par \subsection{Multi-Objective Evolutionary Algorithm based on Decomposition} \label{sec:relWork:moead} Multiobjective Evolutionary Algorithm based on Decomposition (MOEA/D) is a multi-objective optimisation algorithm whose main principle is to decompose an $m$-objective problem into $N$ single-objective subproblems \cite{moead}. The three decomposition techniques in MOEA/D are: the weighted sum approach, the Tchebycheff approach, and the penalty-based boundary intersection approach. For example, employing the Tchebycheff approach, maximisation of an $m$-objective optimisation problem $F(x) = (f_1(x), \ldots, f_m(x))^T$ can be decomposed to the optimisation of the $N$ subproblems and the objective function of the $j$-th subproblem, $j=1,\ldots,N$, is: \begin{equation} \label{tchebycheff} g^{te} \left(x \vert \lambda^j, z^*\right) = \max_{1 \leq i \leq m} \left\{ \lambda_i^j | f_i(x) - z^*_i | \right\}, \end{equation} where $x$ indicates a given solution in the decision space, $\lambda^j=(\lambda_1^j,\ldots,\lambda_m^j)$ is a weight vector, $z^*$ indicates a set of reference points $z_i^* = min \{f_i(x) | x \in \mathrm{\Omega} \}$ and $|\cdot|$ denotes the Euclidean distance. Several different methods for selecting weight vectors $\lambda^j$ have been proposed, including classic simplex-centroid and simplex-lattice, as well as more recent transformation methods and uniform decomposition measurement \cite{Ma2014c}. Single-objective subproblems (\ref{tchebycheff}) are solved simultaneously, employing evolutionary algorithms. Each solution to such single-objective subproblems forms a Pareto-optimal front of the original multi-objective problem $F(x)$. One of the main assumptions of MOEA/D is that the optimal solutions to neighbouring subproblems (in terms of the Euclidean distance between the corresponding weight vectors) are likely to be similar. Hence, a chromosome describing a solution to a certain single-objective subproblem can be crossed-over only with the chromosomes of the neighbouring subproblems, where the neighbourhood size is a parameter. Each population comprises the best solutions found so far to all $N$ subproblems. In MOEA/D, the one-point crossover operator and the standard mutation operator are applied. Thanks to defining the weight vector set a priori, the diversity in the population is maintained without the need for computing crowding distances, which is one of the major costs in other multiobjective optimisation evolutionary algorithms, such as NSGA-II \cite{nsga2}. MOEA/D has attracted much attention in the field of evolutionary multiobjective optimisation, and several modifications have been proposed, as surveyed in \cite{Zhou2011}. Some of the suggested improvements, for example, integration with the opposition-based learning \cite{Ma2014b}, Baldwinian learning \cite{Ma2014}, or end-user preference incorporation \cite{Ma2016} can be applied to the method proposed in this paper. The addition of these features is considered as future work. \subsection{Multi-objective GAs for manufacturing scheduling} \label{sec:relWork:IPP} One of the pioneering research related to industrial production planning using a multi-objective GA was described in \cite{Ishibuchi1998}. In that paper, a set of nondominated solutions was determined for a classic flowshop scheduling problem with three objectives, namely, the minimal makespan, the maximum tardiness and the total flowtime. A weighted sum of these three criteria was treated as a fitness value of each individual, but the weight values were randomly specified whenever a pair of the parent solutions was selected. Consequently, each point of the solution space was generated using a different weight vector. A local search was then applied for further improvement of those solutions. However, the considered problem was rather abstract and the considered plant and taskset sizes were limited \cite{Ishibuchi1998}. Various real-world industrial scheduling problems were attempted to be solved with customised multi-objective GAs as well. In \cite{Li2009}, for example, a real-world manufacturing problem of a steel tube production was described as an extension of a classic Job-Shop Scheduling Problem with compatible resources (aka Flexible Job-Shop Scheduling Problem). A multi-objective GA was applied with two objectives: minimisation of the resources' idleness and waiting time of orders. In that paper, it stated explicitly that the prior research related to Job-Shop Scheduling Problems was impractical as being based on oversimplified models and assumptions. Nevertheless, that model is still inappropriate for the batch production problem considered in this paper. In particular, it is unable to select recipes or minimise the commodity surplus. Another interesting real-world manufacturing problem of textile batch dyeing scheduling was presented in \cite{Huynh2018}. In that problem, a batch is comprised of clothes of the same colour whose total weight does not exceed the capacity of the manufacturing resource. Again, that problem is different of the one analysed in this paper, as in the considered case the resources can produce only an exact weight of a given commodity. The total amount of manufactured commodities depends only on the recipes multisubset (i.e., a combination with repetitions) selected for manufacturing. Hence, a batching heuristics, as proposed in \cite{Huynh2018}, is not applicable, but a technique for optimisation of recipe multisubset selection is needed. GA was applied to such a problem in \cite{paintsOrig}, yet the optimisation was performed with typical multi-objective GAs (NSGA-II and MOEA/D). In particular, no linkage learning was performed in that approach. Note that in the research presented in this paper, we compare to both methods considered in \cite{paintsOrig} and both of these methods are outperformed by linkage learning GAs (namely MO-GOMEA and MO-P3) for the considered practical problem and for a wide set of benchmark problems. More examples of applying multi-objective GAs to solve manufacture scheduling problems were surveyed in \cite{Gen2014}, including Job-Shop Scheduling Problems, Flexible Job-Shop Scheduling Problems, dispatching in flexible manufacturing systems and integrated process planning and scheduling. However, none of the papers reviewed there dealt with recipe multisubsets nor minimising the surplus of the manufactured commodities. Similarly, none of the reviewed papers used linkage learning to improve the performance of the applied GAs, as it is proposed in this paper. \section{Real-World Multi-Objective Bulk Commodity Production Problem Formulation} \label{sec:problemDef} In this section, the considered practical problem is firstly described and then formalised as a typical covering problem (CP) instance and its extension to multi-objectiveness. \subsection{Real-World Scenario Description} The considered scenario is based on a process of manufacturing, in which a certain amount of commodities is produced by combining supplies, ingredients or raw substances following a stored recipe. The main optimisation objective of this case study is to decrease the makespan of batch production. Depending on the selected multisubset (i.e., a combination with repetitions) of recipes, the time to produce a commodity may vary significantly, which influences the percentage of manufacturing time that is truly productive, known as Overall Equipment Effectiveness (OEE). In the considered multi-objective bulk commodity production problem (MOB\\CPP), the recipes for each batch produce a certain amount of commodity. Consequently, to satisfy an order for a certain commodity, one or more recipes for producing such commodity have to be selected and allocated to resources. However, the sum of the commodity amount produced by any selection of recipes may be different from the order amount for that commodity. If a certain commodity cannot be produced in the required amount, some commodity surplus is expected. As the surplus storage can be expensive and larger surplus usually implies a higher cost of raw substances used in the production, additional optimisation objectives can be defined: not only the makespan but also the surpluses of each produced commodities have to be minimised. This observation leads to the conclusion that multi-objective optimisation techniques, as described earlier in this paper, can be applied. In particular, this problem can be viewed as a variant of the classic covering problem, as shown in the following subsection. \subsection{Problem Formulation} The considered factory manufactures bulk commodities $c_j$, $j = 1, \ldots, m$. These commodities can be produced by executing $x_i$, $i=1,\ldots,n$, times some pre-defined manufacturing recipes $\gamma_i$ on the only resource $\pi$. The objective is to minimise the makespan \begin{equation} \sum_{i=1}^{n}t_ix_i, \end{equation} where $t_i$ denotes the pre-defined execution time of recipe $\gamma_i$ subject to \begin{equation}\label{eq:constraints} \sum_{i=1}^{n}\delta_{i,j}x_i \geq o_j, \end{equation} where $o_j$ denotes the ordered amount of commodity $c_j$, $\delta_{i,j}$ is the amount of commodity $c_j$ produced by recipe $\delta_i$. The problem defined in this way is a typical example of CP and, as such, is an instance of ILP and belongs to the NP-hard class \cite{Garey1990}. The first extension of the above problem is the possibility of multiple resources $\pi_i$ in the factory, each being capable of executing recipe $\gamma_i$. Hence the makespan minimisation objective can be rewritten as minimising \begin{equation} \max_{\forall i \in \{1,\ldots,n\}} (t_ix_i) \end{equation} subject to the same constraints as provided in (\ref{eq:constraints}). The next modification is caused by the surplus storage cost in the factory and the cost of raw substances needed to produce the commodities, which force the factory to minimise not only the makespan, but also the surpluses of each commodity, i.e. to produce as little commodities as possible to satisfy the ordered amounts. Hence, the following $m$ objectives need to be added to the optimisation problem: $\forall j \in \{1,\ldots,m\}$ minimise \begin{equation} \sum_{i=1}^{n}\delta_{i,j}x_i, \end{equation} subject to the same constraints (\ref{eq:constraints}) as above. The number of instances of each recipe $\gamma_i$ can be viewed as being bounded by the ordered amount of commodities produced by this recipe, computed with equation \begin{equation}\label{eq:ceil} \mu_i=\max_{\forall j \in \{1,\ldots,m\}} \left\lceil \frac{o_j}{\delta_{i,j}}\right\rceil. \end{equation} This upper-bound facilitates the binary encoding of the solutions for GA as described in the next section. The considered problem is a discrete combinatorial problem. As pointed in \cite{moSurvey}, if such problems are solved by conventional methods, the time required to solve them may increase exponentially. Therefore, the use of Multi-Objective Evolutionary Algorithms is justified. \section{Multi-Objective Parameter-less Population Pyramid for Solving MOBCPP} \label{sec:mop3} In this section, we describe the details, motivations and intuitions of the proposed Multi-Objective Parameter-less Population Pyramid (MOP3). In the first subsection, we discuss the solution encoding, while in the second one, we describe the proposed method. \subsection{Solution Encoding} \label{sec:mop3:encoding} As presented in the previous section, in the MOBCPP problem, the size of ordered amounts is known. However, the number of production tasks (\textit{jobs}) is not specified because each recipe may produce a different amount of paint. \begin{comment} In MOBCPP, the goal is to satisfy orders in the shortest possible time with the overproduction as low as possible. The commodities are produced by executing recipes; each recipe execution is termed as a \textit{job}. The produced amount of a commodity may differ for each recipe and one recipe may produce more than one commodity during its execution. We can compute how many jobs are necessary to satisfy the ordered amount of a commodity when a particular recipe is selected. \end{comment} Let us consider an example with a single commodity. The ordered amount is $o_1 = 10$ units. There are two available recipes, $\gamma_1$ and $\gamma_2$, that produce $\delta_{1,1}=3$ and $\delta_{2,1}=5$ units of commodity $c_1$, respectively. Thus, based on equation (\ref{eq:ceil}), to satisfy order $o_1$, it is sufficient to execute $\mu_1=4$ jobs using $\gamma_1$ recipe or $\mu_2=2$ jobs that use recipe $\gamma_2$. Note that the solution to the problem instance considered in this example may be encoded as a 6-bit long binary string, where the first four bits refer to jobs executing recipe $\gamma_1$ and the last two bits refer to jobs that execute recipe $\gamma_2$.\par Based on the above example, we may state that a solution to MOBCPP can be encoded as a binary string where a particular bit refers to a single job executing a particular recipe. In this paper, we order the bits in the following manner. First, we consider all bits that refer to the jobs producing the first commodity, then the bits that refer to the jobs producing the second commodity and so on. The jobs producing more than one commodity are located at the position suitable for the produced commodity with the lowest index. Among the bits that consider the production of a particular commodity, we first encode the bits referring to the minimum number of jobs using a recipe with the lowest index in the recipe list, then we encode the bits referring to the jobs using the recipe with the second-lowest index in the list and so on. The minimum number of jobs to satisfy the ordered amount of $o_i$, using recipe $\gamma_i$ that produces $\delta_{i,j}$ resource units is computed with equation (\ref{eq:ceil}). \begin{figure}[ht!] \centering% \includegraphics[width=0.9\textwidth]{encodingExample} \caption{Solution encoding example} \label{fig:encoding:ex} \end{figure} Let us consider the following example. Two commodities with orders $o_1 = 10$ and $o_2 = 8$ units are considered. The first commodity may be produced with the use of $\gamma_1$ and $\gamma_2$ recipes that produce $\delta_{1,1}=3$ and $\delta_{2,1}=5$ of commodity units, respectively. The second commodity may be produced with the use of three recipes ($\gamma_3$, $\gamma_4$ and $\gamma_5$) that produce $\delta_{3,2}=5$, $\delta_{4,2}=2$ and $\delta_{5,2}=3$ units of this commodity. The encoding and the solution to this problem instance are presented in Fig. \ref{fig:encoding:ex}. First, the jobs that consider the order for the first commodity are considered. Among them, the first four bits refer to jobs using recipe $\gamma_1$, the next two refer to jobs using recipe $\gamma_2$. Respectively, for the order referring to the second commodity, the first two bits refer to recipe $\gamma_3$, the next four to recipe $\gamma_4$ and the last three to recipe $\gamma_5$.\par Note that Fig. \ref{fig:encoding:ex} presents a feasible solution, i.e., the one that produces enough commodities. However, the solution encoded in the manner proposed above may be infeasible. Moreover, it may exceed the order size. Therefore, to fix the above issues, we propose a genotype repair algorithm presented in Pseudocode \ref{alg:imAndSdsnc}. Any genotype that has been updated by the proposed algorithm is feasible and it does not use more jobs for a particular recipe than necessary (i.e., all jobs that may be abandoned without violating the order constraint will be removed). The proposed solution encoding is not unique as two or more different genotypes can encode the same solution. The genotype repair algorithm works as follows. For each gene (that corresponds to a particular recipe), the list of orders produced by the corresponding recipe is gathered. If, for at least one order, we need to increase the production amount, then we set the gene value on $1$. If, for all orders, we can resign from using the recipe without violating the order size, then we set the gene value on $0$. Otherwise, the gene value remains unmodified. \begin{algorithm} \caption{Genotype repair algorithm} \begin{algorithmic}[1] \Procedure{Repair}{Genotype} \State ResGenotype = Genotype \For{$Gene \gets 1$ \textbf{to} length($ResGenotype$)} \State $OrdersIndexes \gets$ GetOrdersForGene($ResGenotype, Gene$) \State $decision = -1$ \For{$i \gets 1$ \textbf{to} length($OrdersIndexes$)} \State $Order \gets OrdersIndexes[i]$ \State $OrderToDo \gets $ GetOrderSize($Order$) \State $OrderPlanProd \gets $ GetPlanProd($Order,ResGenotype$) \State $RecipeAmount \gets$ GetRecipeAmountForGene($Order,Gene$) \If {$OrderToDo > OrderPlanProd$} \State $decision = 1$ \EndIf \If {$OrderToDo > OrderPlanProd - RecipeAmount$ \textbf{and} $decision = -1$} \State $decision = 0$ \EndIf \EndFor \If {$decision = 1$} \State $ResGenotype[Gene] = 1$ \EndIf \If {$decision = -1$} \State $ResGenotype[Gene] = 0$ \EndIf \EndFor \State \Return{ResGenotype} \EndProcedure \end{algorithmic} \label{alg:imAndSdsnc} \end{algorithm} \subsection{Multi-Objective Parameter-less Population Pyramid} \label{sec:mop3:mmethod} In this section, we present the motivations behind the proposed Multi-Objective Parameter-less Population Pyramid (MO-P3) and its description. The main reason for using P3 as a research starting point for proposing a method dedicated to solving a practical multi-objective problem considered in this paper are enumerated below.\par \textbf{Motivation 1}. P3 is effective in solving problems with overlapping building blocks (see Section \ref{sec:relWork:linkageDiversity}). The relations between building blocks (overlapping) are typical for real-life problems \cite{watsonHiffPPSNfirst,OverlappingSimon}. P3 has also been found more effective than LTGA and DSMGA-II when applied to a single-objective practical problem \cite{steinerTrees} (to the best of our knowledge, the results presented in \cite{steinerTrees} are the only comparison between P3, LTGA and DSMGA-II based on practical problem instances). Thus, it is reasonable to assume that a P3-based method dedicated to solving a practical multi-objective problem may be found more effective than MO-GOMEA (that is LTGA-based).\par \textbf{Motivation 2}. As explained in Section \ref{sec:relWork:moGomea}, MO-GOMEA clusters its population concerning the objective space. MO-GOMEA maintains separate linkages for each Pareto front cluster. This kind of multi-objective problem decomposition is the key feature of MO-GOMEA and one of the reasons for its high effectiveness. MO-GOMEA is based on the idea of LTGA, which maintains a single linkage at a time. On the other hand, P3 maintains many linkages (one per pyramid level). As explained in Section \ref{sec:relWork:dsmMethods:p3}, this linkage diversity is likely to be the reason for the high effectiveness of P3 in solving the heavily overlapping problems. Maintaining many different linkages facilitates identifying different blocks (groups of gene indexes). The same feature is required when solving multi-objective problems. Thus, a P3-based method may be highly effective in solving multi-objective problems even without problem decomposition performed by MO-GOMEA.\par Considering the above motivations, we propose a Multi-Objective Parameter-less Population Pyramid (MO-P3) that includes the following mechanisms. MO-P3 uses the elitist archive in the same way as MO-GOMEA (see Section \ref{sec:relWork:moGomea}). In the original P3, each individual that climbs up the pyramid optimises a single-objective problem. Therefore, to adjust MO-P3 to multi-objective optimisation, when a new iteration of MO-P3 starts, a normalised weight vector is chosen to transform a multi-objective problem into a single-objective one. Thus, during its climbing, each individual optimises a single-objective problem. However, due to different weights, it shall climb to reach a different part of the Pareto front.\par \begin{algorithm} \caption{The general MO-P3 overview} \begin{algorithmic}[1] \Procedure{MO-P3}{} \State $levels \gets $ \{ CreateNewEmptyPop()\} \Comment{initialization} \While{$\neg stopCondition$} \State $weightVec \gets $ GetWeightVector(); \State $newInd \gets $ GetRandomIndividual(); \State $newInd \gets $ FIHC($newInd, weightVec$); \If {$newInd$ $\neg$ exist in $levels$} \State InsertIndividualOnLevel($levels[0]$,$newInd$); \EndIf \For {\textbf{each }$level \in levels$} \State $IndImpr \gets $ ImproveIndWithLevel($level$, $newInd$, $weightVec$); \If {$IndImpr \neq newInd$ } \State $newInd \gets IndImpr$ \If {$newInd$ $\neg$ exist in $levels$} \State $nextLevel \gets$ GetNextLevel($level$); \If {$nextLevel = empty$ } \State $nextLevel \gets $ \{ CreateNewEmptyPop()\} \State AddNewTopLevel($levels, nextLevel$); \EndIf \State InsertIndividualOnLevel($nextLevel$,$newInd$); \EndIf \EndIf \EndFor \EndWhile \EndProcedure \end{algorithmic} \label{alg:mop3Overview} \end{algorithm} The general overview of MO-P3 work is presented in Pseudocode \ref{alg:mop3Overview}. For each new individual, the weight vector is chosen to direct the search in one of the parts of the Pareto front (lines 4 and 5). The new individual is improved by FIHC and added to the pyramid (lines 6-9). Then, the new individual climbs up the pyramid. Note that the chosen weight vector is used during the whole iteration. The new individual may cross with any other individual that was added to the pyramid. However, any time the new individual is mixed with individuals on the given pyramid level (line 11), the linkage gathered for this level is employed, and the search is directed by the weight vector selected at the beginning of the iteration (line 4).\par The way of choosing the weight vector at the beginning of each MO-P3 iteration is crucial. It shall push the search to focus on different parts of the Pareto front. However, if the search is too heavily biased towards some parts of the Pareto front, the linkage diversity offered by the pyramid-like population structure may not be sufficient. In consequence, the linkage gathered by MO-P3 may become useful to optimise only some parts of the Pareto front. If so, the quality of solutions referring to other Pareto front parts (those for which the linkage stored by MO-P3 is not useful) may be low. In this paper, we consider two different strategies of choosing the weight vector. In the first one, the weight vector is chosen randomly. MO-P3 using this technique will be denoted as MO-P3-Random. The second strategy of choosing the weight vector is presented in Pseudocode \ref{alg:smartWeightVector} and denoted as MO-P3-Smart. \begin{algorithm} \caption{Smart strategy of choosing the two-dimensional weight vector} \begin{algorithmic}[1] \Procedure{GetWeightVector}{ElitistArchive} \State $EApoints \gets empty$ \For {\textbf{each} \textit{sol} in \textit{ElitistArchive}} \State $sum = sol.FirstObjNormalised + sol.SecondObjNormalised$ \State $newPoint.FirstWeight = sol.FirstObjNormalised / sum$ \State $newPoint.SecondWeight = sol.SecondObjNormalised / sum$ \State $EApoints \gets newPoint$ \EndFor \text{\textbf{ each}} \State $EApoints \gets$ Sort($EApoints$) \State $interv_1 \gets$ GetRandomInt($1, $ SizeOf($EApoints$)$-1$) \State $interv_2 \gets$ GetRandomInt($1, $ SizeOf($EApoints$)$-1$) \State $length_1 \gets $ GetEuclDist($EApoints.At(inter_1), EApoints.At(inter_1 + 1)$) \State $length_2 \gets $ GetEuclDist($EApoints.At(inter_2), EApoints.At(inter_2 + 1)$) \If {$length_1 > length_1$} \State $intervChosen \gets interv_1$ \Else \State $intervChosen \gets interv_2$ \EndIf \State $IntervalStart = EApoints.At(intervChosen).FirstObj$ \State $IntervalEnd = EApoints.At(intervChosen).SecondObj$ \State $weightVec.First = $ GetRandomReal($IntervalStart, IntervalEnd$) \State $weightVec.Second = 1 - weightVec.First$ \State \Return{weightVec} \EndProcedure \end{algorithmic} \label{alg:smartWeightVector} \end{algorithm} In the \textit{smart} strategy of choosing the weight vector, each solution in the elitist archive is transformed into a weight vector. Such an array of weight vectors is then sorted concerning the weight corresponding to the first objective. After sorting an array of weights, the vectors may be interpreted as an array of the crowding distances \cite{nsga2}. Then, the tournament of size two is used to choose the interval that refers to the higher value of the crowding distance. The weight vector is randomly chosen from the interval returned by the tournament.\par The motivation behind the \textit{smart} strategy of choosing the weight vector is as follows. MO-P3-Smart is expected to push the search towards these regions of the Pareto front that are poorly represented. On the other hand, such a bias may cause the linkage to be useful to optimise only some parts of the Pareto front. In this case, the overall Pareto front quality may decrease significantly.\par In this section, we have proposed a multi-objective method dedicated to solving the MOBCPP problem. We propose both: the problem-dedicated solution encoding and the new method. MO-P3 is based on the P3 method. The key modification is the choice of weight vector for further optimisation of a new individual during the climb. We propose two strategies for choosing the weight vector: Random and Smart. In the subsequent sections, we show that our proposition is more effective than the competing methods in solving both: the MOBCPP problem and the typical benchmarks employed in multi-objective discrete optimisation. \section{Experiments on MOBCPP} \label{sec:exp:paints} In this section, we present the results obtained for the MOBCPP problem. The objective of the experiments was to compare the effectiveness of the proposed MO-P3 with other methods dedicated to multi-objective optimisation on the base of the MOBCPP problem. The rest of this section is organised as follows. In the first subsection, we present the experiment setup. In Section \ref{sec:exp:paints:strategiesComparison}, the two considered MO-P3 versions are compared. In the third subsection, we analyse the fitness evaluation number (FFE) and computation time ratio. Finally, in the last subsection, we compare MO-P3 with MO-GOMEA, MOEA/D and NSGA-II. \subsection{Experiments Setup} \label{sec:exp:paints:setup} In this paper, we consider $27$ different MOBCPP problem instances. Each instance is related to a real-life configuration that takes place or may take place in practice. We consider two groups of test cases. In the first group (16 test cases), we consider one production hall, with multiple machines. In these scenarios, each job can be executed on any machine (more information about these scenarios is given in Table \ref{tab:testCases}). In the second group of test cases (11 test cases), we consider scenarios with multiple production halls. In each hall, we can produce only a subgroup of paints (more information is given in Table \ref{tab:testCasesMulti}). Note that even for a relatively low number of resources, the number of available encodings is large. Since MOBCPP is NP-hard (see Section \ref{sec:problemDef}), the considered test cases may be found difficult to solve. Each experiment has been repeated 50 times.\par \begin{table} \caption{The parameters of the single-hall test cases} \centering% \label{tab:testCases} \begin{tabular}{ccc} \hline \textbf{Parameter} & \textbf{Min} & \textbf{Max} \\ \hline \textbf{Production halls} & \multicolumn{2}{c}{1} \\ \textbf{Resources} & 2 & 3 \\ \textbf{Commodities} & 6 & 20 \\ \textbf{Recipes} & 12 & 60 \\ \textbf{Genotype length} & 46 & 746 \\ \textbf{Encodable solutions} & $7.03 \cdot 10^{13}$ & $3.70 \cdot 10^{224}$\\ \hline \end{tabular} \end{table} \begin{table} \caption{The parameters of the multi-hall test cases} \centering% \label{tab:testCasesMulti} \begin{tabular}{ccc} \hline \textbf{Parameter} & \textbf{Min} & \textbf{Max} \\ \hline \textbf{Production halls} & 2 & 12 \\ \textbf{Resources} & 2 & 24 \\ \textbf{Commodities} & 6 & 72 \\ \textbf{Recipes} & 12 & 144 \\ \textbf{Genotype length} & 92 & 552 \\ \textbf{Encodable solutions} & $10^{27}$ & $10^{162}$\\ \hline \end{tabular} \end{table} We consider two MO-P3 versions that employ two different strategies for weight vector initialisation (see Section \ref{sec:mop3:mmethod}). Depending on the employed strategy, they will be denoted as MO-P3-Random and MO-P3-Smart, respectively. We use three competing methods: Non-dominated Sorting Genetic Algorithm II (NSGA-II) \cite{nsga2}, Multi-Objective Evolutionary Algorithm based on Decomposition (MOEA/D) \cite{moead} and Multi-objective Gene-pool Optimal Mixing Evolutionary Algorithm (MO-GOMEA) \cite{MoGomeaSwarm}. NSGA-II has been selected as it is commonly employed as a baseline in the multi-objective optimisation domain. Similarly to \cite{MoGomeaGecco}, we use bit-flipping mutation with probability $1/l$, where $l$ is the genotype length, the probability of crossover is 0.9. To make NSGA-II independent of the gene order, we use the uniform crossover. Finally, we consider the population sizes of 25, 50, 100, 200, 400 individuals, the same as in \cite{MoGomeaGecco,MoGomeaSwarm}. MOEA/D is frequently used as a research starting point and as a baseline \cite{MoGomeaSwarm,Zhou2011}. Similarly to NSGA-II, MOEA/D requires specification of the population size. We consider the same population sizes as in the NSGA-II case. MO-GOMEA is a state-of-the-art method in the multi-objective optimisation domain that has been reported to significantly outperform NSGA-II \cite{MoGomeaGecco,MoGomeaSwarm} and MOEA/D \cite{MoGomeaSwarm}. Note that MO-GOMEA and the proposed MO-P3 are parameter-less methods. Thus, no tuning is necessary. This feature makes these methods particularly useful for practical implementations. We have abandoned the comparison with the Multi-objective Hierarchical Bayesian Optimization Algorithm \cite{mohBOA} because it was significantly outperformed by MO-GOMEA \cite{MoGomeaGecco,MoGomeaSwarm}.\par For the considered methods, we use the source codes published by their authors\footnote{\url{http://www.iitk.ac.in/kangal/codes.shtml} for NSGA-II, the source code used in \cite{MoGomeaSwarm} for MO-GOMEA, the source code given in \cite{P3Original} for P3 and \url{https://github.com/ZhenkunWang} for MOEA/D}. All sources have been merged on the problem definition level in one project that is available at \url{https://github.com/przewooz/moP3}. Additionally, with the source code, all settings files and the detailed results of all experiments are provided.\par As the stop condition, we use the fitness function evaluation number (FFE). This choice is motivated by the significant amount of computation time consumed by the fitness value computation. The computation budget has been set to 25 million fitness evaluations.\par As a quality measure, we use the Inverted Generational Distance (IGD). IGD is defined as \begin{equation} \label{eq:igd} D_{\mathcal{P}_F\to \mathcal{S}}(\mathcal{S}) = \frac{1}{|\mathcal{P}_F|} \sum_{\substack{f^0 \in \mathcal{P}_F}} \min_{x \in \mathcal{S}}{\{d(f(x), f^0) \}}, \end{equation} where $\mathcal{P}_F$ is the Pareto-optimal front, $\mathcal{S}$ is the final front proposed by the optimiser and $d(\cdot,\cdot)$ is the Euclidean distance. IGD is an average distance from each point in $\mathcal{P}_F$ to the nearest point in $\mathcal{S}$. The quality of the proposed front $\mathcal{S}$ is inversely proportional to the IGD value. The optimal IGD value is $0$, which means that $\mathcal{S}$ covers $\mathcal{P}_F$. We can also compute the average distance from each point in $\mathcal{S}$ to the nearest point in $\mathcal{P}_F$. Such a measure is called the Generational Distance (GD) \cite{MoGomeaSwarm}. The advantage of IGD over GD is that IGD value is optimal if and only if $\mathcal{S}$ covers the whole $\mathcal{P}_F$. Oppositely, GD value is optimal if $\mathcal{S}$ is a subset of $\mathcal{P}_F$ \cite{MoGomeaGecco}. Therefore, we favour IGD over GD.\par The optimal Pareto front must be known to compute IGD. Unfortunately, the considered test cases are based on practice and the optimal Pareto front is not known. To overcome this issue, we construct a pseudo-optimal Pareto front in the following way. For each test case, we consider all $\mathcal{S}$ fronts proposed by every method in every run. From this set of points, we choose only non-dominated ones. The pseudo-optimal Pareto front obtained this way may not be optimal. Nevertheless, all considered $\mathcal{S}$ fronts only contain points that are the part of pseudo-optimal Pareto front or that are dominated by points from pseudo-optimal Pareto front. The same procedure of pseudo-optimal Pareto front creation has been applied in \cite{MoGomeaGecco}. \subsection{The Comparison between MO-P3 with Random and Smart Strategies} \label{sec:exp:paints:strategiesComparison} To compare the performance of MO-P3-Random and MO-P3-Smart, we consider the median IGD value that describes the quality of the proposed Pareto front and the median FFE number necessary to obtain the final solution. To check the statistical significance of the differences, we use the Wilcoxon signed-rank test with a typical 5\% significance level. The summarised results are presented in Table \ref{tab:radnomVsSmart}.\par \begin{table} \caption{The effectiveness comparison between MO-P3 employing Random and Smart strategies} \centering% \label{tab:radnomVsSmart} \begin{tabular}{ccccc} \hline \textbf{Test-case type} & & \textbf{Random} & \textbf{equal} & \textbf{Smart} \\ \hline \multirow{2}{*}{\textbf{Single-hall}} & \textbf{IGD} & 7 & 9 & 0 \\ & \textbf{Median FFE until final solution} & 8 & 7 & 1 \\ \multirow{2}{*}{\textbf{Multi-hall}} & \textbf{IGD} & 0 & 11 & 0 \\ & \textbf{Median FFE until final solution} & 0 & 11 & 0 \\ \hline \end{tabular} \end{table} For test cases with a single production hall, MO-P3 with the \textit{random} strategy has outperformed MO-P3-Smart for 7 test cases (out of 16) and has never been found inferior. Moreover, MO-P3-Random has also been faster to find the solution in 50\% of the cases and found slower for only one test case.\par The \textit{smart} strategy chooses the weight vector at each MO-P3 iteration in a way that shall force the method to obtain a more diverse Pareto front. Thus, it may be found surprising that MO-P3-Smart has been outperformed by MO-P3-Random. However, as stressed in Section \ref{sec:mop3:mmethod}, the \textit{smart} strategy may bias the method towards some solution space regions. If this happens, the linkage gathered and utilised by MO-P3 may become useful only for improving some parts of the Pareto front. As a consequence, the overall Pareto front quality will drop. Note that the drop or lack of linkage diversity may cause a method to become ineffective \cite{3lo}.\par For the test cases considering many production halls, both strategies report results of equal quality. The differences in median FFE necessary for reaching the best result are not statistically significant. Such results may be found surprising when compared to those obtained for a single production hall. The reasonable explanation of this fact is as follows. When we consider multiple halls and each hall produces only a subgroup of paints, then the key issue is to successfully find the appropriate linkage that divides a genotype into subparts responsible for production on each of the halls. For DSM-using methods (like P3, or MO-GOMEA), such a task may be easy for some problem types \cite{linkageQuality}, and hard for the other. If for these test cases, the key to finding a high-quality Pareto front is to find a high-quality linkage that divides a genotype into the appropriate parts, then the multi-level population structure of MO-P3 is the key to solve these problem instances. The other MO-P3 features that cause the domination of MO-P3-Random over the MO-P3-Smart in the case of single-hall test cases do not seem to significantly influence the results for test cases considering many production halls.\par \begin{figure} \includegraphics[width=\linewidth]{paints_mop3_random_vs_smart.png} \caption{The $FFE_{Random}/FFE_{Smart}$ ratio of FFE spent on reaching the final result by MO-P3-Random and MO-P3-Smart for test cases with a single production hall}. Horizontal axis: problem size \label{fig:ffeRationSmartvSRandom} \end{figure} In Figure \ref{fig:ffeRationSmartvSRandom}, we show the $FFE_{Random} / FFE_{Smart}$ ratio for test cases with a single production hall. The $FFE_{Strategy}$ is the median FFE necessary for finding the final solution. The figure shows which method has been faster depending on the number of genes necessary to encode the problem solution. We abandon such a comparison for the multi-hall test cases because there are no statistically significant differences in the FFE number necessary to find the final solution between MO-P3-Random and MO-P3-Smart. If the value of the ratio is below $1$, then MO-P3-Random is faster, if it is higher, then the situation is the opposite. Note that the longer is the genotype, the faster is MO-P3-Random when compared to MO-P3-Smart. Such observation is coherent with the conclusion that the likely reason for the low effectiveness of MO-P3-Smart is the loss of linkage diversity. The lower is the number of genes, the less important is the quality of linkage \cite{linkageQuality}. In other words, the chance for successful crossing is inversely proportional to the genotype length (see Section \ref{sec:exp:benchmarks}). That is why MO-P3-Smart is almost equally fast to find the final solution for the genotypes of the length not exceeding 200 genes (for two test cases, it is even faster than MO-P3-Random). However, for longer genotypes, MO-P3-Random is up to twenty times faster (with equal or better results quality). The reasonable explanation of this observation is that MO-P3-Random posses linkage that is good enough to optimise any part of the Pareto front, while MO-P3-Smart does not due to the bias caused by the \textit{smart} strategy. The situation in which precisely constructed algorithms (or their parts) are outperformed by their random-based competitors is rather rare and may be found as a phenomenon. However, in the literature of the field, we may point the similar cases \cite{linkageLearningIsBad2}.\par Since MO-P3-Random outperforms MO-P3-Smart, in the latter parts of this paper, we will consider only MO-P3 that employs the \textit{random} strategy only. Thus, whenever we refer to MO-P3, we mean MO-P3-Random. \subsection{FFE and Computation Time Ratio Comparison} \label{sec:exp:paints:ffeTimeRatio} Figure \ref{fig:plotFfeRatio} presents the median fitness function evaluation number per second ratio. All MOBCPP test cases have been considered. The values have been measured for short 10-minute runs performed on PowerEdge R430 Dell server Intel Xeon E5-2670 2.3 GHz 64GB RAM with Windows 2012 Server 64-bit installed. To assure the precision of computation time measurement, the number of computation processes has always been one fewer than a number of available CPU nodes. All experiments have been executed in a single thread without any other resource-consuming processes running. Such an experiment setup seems reliable for experiments using a time-based stop condition. Similar experiment setup may be found in \cite{muppets,3lo,muppetsActive}\par As stated in Subsection \ref{sec:exp:paints:setup}, for the considered test problem, the significant amount of computation resources is spent only on fitness value computation. Nevertheless, the $FFE/ComputationTime$ ratio comparison is important as it shows which method is faster. \begin{figure} \includegraphics[width=\linewidth]{plotFfeRatio.png} \caption{Median $FFE/ComputationTime$ ratio per method for all considered test cases} \label{fig:plotFfeRatio} \end{figure} As presented in Figure \ref{fig:plotFfeRatio}, MO-P3 is significantly faster than any other considered method. The statistical significance of median differences has been confirmed by the Wilcoxon signed-rank test. For the null hypothesis that the median $FFE/ComputationTime$ ratio is equal to the median of any other method, the \textit{p}-value has not been higher than $10^{-56}$. NSGA-II and MOEA/D results are dependent on the population size. Such an observation is expected since the smaller the population size is, the more likely the population is to stuck. When the population is stuck, the method frequently requires fitness computation for the same genotypes. If this happens, the fitness may be recomputed or recovered from the caching buffer that stores the fitness values for some of the already considered genotypes. In the considered experiments, all methods have been joined on the problem definition level and the fitness is not recomputed if an individual remains unchanged. Therefore, the $FFE/ComputationTime$ ratio for NSGA-II and MOEA/D with low population size values is low. Note that fitness caching may lead to the following consequences. If the method is stuck and tends to consider the same and small subset of encodable genotypes, the $FFE/ComputationTime$ ratio may become so low, that the computation resources spent on other method activities than the fitness computation will become so significant that FFE will not be a fair and reliable measure. A more detailed analysis of this phenomenon may be found in \cite{fitnessCaching,PEACh,PEAChWPlfl}. Due to the very low $FFE/ComputationTime$ ratio values obtained for NSGA-II and MOEA/D, the considered population size for these methods is 400 individuals hereafter. \subsection{The Comparison between MO-P3 and the Competing Methods} \label{sec:exp:paints:moP3moGomea} \begin{figure} \includegraphics[width=\linewidth]{plotIGDPaintsMop3MogoMoeadNsga.png} \caption{The IGD-based comparison of considered methods for test cases using a single hall} \label{fig:paintsSingleHall} \end{figure} \begin{figure} \includegraphics[width=\linewidth]{plotIGDmultiPaintsMop3MogoMoeadNsga.png} \caption{The IGD-based comparison of considered methods for multi-hall test cases} \label{fig:paintsMultiHall} \end{figure} The IGD comparison between MO-P3 and the rest of the considered methods is presented in figures \ref{fig:paintsSingleHall} and \ref{fig:paintsMultiHall}. MO-P3 outperforms NSGA-II and MOEA/D for both types of test cases. Such a result is expected since neither NSGA-II nor MOEA/D uses linkage information. Therefore, these methods are not capable of recognising the nature of the problem and do not use this knowledge to improve the effectiveness of the optimisation process. Thus, in the latter part of this subsection, we compare MO-P3 with MO-GOMEA that employs linkage learning, the same as MO-P3 is parameter-less and has been proposed recently to solve multi-objective problems effectively.\par \begin{figure} \includegraphics[width=\linewidth]{ffeRatioMOP3vsMoGomea.png} \caption{The ratio of FFE spent on reaching the final result by MO-P3 and MO-GOMEA for test cases with a single production hall} \label{fig:ffeRatioMOP3vsMOGOMEA} \end{figure} For all the test cases considering a single production hall, the median IGD values obtained by MO-P3 and MO-GOMEA have been equal. However, MO-P3 has been significantly faster in finding the solution in most of the runs. The Wilcoxon signed-rank test with the 5\% significance level has confirmed that these differences are statistically significant for 7 test cases. For another 7 test cases, the differences have not been meaningful and MO-GOMEA has been faster for two test cases. Figure \ref{fig:ffeRatioMOP3vsMOGOMEA} shows the $FFE_{MOP3} / FFE_{MO-GOMEA}$ ratio (similarly to the ratio shown in Figure \ref{fig:ffeRationSmartvSRandom}). For most of the considered test cases, MO-P3 is about two times faster than MO-GOMEA. However, the FFE ratio presented in Figure \ref{fig:ffeRatioMOP3vsMOGOMEA} does not seem related to the genotype length. Such an observation has been expected as both the compared methods gather linkage and try to make it diverse. MO-GOMEA supports different linkages necessary to optimise different Pareto front parts by individuals clustering, while MO-P3 uses a pyramid-like population structure.\par The situation is different for multi-hall test cases. For most of the test cases, both methods report similar IGD, but MO-P3 outperforms MO-GOMEA for four test cases and is outperformed only in one of them. The difference between single- and multi-hall test cases is that to successfully solve them, a method has to precisely decompose the problem into parts referring to different production halls. MO-P3 maintains a larger number of linkage sets. Thus it is more likely that some of these linkages will be precise enough to allow for successful exchange for some of the halls (see Section \ref{sec:relWork:linkageDiversityExample}). Therefore, for a relatively low number of halls, both methods report results of equal quality (for one of them MO-GOMEA even outperforms MO-P3). However, when the number of halls increases, MO-P3 outperforms MO-GOMEA. These differences are statistically significant. Moreover, MO-P3 has been faster than MO-GOMEA in finding the final result (in terms of FFEs) for 7 test cases of 11. For other test cases, the differences have been not statistically significant.\par For the MOBCPP problem, MO-P3 and MO-GOMEA yield results of similar quality. However, MO-P3 has outperformed MO-GOMEA for four test cases when many production halls are considered and has been outperformed by MO-GOMEA for one test case only. Since these results are statistically significant, we may state that MO-P3 outperforms MO-GOMEA for the MOBCPP problem. An important advantage of MO-P3 over MO-GOMEA is that MO-P3 requires fewer FFEs to reach the final result. This situation takes place for 11 out of 27 considered test cases, and only for two test cases, MO-GOMEA is better. If we consider the fact that MO-P3 performs about two times more FFEs per second than MO-GOMEA (see Figure \ref{fig:plotFfeRatio}), we can state that MO-P3 is better in solving MOBCPP because it reports the results of slightly higher quality and is significantly faster in reaching these results in terms of FFEs and computation time.\par In this section, we have shown that the proposed MO-P3 outperforms NSGA-II and MOEA/D for the considered practical problem. It has been also demonstrated that it performs better and significantly faster than MO-GOMEA. The intuition that in multi-objective optimisation the P3-based methods may be significantly faster than LTGA-based (GOMEA-based) in solving practical problem instances has been confirmed. To get the full view on MO-P3 effectiveness, we report the comparison based on popular theoretical benchmarks in the next section. \section{Experiments on Benchmark Problems} \label{sec:exp:benchmarks} In this section, we compare MO-P3 with MO-GOMEA, MOEA/D, and NSGA-II using various theoretical benchmarks. The objective of this comparison is to evaluate the overall MO-P3 effectiveness in solving assorted multi-objective problems. As a baseline, we use NSGA-II and MOEA/D. Similarly to the results presented in \cite{MoGomeaGecco,MoGomeaSwarm}, MOEA/D and NSGA-II were outperformed by MO-GOMEA. In this section, we show that except for one benchmark problem (multi-objective knapsack), MO-P3 performs even better than MO-GOMEA. \subsection{Benchmark Problems} In this section, we present the considered benchmark problems. We use the same benchmarks as in \cite{MoGomeaGecco,MoGomeaSwarm}. For Multi-objective weighted MAXCUT and Multi-objective knapsack, we have adopted the implementation from \cite{MoGomeaSwarm} and developed our implementations for \textit{Zeromax-Onemax}, \textit{Trap5-Inverse Trap5} and \textit{Leading Ones Trailing Zeros} (LOTZ). \subsubsection{Zeromax-onemax} The objectives for \textit{Zeromax-onemax} problem are defined as \begin{equation} \label{eq:probDef:oneMaxZeroMax} f_{Onemax}(u) = u; f_{Zeromax}(u) = l-u, \end{equation} where $l$ is the genotype length and $u$ is the \textit{unitation} (see Section \ref{sec:relWork:linkageDiversity}). Thus, $f_{Onemax}$ maximises the number of ones in the genotype, while $f_{Zeromax}$ maximises the number of zeros. The optimal Pareto front $\mathcal{P}_F$ contains $l+1$ points. Many solutions can refer to a single point on $\mathcal{P}_F$ except for the two extreme points that contain only ones and only zeros. Thus, it is potentially harder to find extreme parts of $\mathcal{P}_F$ than the extreme regions \cite{mohBOA}. Note that every encodable solution lies on $\mathcal{P}_F$. \subsubsection{Trap5-Inverse Trap5} Deceptive function of unitation~\cite{decFunc} has been introduced in Section \ref{sec:relWork:linkageDiversity} in formula (\ref{eq:dec3}). The inverse deceptive function of unitation is defined as \begin{equation} \label{eq:dec3inverse} \mathit{dec_{inverse}(u)}= \begin{cases} u - 1 & \text{if } u > 0\\ k & \text{if } u = 0 \end{cases}, \end{equation} where $u$ is a sum of gene values (so called \textit{unitation}) and $k$ is a deceptive function size. In this paper, we use $k=5$, which is the same setting as used in \cite{MoGomeaGecco,MoGomeaSwarm}. The \textit{Trap5-Inverse Trap5} problem is a concatenation of order-5 deceptive blocks. The first objective refers to the trap-5 function and maximises the blocks built from ones, while the second objective maximises the number of blocks built from zeroes. The number of points in $\mathcal{P}_F$ is $l/5+1$. Similarly to the case of the \textit{Zeromax-onemax} problem, there is only one solution that refers to each extreme $\mathcal{P}_F$ point, but there may be more solutions that refer to other parts of $\mathcal{P}_F$. Similarly to the single-objective optimisation, it is difficult to solve a problem built from deceptive blocks if a method is unable to obtain a linkage of appropriately high-quality \cite{MoGomeaSwarm,ltga}. \subsubsection{Leading Ones Trailing Zeros (LOTZ)} \textit{Leading ones trailing zeroes} is a classic benchmark in multi-objective optimisation. The first objective is the \textit{Leading Ones} function, while the second is \textit{Trailing Zeroes} function. They are defined as \begin{equation} \label{eq:lotz} \mathit{f_{LO}(x)}=\sum_{i=1}^{l-1} \prod_{j=1}^{i} x_j; \mathit{f_{TZ}(x)}=\sum_{i=1}^{l-1} \prod_{j=i}^{l-1} (1-x_j). \end{equation} The leading ones function ($f_{LO}$) optimises the number of subsequent ones at the beginning of a genotype. The trailing zeroes optimises the number of subsequent zeroes at the end of it. The number of points in the Pareto-optimal front is $l+1$. In the case of LOTZ, each point in $\mathcal{P}_F$ refers to exactly one genotype. \subsubsection{Multi-objective Weighted MAXCUT} We employ the same multi-objective MAXCUT problem version as in \cite{MoGomeaSwarm,MoGomeaGecco} and use the same source code implementing the MAXCUT problem as in \cite{MoGomeaSwarm}. The problem instances have been generated using the approach proposed in \cite{maxcutOrigin}. The problem is defined as follows.\par Let $G=(V,E)$ be a weighted undirected graph, where $V=(v_0, v_1,\ldots,v_l)$ is a set of $l$ vertices and $E$ is the set of edges $(v_i,v_j)$. Each edge has an associated weight $w_{i,j}$. In the weighted MAXCUT problem, the objective is to find a maximum cut which is a partition of $l$ vertices into two disjoint subsets $A$ and $B$ ($A = V\ B$) such that the total weight of edges $(v_i,v_j)$ having $v_i \in A$ and $v_j \in B$ is maximised. We solve each MAXCUT instance for two different weight sets, making this problem bi-objective.\par The solution is encoded as a string of $l$ bits, where each variable $x_i$ corresponds to each vertex. If $x_i=0$ then $v_i \in A$ and $v_i \in B$ otherwise. The same solution encoding has been used in \cite{MoGomeaSwarm,MoGomeaGecco}. In the experiments, we consider problem instances for $l \in \{12, 25, 50, 100\}$. The Pareto-optimal front $\mathcal{P}_F$ is necessary to compute IGD. For $l \in \{12, 25\}$, the optimal Pareto front has been obtained by the enumeration method. For $l=50$ and larger $\mathcal{P}_F$, we use the reference sets proposed in \cite{MoGomeaGecco}. The instances and the reference Pareto front sets are the same as in \cite{MoGomeaSwarm,MoGomeaGecco}. \subsubsection{Multi-Objective Knapsack} In the multi-objective knapsack problem, we consider $l$ items and $m$ knapsacks. Each knapsack $k$ has capacity $c_k$ and each item $i$ is characterised by weight $w_{i,k}$ and profit $p_{i,k}$ corresponding to each knapsack $k$. Each item $i$ may be either selected and placed in every knapsack or not selected at all. Thus, the problem solution may be encoded as an $l$-bit binary string. If the total weight of the selected items does not violate the capacity constraint of any knapsacks, the solution is feasible. The objective is to maximise the profits of all knapsacks at the same time. The problem may be defined as \begin{equation} \label{eq:knapsack} \max_x (f_0(x), f_1(x),\ldots,f_{m-1}(x)),\\ \end{equation} where $f_k(x) = \sum_{i=0}^{l-1}p_{i,k}x_i$ for $k=0,1,\ldots,m$ and subject to $\sum_{i=0}^{l-1} w_{i,k}x_i~\leq~c_k$. We use the same problem implementation as in \cite{MoGomeaSwarm}. Therefore, we also use the same mechanism to repair a solution that violates the constraints \cite{knapsackRepair}. The repair algorithm removes selected items one by one until all the constraints are satisfied. The items with the lowest profit/weight ratio are removed first.\par We employ the same bi-objective knapsack instances as in \cite{MoGomeaSwarm,knapsackRepair}. The considered number of items is $l \in \{100, 250, 500, 750\}$. For the instance of 750 items, we use pseudo-optimal $\mathcal{P}_F$ created by the combination of many Pareto fronts and employed in \cite{MoGomeaSwarm}. For the remaining instances, we use the optimal Pareto fronts reported in \cite{knapsackRepair}. \subsection{Main Results for Benchmarks} \begin{figure} \includegraphics[width=\linewidth]{plotScalabilitySimpleBench.png} \caption{Scalability of MO-P3 and the competing methods for benchmark problems.} \label{fig:scalePerfsimpleBench} \end{figure} In Figure \ref{fig:scalePerfsimpleBench}, we show MO-P3, MO-GOMEA, and MOEA/D scalability on the \textit{Zeromax-Onemax}, \textit{Trap5-Inverse Trap5}, and \textit{LOTZ} problems. We present the median FFE necessary to find the optimal Pareto front. NSGA-II is excluded from the comparison because it has not found the optimal Pareto front in most of the runs for each problem. For these benchmarks, MO-P3 outperforms MO-GOMEA. This supremacy is caused by the following reason. For all three benchmarks, the linkage is the same for all Pareto front parts. For instance, for the \textit{Trap5-Inverse Trap5} problem, the corresponding bits always occupy the same blocks. This situation may favour MO-P3 because population clusterisation employed by MO-GOMEA does not guarantee any benefits. However, thanks to using linkage learning, MO-GOMEA is the only competing method that can successfully solve the \textit{Trap5-Inverse Trap5}. MOEA/D and NSGA-II were unable to find the optimal Pareto front even for a 25-bit problem version. Note that for the problems based on deceptive trap functions, the DSM-using methods (e.g., MO-GOMEA and MO-P3) are capable of finding the perfect problem decomposition in the early stages of the run \cite{linkageQuality}. This capability allows them to solve the problem. \begin{figure} \includegraphics[width=\linewidth]{plotScalabilityMaxcut.png} \caption{Scalability of MO-P3 and the competing methods for the Maxcut problem} \label{fig:scalabilityMaxcut} \end{figure} \begin{figure} \includegraphics[width=\linewidth]{plotScalabilityKnap.png} \caption{Scalability of MO-P3 and the competing methods for the Knapsack problem} \label{fig:scalabilityKnap} \end{figure} In Figure \ref{fig:scalabilityMaxcut}, we present the scalability on the MAXCUT problems. MO-P3 performs better than all the remaining considered methods including MO-GOMEA. It is the only method that can solve all the MAXCUT instances for $l \leq 50$. On the other hand, MO-GOMEA outperforms MO-P3 for the bi-objective Knapsack problem (Figure \ref{fig:scalabilityKnap}). For this problem, MO-P3 is also slightly outperformed by MOEA/D. Note that bi-objective knapsack problem is the only problem considered in this paper for which MO-P3 has been outperformed by any other method. \section{Results Discussion} In this paper, we have proposed a new multi-objective optimisation method based on the proposition of the Parameter-less Population Pyramid. MO-P3 uses a weighted vector to optimise new solutions added to the pyramid. Two different strategies have been considered: \textit{random} and \textit{smart}. The comparison based on a practical MOBCPP problem has shown that MO-P3-Random performs better. Such an observation may be surprising but is well explainable as the \textit{random} strategy does not bias MO-P3 towards any part of the Pareto front. The lack of bias allows MO-P3 to maintain a diverse linkage that seems to be the key to solve the considered practical problem. The importance of linkage is also supported by the comparison between MO-P3 and NSGA-II. For all the considered test cases except the smallest one, MO-P3 has outperformed NSGA-II as the IGD values for MO-P3 have been equal to $0$ in all the runs. It means that at least some of the points from the Pareto fronts proposed by NSGA-II have been dominated by the points from the Pareto fronts proposed by MO-P3.\par The comparison with MO-GOMEA on the base of MOBCPP instances shows that both the methods yield results of the same quality. However, for most of the test cases, MO-P3 requires significantly fewer FFEs to reach the best result. These results confirm the intuition presented in Section \ref{sec:mop3} that a P3-based method may be more suitable to solve practical problems than the LTGA-based ones. The high potential of MO-P3 application to practical problems is also confirmed by the analysis of the $FFE/ComputationTime$ ratio. It is significantly higher for MO-P3 than for MO-GOMEA and NSGA-II since MO-P3 does not spend the computation resources on the population clusterisation performed by MO-GOMEA and the computation of the crowding distance done by NSGA-II.\par The comparison made on the multi-objective benchmarks also indicates high effectiveness and high efficiency of MO-P3. For \textit{Zeromax-Onemax}, \textit{Trap5-Inverse Trap5} and \textit{LOTZ} problems, MO-P3 has found the optimal Pareto front in all runs, outperforming MO-GOMEA and NSGA-II. MO-GOMEA has been unable to find the optimal Pareto front for $l>25$. Moreover, for these three problems, MO-P3 has found the optimal Pareto fronts up to 100 times faster than MO-GOMEA. For the MAXCUT problem, MO-P3 has also outperformed the competing methods. Bi-objective Knapsack problem has been the only problem for which MO-GOMEA yielded Pareto fronts of better quality. The detailed analysis of MO-GOMEA and MO-P3 behavior for the Knapsack problem instances requires further investigation and is out of this paper's scope. However, it is possible that for the considered problem instances, MO-GOMEA can divide its population into such clusters that it obtains the linkage of high quality (the linkage that shows the true gene dependencies for the considered Pareto front parts).\par \section{Conclusions} In this paper, we have proposed MO-P3, a new method designed to solve a practical industrial multi-objective problem related to the process of production planning. The proposed method is adjusted to the problem with the appropriate solution encoding-decoding algorithm. Since solutions are represented by binary strings, MO-P3 has been compared with NSGA-II that is a typical baseline in multi-objective optimisation and MO-GOMEA that is an up-to-date method in solving multi-objective problems in discrete domains. Our proposition outperforms all competing methods for the set of considered practical problem instances.\par The experiments conducted on a set of typical benchmarks have confirmed both high-effectiveness and high-efficiency of MO-P3. The proposed method is not only capable of finding optimal or near-optimal Pareto fronts, but it is also the fastest in most of the cases. Additionally, it significantly outperforms both of the competing methods when the $FFE/ComputationTime$ ratio is taken into account. This positive feature is obtained thanks to the fact that MO-P3 does not require computationally costly operations like population clusterisation or crowding distance calculation.\par The main future work directions are as follows. The behaviour of MO-P3 for the Knapsack problem must be analysed to investigate the reason it performs worse than MO-GOMEA for this problem. The other future work objective is the development of MO-P3 itself to further improve its effectiveness and efficiency. \section*{Acknowledgement} We would like to thank Hoang Luong (Centrum Wiskunde \& Informatica) for giving us the access to the original MO-GOMEA source codes which has significantly speeded up the experiments preparation process and improved the paper quality.\par We also wish to express our gratitude to Marcin Komarnicki (Wroclaw University of Science and Technology) for helping us in organising the source codes and improving readability and composition of the paper.\par The authors acknowledge the support of the EU H2020 SAFIRE project (Ref. 723634).
{'timestamp': '2020-09-21T02:17:36', 'yymm': '2009', 'arxiv_id': '2009.08929', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08929'}
arxiv
\section{Introduction} \begin{wrapfigure}{r}{0.45\textwidth} \vspace{-12.5pt} \includegraphics[width=0.45\textwidth]{images/area6_renderc.png} \captionsetup{justification=centering} \caption{Sample segmentation results on S3DIS \cite{2017arXiv170201105A} Area $3$.}\label{fig:area6} \vspace{-10pt} \end{wrapfigure} Semantic segmentation of large-scale 3D pointcloud data has attracted numerous interests in real-world applications. Automatic sight inspection for quality verification, for example, is one of the emerging applications for pointcloud semantic segmentation. Deployment of a 3D pointcloud semantic segmentation algorithm can avoid delays and reduce costs caused by human errors. Figure \ref{fig:area6} shows how accurately our proposed multi-resolution graph neural network can perform and semantic segmentation. When it comes to dense large-scale pointcloud scans, the current methods either require a significant reduction in the data density \cite{kpconv, qi2016volumetric, DBLP:journals/corr/LiPSQG16, DBLP:journals/corr/EngelckeRWTP16, pointnet, shelnet} or offer only limited processing capability for multiple scans \cite{DBLP:journals/corr/MasciBBV15, 10.1007/978-3-030-01237-3_6, pointnet2, pointcnn, pointweb}. Two challenges hinder the development of pointcloud semantic segmentation algorithms on dense large-scale pointcloud scans. The first is the extensive memory usage for processing dense pointclouds with up to billions of data points in a single scan. Prior research has attempted to downsample from the original pointcloud to the state that common computing hardware can be utilized. Performing drastic downsampling on dense pointcloud can, however, negatively impact the segmentation result on dense pointcloud. Intricate details initially present in the dense pointcloud input are removed during the downsampling process. This is undesirable since sparse pointclouds contain less geometric features. The segmentation result obtained with sparse pointcloud would be inaccurate when interpolating back onto the original dense pointcloud. To address this issue, we convert the large-scale pointclouds into semantically similar point clusters. By doing this, the amount of GPU memory demanded by the semantic segmentation network is drastically reduced. When tested on the benchmarked dataset Stanford Large-Scale 3D Indoor Spaces Dataset, we observe that MuGNet can inference at once up to 45 pointclouds, each containing on average 2.6 million points. Besides the challenge posed by computation requirement, semantic segmentation is also challenged by the orderless and uneven nature of the raw pointclouds. This leads to the less desirable performance of deep convolutional neural networks, which require evenly arranged and ordered data. Prior research has attempted to convert the orderless pointclouds to mesh or voxels as ways to artificially structure pointclouds before applying deep convolutional neural networks \cite{qi2016volumetric, DBLP:journals/corr/LiPSQG16, DBLP:journals/corr/EngelckeRWTP16, acnn, interpolate}. Such attempts typically result in voluminous rendered data and introduce unnecessary computation overhead to the algorithm. To overcome this challenge, we propose a framework with graph convolutions that are invariant to permutations of pointcloud orderings. Segmentation can thus be performed without artificially structuring the pointcloud. In addition to addressing the two major challenges, our proposed framework also features a bidirectional multi-resolution fusion network. The framework reasons the relationship between adjacent clusters at different resolutions with both forward and backward paths. We observe that the concatenated graph features from different resolutions provide richer feature representation compared to the resultant features from the final convolution layer alone. The backward fusion network then further enriches the representations. With the aforementioned design components, we demonstrate that our proposed MuGNet achieves 88.5\% overall accuracy and 69.8\% mIOU accuracy on Stanford Large-Scale 3D Indoor Spaces Dataset semantic segmentation, outperforming SPG \cite{DBLP:journals/corr/abs-1711-09869} by 7.7\% better mIOU accuracy and 3\% better overall accuracy. Figure \ref{fig:area6} presents a sample semantic segmentation result for Area 3 in the Stanford Large-Scale 3D Indoor Spaces Dataset. \section{Related Work} \label{sec:citations} Three main categories of learning-based frameworks have been previously proposed for pointcloud semantic segmentation: voxel-based approach, point-based approach and graph-based approach. We outline the corresponding approaches as follows. \hspace{5mm} \textbf{Voxel-based approach:} As attempts to tackle the orderless and uneven nature of pointcloud, previous algorithms have ventured to convert pointcloud into structured voxel data such that convolution neural networks can be applied. Volumetric CNN \cite{qi2016volumetric} for example, pioneered on voxelized shapes; FPNN \citep{DBLP:journals/corr/LiPSQG16} and Vote3Deep \citep{DBLP:journals/corr/EngelckeRWTP16} proposed special methods to deal with the sparsity problem in volumes. Voxelizing a large pointcloud scan, however, imposes computation overhead. Such operation becomes infeasible for processing dense large-scale pointclouds. \hspace{5mm} \textbf{Point-based approach:} PointNet \cite{pointnet} has inspired many previous works to process pointclouds as direct input. Typical point-based frameworks learn feature encodings of each point. The encoded features are then aggregated with a permutation invariant function to arrive at transformation invariant segmentation results. Spatial and spectral convolutions have been implemented in previous works \cite{DBLP:journals/corr/MasciBBV15, Tang2019ChebNetEA,10.1007/978-3-030-01237-3_6, acnn, kpconv, pointcnn, pointnet2} to improve the efficiency of feature encoding. All of these approaches are demanding in memory usage and thus require either a sliding window approach or data downsampling approach to process dense pointclouds. In contrast, our framework alleviates the memory demand during the segmentation process by preforming point clusters based on geometric similarities. In this way, we can process multiple dense pointclouds at once with a commonly available GPU. \hspace{5mm} \textbf{Graph-based approach:} While pointclouds are inherently orderless and unevenly distributed, they can be represented as graphs with interdependency between points. Node classification can be performed to distinguish the classes among the nodes in the graph representations \cite{DBLP:journals/corr/KipfW16, DBLP:journals/corr/HamiltonYL17,velickovic2018graph}. Wang et al.\cite{DBLP:journals/corr/abs-1801-07829} first applied the concept of graph convolutional network on pointcloud data and formulated an approach that dynamically computes the graphs at each layer of the network. Various types of graph convolutional neural networks have since been utilized in the context of pointcloud segmentation \cite{mining, Wang2019_GACNet, DBLP:journals/corr/abs-1711-09869, eng, dgcnn}. All of the frameworks sequentially infer the graph embeddings with only forward network paths. On the contrary, we exploit a bidirectional framework that retains rich contextual information derived from multiple convolution units. The backward path of our network receives graph embeddings at different resolutions and infer rich contextual relationships to achieve high segmentation accuracy. \section{Proposed Computational Framework} \label{sec:methodology} \begin{figure}[htbp] \centering \includegraphics[width=0.85\textwidth]{images/overview.png} \captionsetup{justification=centering} \caption{Illustration of the overall workflow for MuGNet. The input pointcloud is first clustered, and then each formed cluster is classified into its respective semantic classes based on cluster-features.} \label{overview} \end{figure} Given a large-scale pointcloud with millions of points spanning up to hundreds of meters, directly processing it with a deep neural network requires an innumerable amount of computation capability. Downsampling points from the original pointcloud by order of magnitude is a common practice to cope with this limitation. This approach, however, takes away the intricate details in the original pointcloud and yet still suffers from expensive memory usage. We propose MuGNet, a multi-resolution graph neural network inspired by EfficientDet \cite{tan2019efficientdet}, to effectively translates large-scale pointclouds into directed connectivity graphs and efficiently segments the pointclouds from the formed graph with a bidirectional graph convolution network. MuGNet allows the processing of multiple large-scale pointclouds in a single pass while producing excellent segmentation accuracy. Figure \ref{overview} showcases the overall workflow of MuGNet. In the subsequent sections, we will further explain the cluster formation process and introduce the three key design features in our segmentation network: cluster feature embedding, feature-fusion backbone, and bidirectional-convolution network. \subsection{Clustering algorithm for graph formation} \label{sec:cluster} We preprocess large-scale pointclouds into geometrically homogeneous clusters, a 3D equivalent of superpixels commonly used in image analysis. The existing point clustering approaches can be roughly classified into unsupervised geometric approaches and supervised learning-based approaches. There is currently no standard clustering strategy that is suitable for large-scale pointclouds. We individually analyze their relative merits as follows and indicate our reasoning for choosing the supervised clustering approach. \hspace{5mm} \textbf{(1) Unsupervised clustering} Given a pointcloud data with millions of points, geometric features based on the neighborhood planarity, linearity, and scattering can be calculated \cite{article, DBLP:journals/corr/abs-1711-09869}. The unsupervised methods rely on the assumption that geometrically or radio-metrically homogeneous segments are also semantically homogeneous. This assumption is challenged when attempting to form semantically homogeneous clusters for semantic segmentation \cite{DBLP:journals/corr/abs-1904-02113}. Since the clusters are formed without the oversight of semantic information, the clusters can have semantic impurity among its constituting points. The impurity within each of the clusters negatively impacts the performance of the subsequent node classification network and limits the final semantic-segmentation accuracy. \hspace{5mm} \textbf{(2) Supervised clustering} The supervised-clustering method proposed by Landrieu et al.\cite{DBLP:journals/corr/abs-1904-02113} standardizes a pointcloud with a spatial transformer, embeds local feature with a small MLP-based network, and finally forms clusters by optimizing on the generalized minimal partition problem with the introduction of contrastive loss as a feedback metric for cluster purity. The supervised clustering approach achieves significant improvements compared to the unsupervised methods in terms of reduction in semantic impurity within the formed clusters. The semantically pure clusters can provide enhanced geometric and semantic connectivity information for subsequent learning tasks. On average the supervised clustering technique can effectively encapsulate pointcloud information of a Stanford Large-Scale 3D Indoor Spaces Dataset room scan containing $\sim2.6$ million points into $\sim10^3$ clusters. Compared to downsampling a pointcloud scan randomly, the conversion to point clusters can perform a drastic reduction in data size while carrying richer contextual information from the original pointcloud. Figure \ref{s3dis}(c) and \ref{vKITTI}(c) visualize sample pointcloud scans color-coded by geometric features and point clusters produced by the supervised clustering approach. \subsection{Cluster-feature Embedding} \label{sec:clusteremb} \begin{figure}[h] \centering \captionsetup{justification=centering} \includegraphics[width=0.9\linewidth]{images/network_all.png} \caption{MuGNet includes cluster embedding and bidirectional graph convolution networks. The input pointcloud is clustered based on their geometric similarities and learnable features into cluster set $C = \{C_1, C_2, ...C_K\},$ where $K$ denotes the total number of clusters formed for a pointcloud.} \label{network} \end{figure} As shown in Figure \ref{network}, our cluster-feature embedding network is applied to each of the formed pointcloud clusters. The points in a cluster go through a multi-resolution feature-fusion network with three sets of multi-layer perceptrons. The input points contain geometric features analogous to \cite{DBLP:journals/corr/abs-1711-09869}. The feature-fusion network receives pointcloud at three different resolutions. The highest resolution channel is defined as the cluster points, from which the other two lower-resolution channels are formed by down-sampling with linear layers. Each of the three-channel inputs then goes through a series of 2D convolutions, and their output features are concatenated together into a single feature vector. Utilization of the feature-fusion network for cluster-feature extraction effectively identifies cluster-features that are not only local representative but also distinctive at a larger receptive field. \subsection{Feature-fusion Backbone} \label{sec:backbone} \begin{wrapfigure}{r}{0.25\textwidth} \captionsetup{justification=centering} \vspace{-17.5pt} \includegraphics[width=0.25\textwidth]{images/backbone} \caption{Exploded-view of the backbone layers.}\label{fig:backbone} \vspace{-5pt} \end{wrapfigure} The node-classification network that identifies the semantic class for each formed cluster employs a backbone network to extract feature vectors at different resolutions. The feature vectors are subsequently fed to a bidirectional pyramidal feature-fusion network. Consider a graph $G(V, E)$ containing point clusters as nodes and node features obtained from the embedding network, where $V = {1, 2, ... N}$ and $E \subseteq |V|\times|V|$ represent the set of vertices and edges in the formed graph respectively. $N$ denotes the total number of nodes. The set of neighboring nodes of Node $i$ can be denoted as $N(i) = \{j:(i, j) \in E\} \cup \{i\}$. Each of the individual node feature $h_i\in\mathbb{R}^F$ is associated with a corresponding graph Node $i\in V$, among the set of node features, $H = \{h_1, h_2, ..., h_N\}$, where $F$ denotes feature dimension at each node. The backbone network consists of four residual blocks, each constructed with a graph convolution, batch normalization, and activation layer: $$H^{bb out}_i = Activation(BatchNorm(GraphConv(H^{bb in}_i))),$$ where $i$ denotes the level of backbone. It has been observed in previous works that with the message-passing mechanism for graph convolutions, the node features eventually become similar as the number of passing increases. Short-term and long-term residual connections are added to the basic building blocks to increase information density and avoid gradient diminishing as the network depth increases. For the short-term residual connection, the output features from the previous block are aggregated with a simple addition operation. The expression of the residual block with a short-term direct connection from the previous block is formulated as: $$H^{bb out}_2 = \{Activation(BatchNorm(GraphConv(H^{bb in}_2))) + H^{bb out}_1\}.$$ The outputs from the residual blocks are fed into the bidirectional graph convolution network in parallel. At the end of the backbone structure, the features are concatenated together for cluster classification: $$H^{bb out} = \{H^{bb out}_1, H^{bb out}_2, ..., H^{bb out}_4\},$$ where $H^{bb out}$ expresses the concatenated final feature output from the backbone network. \subsection{Bidirectioal-graph Convolution Network} \label{sec:bidirection} Multi-scale feature-fusion aims to aggregate features at different resolutions. Given a list of multi-scale features, $H^{in} = (H^{in}_{l1}, H^{in}_{l2}, ...)$, where each of $H^{in}_{li}$ represents the feature at level $l_i$, the feature-fusion network acts as a transformation function, $f$, that aggregates features at different resolution and outputs a list of new features denoted as $H^{out} = f(H^{in})$. The structure of the bidirectional graph convolution network is shown in Figure \ref{network}. The network receives graph features, $H^{in} = (H^{in}_{1} ...H^{in}_{4})$, at different resolutions from backbone levels 1-4. The conventional feature pyramidal network used in image tasks aggregates multi-scale features in a top-down manner and performs resizing operation for resolution matching. Each of the network node in the pyramidal network is formulated in a similar fashion to the basic backbone building block, where batchnorm and activation layers are incorporated on top of each of the graph convolution: $$H^{out}_i = Activation(BatchNorm(GraphConv(H^{in}_i))).$$ For graph convolutions, resizing becomes inefficient and causes information mixing during the message passing operation. The feature pyramidal network is thus redesigned to produce a constant number of features at each level: \begin{align*} & H^{out}_4 = GraphConv(H^{in}_4),\\ & H^{out}_3 = GraphConv(H^{in}_3+H^{out}_4),\\ & \cdots \\ & H^{out}_1 = GraphConv(H^{in}_1+H^{out}_2). \end{align*} While propagating the node features through a pyramidal network complements the baseline backbone structure by enriching the aggregated feature information, it is still limited by the one-way information flow. To address this issue, we configure a bidirectional graph propagation network that creates a two-way information flow to aggregate information for both the deep-to-shallow direction and the other way around. In addition to the bidirectional passes, a skip connection that travels from the input node to output node is incorporated for each resolution. In this way, feature information is more densely fused, and diminishing-gradient issue can be avoided to an extent. Resultant features from the fusion network for different resolutions contribute to the final output feature unequally, and naively concatenating the features together requires an unnecessarily heavy memory usage. Instead, an additional set of weights are introduced when aggregating the multi-res output features into a single feature vector. The intuition is to have the network itself learn the importance of each resolution during training. This approach not only avoids manual assignment of importance based on potentially biased or inaccurate human knowledge but also leads to a more elegant memory usage compared to naive concatenation. To give a sample formulation of the final graph bidirectional GraphConv network with learnable weights for different resolutions, the formulation for aggregation at level 3 is shown as follows: \begin{align*} & H^{mid}_3 = GraphConv(\frac{w_1 \cdot H^{in}_3 + w_2 \cdot H^{in}_4}{w_1 + w_2 + \epsilon}),\\ & H^{out}_3 = GraphConv(\frac{w_1' \cdot H^{in}_3 + w_2' \cdot H^{mid}_3 + w_3'\cdot H^{out}_2}{w_1' + w_2' + w_3' + \epsilon}), \end{align*} where $H^{in}_3$ indicates the middle feature-passing node at the third level on the top-to-bottom pathway. Features propagated from channels for the other resolutions are constructed in a similar fashion. The pathway and network edges are formulated according to connections shown in Figure \ref{network}. \\ We have found through experiments that graph neural network is prone to experiencing information assimilation, which leads to ineffective feature-fusion at deeper convolution levels. This phenomenon is conceptually analogous to the thermodynamic equilibrium state where the temperature gradient between two objects diminishes as the energy from one object is transferred to another. To address this problem, we send the output features from both the backbone network and the pyramidal fusion network to the segmentation module. \section{Results} \label{sec:result} In this section, we evaluate the MuGNet on various 3D pointcloud segmentation benchmarks, including the Stanford Large-Scale 3D Indoor Spaces(S3DIS) dataset \cite{2017arXiv170201105A}, and the Virtual KITTI(vKITTI) dataset \cite{DBLP:journals/corr/GaidonWCV16}. The network performance is evaluated by the mean Intersection-over-Union(mIOU), and Overall Accuracy (OA) of all object classes specific to each dataset. \subsection{Segmentation Results on S3DIS} \label{sec:benchmark} The Stanford Large-Scale 3D Indoor Spaces Dataset provides a comprehensive clean collection of indoor pointcloud scans. There are in total over 695 million points and indoor scans of 270 rooms \cite{2017arXiv170201105A}. Each scan is a dense pointcloud of a medium-sized room ($ \sim 20\times15\times5$ meters). We use the standard $6$-fold cross-validation approach in our experiments. \begin{figure}[htbp] \centering \captionsetup{justification=centering} \includegraphics[width=\linewidth]{images/s3dis.png} \caption{Qualitative semantic segmentation results of MuGNet on the validation set of S3DIS \cite{2017arXiv170201105A}.} \label{s3dis} \end{figure} Table \ref{s3dis_6fold} shows the network's performance averaged over all six areas. Our network has achieved better performance than state-of-the-art graph-based methods. When compared to the latest state-of-the-art for non-graph-based network RandLA-Net \cite{hu2019randla}, our network also achieves comparable results with 0.5\% higher overall accuracy and only 0.2\% lower mIOU. It should be noted that our network has been validated to consistently arrive at the reported result for the five times that the network is trained. In contrast, some of the baselines tend to produce inconsistent results due to their random sampling operations. \begin{table}[!htbp] \setlength{\tabcolsep}{2pt} \centering \captionsetup{justification=centering} \scriptsize \begin{tabular}{c|cc|ccccccccccccc} \toprule \textbf{} & \textbf{OA} & \textbf{mIOU} & \textbf{ceiling} & \textbf{floor} & \textbf{wall} & \textbf{beam} & \textbf{column} & \textbf{window} & \textbf{door} & \textbf{chair} & \textbf{table} & \textbf{bookcase} & \textbf{sofa} & \textbf{board} & \textbf{clutter}\\ \midrule \textbf{PointNet \cite{pointnet}} & 78.5 & 47.6 & 88 & 88.7 & 69.3 & 42.4 & 23.1 & 47.5 & 51.6 & 42 & 54.1 & 38.2 & 9.6 & 29.4 & 35.2\\ \textbf{Engelmann et al. \cite{eng}} & 81.1 & 49.7 & 90.3 & 92.1 & 67.9 & 44.7 & 24.2 & 52.3 & 51.2 & 47.4 & 58.1 & 39 & 6.9 & 30.0 & 41.9\\ \textbf{DGCNN \cite{dgcnn}} & 84.1 & 56.1 & - & - & - & - & - & - & - & - & - & - & - & - & -\\ \textbf{SPG \cite{DBLP:journals/corr/abs-1711-09869}} & 85.5 & 62.1 & 89.9 & 95.1 & 76.4 & 62.8 & 47.1 & 55.3 & 68.4 & 73.5 & 69.2 & 63.2 & 45.9 & 8.7 & 52.9\\ \textbf{RandLA-Net \cite{hu2019randla}} & 88.0 & \textbf{70.0} & - & - & - & - & - & - & - & - & - & - & - & - & -\\ \textbf{MuGNet (ours)} & \textbf{88.5} & 69.8 & \textbf{92.0} & \textbf{95.7} & \textbf{82.5} & \textbf{64.4} & \textbf{60.1} & \textbf{60.7} & \textbf{69.7} & \textbf{82.6} & \textbf{70.3} & \textbf{64.4} & \textbf{52.1} & \textbf{52.8} & \textbf{60.6}\\ \bottomrule \end{tabular} \vspace{0.5em} \caption{Semantic segmentation results measured by overall accuracy, mean intersection over union, and intersection over union of each class for all six areas in S3DIS dataset \cite{2017arXiv170201105A}.} \label{s3dis_6fold} \end{table} \begin{table}[!htbp] \setlength{\tabcolsep}{2pt} \centering \captionsetup{justification=centering} \scriptsize \begin{tabular}{c|cc|ccccccccccccc} \toprule \textbf{ } & \textbf{OA} & \textbf{mIOU} & \textbf{ceiling} & \textbf{floor} & \textbf{wall} & \textbf{beam} & \textbf{column} & \textbf{window} & \textbf{door} & \textbf{chair} & \textbf{table} & \textbf{bookcase} & \textbf{sofa} & \textbf{board} & \textbf{clutter}\\ \midrule \textbf{PointNet \cite{pointnet}} & - & 41.1 & 88.8 & 97.3 & 69.8 & 0.05 & 3.9 & 46.3 & 10.8 & 52.6 & 58.9 & 40.3 & 5.8 & 26.4 & 33.2\\ \textbf{Engelmann et al. \cite{eng}} & - & 48.9 & 90.1 & 96.0 & 69.9 & 0.0 & 18.4 & 38.3 & 23.1 & 75.9 & 70.4 & 58.4 & 40.9 & 13.0 & 41.6\\ \textbf{SPG \cite{DBLP:journals/corr/abs-1711-09869}} & 86.4 & 58.0 & 89.3 & 96.9 & 78.1 & 0.0 & 42.8 & 48.9 & 61.6 & 84.7 & 75.4 & 69.8 & 52.6 & 2.1 & 52.2\\ \textbf{GACNet \cite{Wang2019_GACNet}} & 87.8 & 62.8 & \textbf{92.3} & \textbf{98.3} & 81.9 & 0.0 & 20.3 & \textbf{59.1} & 40.8 & 78.5 & \textbf{85.8} & 61.7 & \textbf{70.7} & \textbf{74.7} & 52.8\\ \textbf{MuGNet (ours)} & \textbf{88.1} & \textbf{63.5} & 91.0 & 96.9 & \textbf{83.2} & \textbf{5.0} & \textbf{37.0} & 54.3 & \textbf{62.6} & \textbf{85.3} & 76.4 & \textbf{70.1} & 55.2 & 55.2 & \textbf{53.4}\\ \bottomrule \end{tabular} \vspace{0.5em} \caption{Semantic segmentation results measured by overall accuracy, mean intersection over union, and intersection over union of each class in Area $5$ of S3DIS dataset \cite{2017arXiv170201105A}.} \label{s3dis_a5} \end{table} We would also like to investigate our network's performance compared to GACNet \cite{Wang2019_GACNet}, a state-of-the-art graph convolution for pointcloud semantic segmentation. The results for Area $5$ are compared since this is the only area reported for the work. As shown in Table \ref{s3dis_a5}, our network still achieves better performance than the rest of the baselines for the segmentation task on Area $5$. Besides, most of the compared baseline networks struggle with handling a single pointcloud scan at once. They require drastic down-sampling and dividing of a large pointcloud room into small $1\times 1 \times 1$ blocks with sparse points. Our network, on the other hand, can effectively process multiple rooms in a single pass. \subsection{Segmentation Results on Virtual KITTI} \label{sec:vKITTI} \begin{figure}[htbp] \centering \captionsetup{justification=centering} \includegraphics[width=\linewidth]{images/vkitti_corl.png} \caption{Qualitative semantic segmentation results of MuGNet on the validation set of vKITTI \cite{DBLP:journals/corr/GaidonWCV16}.} \label{vKITTI} \end{figure} The Virtual KITTI (vKITTI) dataset \cite{DBLP:journals/corr/GaidonWCV16} contains simulated LiDAR data acquired through $50$ annotated $1242 \times 375$ resolution monocular videos generated from five different worlds in urban setting. Each of the scans in the dataset is a dense pointcloud with $13$ semantic classes. The annotated 2D depth images are projected into 3D space to produce the simulated LiDAR scans that resemble pointclouds obtained by real-life LiDAR scanners. For testing and training, the scans are separated into $6$ non-overlapping sets. We obtain the final evaluation following the $6$-fold validation protocol. \begin{table}[!htbp] \setlength{\tabcolsep}{2pt} \centering \captionsetup{justification=centering} \scriptsize \begin{tabular}{c|cc|ccccccccccccc} \toprule \textbf{} & \textbf{OA} & \textbf{mIOU} & \textbf{terrain} & \textbf{tree} & \textbf{vegetation} & \textbf{building} & \textbf{road} & \textbf{g-rail*} & \textbf{t-sign*} & \textbf{t-light*} & \textbf{pole} & \textbf{misc} & \textbf{truck} & \textbf{car} & \textbf{van}\\ \midrule \textbf{PointNet \cite{pointnet}} & 63.3 & 17.9 & 32.9 & 76.4 & 11.9 & 11.7 & 49.9 & 3.6 & 2.8 & 3.7 & 3.5 & 0.7 & 1.5 & 25.1 & 3.4\\ \textbf{Engelmann et al. \cite{eng}} & 73.2 & 26.4 & 38.9 & 87.1 & 14.6 & 44.0 & 58.4 & 12.4 & 9.4 & 10.6 & 5.3 & 2.2 & 3.6 & 43.0 & 13.3\\ \textbf{MuGNet (ours)} & \textbf{85.1} & \textbf{50.0} & \textbf{70.0} & \textbf{88.6} & \textbf{35.2} & \textbf{63.0} & \textbf{80.2} & \textbf{40.8} & \textbf{32.0} & \textbf{56.3} & \textbf{23.4} & \textbf{3.92} & \textbf{7.1} & \textbf{84.3} & \textbf{65.4}\\ \bottomrule \end{tabular} \vspace{0.5em} \caption{Overall accuracy, mean intersection over union, and intersection over union of each class for all six splits in vKITTI dataset\cite{DBLP:journals/corr/GaidonWCV16}. *"t-" is short for traffic; "g-" is short for guard.} \label{vkitti_6fold} \end{table} Table \ref{vkitti_6fold} shows a quantitative comparison of MuGNet against other benchmark methods for the dataset, and Figure \ref{vKITTI} presents MuGNet's qualitative segmentation result. The reported model is trained with the XYZ coordinates without RGB values to investigate our model's ability to learn geometric features. For comparison purposes, the benchmarked models are also trained with the same configuration. MuGNet has demonstrated to exceeded previous approaches in all evaluation metrics. It should be noted that during inference MuGNet can fit all $15$ scans in each of the six splits into a single GPU simultaneously, making it more viable for inspection tasks where computation resource is limited. \subsection{Efficiency Analysis} \label{sec:efficiency} The scalability of MuGNet is investigated by increasing the number of rooms to be processed in a single shot with the Stanford Large-Scale 3D Indoor Spaces(S3DIS) dataset \cite{2017arXiv170201105A}. Table \ref{table:efficiency_table} showcases the number of rooms for inference against the respective inference time and GPU memory consumption, and Figure \ref{fig:efficiency_plot} presents the corresponding plot of the trend. With a setup of single NVIDIA RTX $1080$Ti GPU, up to $45$ rooms (totaled $38,726,591$ points) can be accommodated into the available computation resource. We have observed that with an increase of room number, the increase in memory usage slows down and resembles a pseudo-logistic growth. The inference time also only increases at a relatively low rate. The growth trends indicate that the model scales nicely with an increased number of scans to be processed. The model would, therefore, be desirable for the application scenario where a multitude of dense scans need to be processed with few shots. \begin{figure}[!htb] \minipage{0.6\textwidth} \scriptsize \begin{tabular}{ p{.16\textwidth}| p{.33\textwidth}| p{.33\textwidth} } \toprule \textbf{\# of Rooms} & \textbf{Mean Inference Time(sec)} & \textbf{GPU Memory Usage(GB)} \\ \midrule \textbf{1} & 0.5056 & 1.042\\ \textbf{5} & 0.5396 & 4.073\\ \textbf{12} & 0.6124 & 6.684\\ \textbf{34} & 0.7077 & 10.365\\ \textbf{45} & 0.8332 & 10.617\\ \bottomrule \end{tabular} \vspace{14pt} \captionof{table}{Efficiency analysis on S3DIS dataset \cite{2017arXiv170201105A}.}\label{table:efficiency_table} \endminipage\hfill \minipage{0.4\textwidth} \vspace{-4pt} \includegraphics[width=\linewidth]{images/efficiency_plot.png} \captionof{figure}{Corresponding efficiency plot.}\label{fig:efficiency_plot} \endminipage\hfill \end{figure} \subsection{Ablation Study} \label{sec:ablation} In order to further investigate the behavior of our network, we conduct the following ablation studies. All ablated networks are trained and tested with the same $6$-fold validation setup as previously mentioned in Section 4.1 . \hspace{5mm} \textbf{(1$\sim$3) Removing Bidirectional GraphConv:} We want to study the backbone's ability to propagate useful information. In conventional convolutions, it has been widely proven that deeper networks often produce features at a higher quality that are more representative of the entire data distribution and in turn enhance network performance. If this phenomenon remains true for graph convolutions, then using features from deeper layers of the backbone as input to Bidirectional GraphConv should in theory yield a higher accuracy segmentation result. After removing the bidirectional network entirely, we obtain the final features directly from the backbone network before feeding them to the segmentation network. We also vary the number of backbone blocks to $7, 14$, and $28$ to investigate the extent of the backbone structure's capability. From the three different depths that the backbone has been tested, it can be observed that increased backbone depth in fact leads to better performance. \hspace{5mm} \textbf{(4) Stacking multiple Bidirectional GraphConvs:} The Bidirectional GraphConv network is structurally capable of stacking multiple network copies in parallel. Previous works in 2D image processing have shown positive correlation between model performance and the number of stacked networks. However, graph convolutions are fundamentally different from the conventional convolutions for 2D images, where the filtering operation is replaced by a message-passing mechanism. Naively adopting the structure used in 2D image processing would lead to sub-optimal results. \hspace{5mm} \textbf{(5) Increase depth of backbone layers:} Previous studies on graph neural networks have alerted on the loss of expressive power as the network complexity increases \cite{express, power}. It is therefore crucial to investigate the impact of backbone depth to the Bidirectional GraphConv network. When the backbone layer is increased to $14$, and the last $4$-layer outputs are fed into the Bidirectional GraphConv, the resultant segmentation is deemed to be less optimal compared to having $4$ layers of the backbone. Besides, the GPU memory usage increases by $\sim1/3$ times from our final network. Despite the incorporation of short-term and long-term residual connections, graph convolutions are still prone to information assimilation among nodes. A deeper backbone network does not necessarily extract higher-quality features. \begin{table}[!htbp] \setlength{\tabcolsep}{2pt} \centering \captionsetup{justification=centering} \scriptsize \begin{tabular}{p{25em} | p{3.5em}} \toprule \textbf{ } & \textbf{mIOU\%}\\ \midrule \textbf{(1) Backbone with 7 layers} & 59.0\\ \textbf{(2) Backbone with 14 layers} & 53.4\\ \textbf{(3) Backbone with 28 layers} & 64.5\\ \textbf{(4) Stacking 2 bidirectional GraphConvs} & 66.3\\ \textbf{(5) MuGNet with 14-layer backbone} & 63.7\\ \textbf{(6) MuGNet Baseline} & \textbf{69.8}\\ \bottomrule \end{tabular} \vspace{0.5em} \caption{The $6$-fold validated mean IOU of ablated networks tested on the S3DIS dataset \cite{2017arXiv170201105A}.\\ The results are compared against the final MuGNet configuration.} \label{experiments} \end{table} \vspace{-2em} \section{Conclusion} \label{sec:conclusion} In this paper, we have demonstrated that it is possible to process a large quantity of dense pointcloud scans by reformulating the learning objective to utilize a bidirectional graph convolutional network. Most of the current approaches rely on drastic downsampling or sliding window operations, both of which negatively impact the segmentation result on dense pointclouds. In contrast, we effectively transform the pointclouds into graph representations, which radically reduce the computation demand and facilitate the processing of up to forty-five room scans with a single commercially available GPU. A multi-resolution cluster embedding network is introduced to provide high-quality representations of the point clusters. Finally, a bidirectional-graph convolution network aggregates useful features from different graph resolutions. Extensive experiments on benchmark datasets have proven our network's strong capability in processing a multitude of pointclouds. It has also achieved state-of-the-art accuracy for pointcloud semantic segmentation. Our model would be desirable for application scenarios where a multitude of pointcloud scans need to be processed at once, and detailed pointcloud information need to be retained in the segmented pointcloud. Future work will involve investigations on potential industrial applications for the model. \clearpage
{'timestamp': '2020-09-21T02:17:22', 'yymm': '2009', 'arxiv_id': '2009.08924', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08924'}
arxiv
\section{Introduction} \label{sec:intro}} \section{Introduction} \label{sec:intro} Meaningful information is often hidden in subtle interactions and associations within data. Naturally, graphs are well-suited to representing the connectivity structures that emerge from many real-world social, biological, and physical phenomena. Often, to gain a deeper understanding of a graph's topology, it is useful to summarize a graph through specific representative characteristics that capture its structure. These summarizations often abstract away some graph details and no longer represent any single graph, but rather an entire set of graphs sharing similar characteristics. The faithfulness of a graph model on an input graph is usually tested by asking a model to make predictions about the graph's evolution or by generating a new graph using some production scheme. In the generative case, if the model faithfully captures the source graph's structure, the subsequently generated graphs should resemble the original according to some similarity criteria. These graph models come in many varieties. For example, the Erdős–Rényi model relies only on external parameters---typically a count of nodes and edges---to determine how it will randomly connect nodes, making it incapable of truly \textit{learning} any deeper topological structure~\citep{erdos1960evolution}. More recent graph models, like the Chung-Lu model, improve on the Erdős–Rényi model by combining specific extrinsic parameters with information learned directly from the input graph~\citep{chung2002average}. Then, there are those models, including grammar-based schemes and graph neural networks, that are parameterized solely by the topology of the source graph. These latter two classes of graph models seek a more comprehensive approach by imbuing their production strategies with salient topological information extracted directly from the source graph. \begin{figure}[tb!] \centering \input{figures/inf-mirror-framework} \caption{The Infinity Mirror method iteratively fits a graph model $\mathcal{M}$ on $G_i$, uses the fit parameters $\Theta_i$ to generate a new graph $G_{i + 1}$, and repeats with $G_{i + 1}$. Model biases and errors are quickly revealed.} \label{fig:framework} \end{figure} Just as statistical biases exist in classical machine learning models, any graph model will make implicit assumptions and value judgments that influence the learning and generation process. Of course, this is not necessarily undesirable; principled assumptions are often necessary for decision-making. Certain aspects of graphs may be more important based on the model wielder's focus and intentions. Indeed, models like Chung-Lu---which learns a degree distribution---and the various stochastic block models, which capture clustering information, are clear about which graph properties they preserve and ignore. However, what assumptions do graph neural networks make when learning parameters from a source graph? What implicit biases drive a grammar-based model to extract one production rule over another? Often, these questions are difficult to answer, and these hidden inclinations may not be easily revealed using traditional methodologies. In this paper, we present the Infinity Mirror test: a framework for revealing and evaluating statistical biases present in graph models. The Infinity Mirror test takes its name from the children's toy, which contains two mirrors that reflect light interminably between them. As illustrated in Fig.~\ref{fig:framework}, this framework operates by iteratively applying a particular graph model onto a graph that it previously generated, constructing a sequence of generated graphs starting from some source graph. As a JPEG image reveals compression artifacts when repeatedly re-compressed, a graph will degenerate when the same model is repeatedly fit on its own outputs. This sequence of generated graphs can be analyzed using a variety of graph similarity metrics to quantify how the generated graphs diverge from the source graph. If the sequence is allowed to grow long enough, this repetition is likely to cause the sequence of graphs to deviate from the source in a way that exposes unknown statistical biases hidden in the model. \section{Preliminaries} \label{sec:prelim} A graph $G = (V,E)$ is defined by a finite set of nodes $V$ and a set of edges $E$. We denote a node by $v_i \in V$ and an edge between $v_i$ and $v_j$ is given by $e_{ij} = (v_i, v_j) \in E$. For convenience, we let $n = |V|$ and $m = |E|$. It is sometimes desirable to represent the graph as an $n \times n$ adjacency matrix $A$, where $A_{ij} = 1$ if $e_{ij} \in E$ and $A_{ij} = 0$ otherwise. We take the convention that all graphs are undirected, static, and unlabeled unless otherwise indicated. \subsection{Graph Models} A graph model $\mathcal{M}$ is any process or algorithm by which a set of salient features $\Theta$ can be extracted from a graph $G$. In prediction scenarios, the performance of $\mathcal{M}$ can be assessed using standard precision and recall metrics on held-out data. If $\mathcal{M}$ also describes how new graphs can be constructed from $\Theta$, its performance can be analyzed by comparing the generated graphs to $G$ using various measures of graph similarity. Early graph models like the random graph of Erd\H{o}s and R\'{e}nyi~\citep{erdos1960evolution}, the small world network of Watts and Strogatz~\citep{watts1998collective}, the scale-free graph of Albert and Barab\'{a}si~\citep{barabasi1999emergence} and its variants~\citep{bianconi2001competition,ravasz2003hierarchical}, or the more recent LFR benchmark graph generators~\citep{lancichinetti2008benchmark} generate graphs by applying hand-tuned parameters to some underlying generative process. This exercise of fine-tuning the model parameters to generate topologically faithful graphs to an input graph is taxing and often hard to achieve. In response, graph models were developed to automatically learn the topological properties of the source graph for more faithful generation. One of the first of this new generation of graph models was the Chung-Lu/configuration model~\citep{chung2002average}. It generated graphs by randomly rewiring edges based on the degree sequence of the source graph. Even though the degree sequence of the generated graph exactly matched that of the original, the configuration model often failed to incorporate higher-order topological structures like triangles, cliques, cores, and communities observed in the original graph. Since its introduction, more comprehensive models have attempted to fix these flaws by proposing improvements like incorporating assortativity and clustering~\citep{pfeiffer2012fast,mussmann2014assortativity,mussmann2015incorporating,kolda2014scalable}. For example, the Block Two-level Erd\H{o}s-R\'{e}nyi (BTER) model interprets its input as a scale-free collection of dense Erd\H{o}s-R\'{e}nyi graphs~\citep{kolda2014scalable}. BTER respects two properties of the original graph: local clustering and degree sequence. However, BTER sometimes fails to capture higher-order structures and degenerates in graphs with homogenous degree sequences (\textit{e.g.}, grids). Stochastic Block Models (SBMs) primarily consider communities in the source graph and then create a block matrix that encodes communities as block-to-block connectivity patterns~\citep{karrer2011stochastic, funke2019stochastic}. To generate a graph, the SBM creates an Erd\H{o}s-R\'{e}nyi graph inside each block and random bipartite graphs across communities. Since SBMs' introduction, they have been extended to handle edge-weighted~\citep{aicher2013adapting}, bipartite~\citep{larremore2014efficiently}, temporal~\citep{peixoto2015inferring}, and hierarchical networks~\citep{peixoto2014hierarchical}. Likewise, Exponential Random Graph Models (ERGMs)~\citep{robins2007introduction}, Kronecker graph models~\citep{leskovec2010kronecker,leskovec2007scalable,gleich2012moment}, and graph grammar models~\citep{aguinaga2018learning, sikdar2019modeling, hibshman2019towards} are able to generate graphs that are more-or-less faithful to the source graph. Recent advances in graph neural networks have produced graph generators based on recurrent neural networks~\citep{you2018graphrnn}, variational autoencoders~\citep{salha2020simple, kipf2016variational, li2018learning}, transformers~\citep{yun2019graph}, and generative adversarial networks~\citep{bojchevski2018netgan}, each of which has advantages and disadvantages. Graph autoencoders (GraphAE) learn an embedding of the input graph's nodes via message-passing and then construct new graphs by taking inner products of the embedding vectors and passing them through an activation function (\textit{e.g.}, sigmoid). NetGAN trains a Generative Adversarial Network (GAN) to \textit{generate} and \textit{discriminate} between real and synthetic random walks over the input graph. After training, the model builds graphs from random walks produced by the generator. GraphRNN, a kind of Recurrent Neural Network (RNN), decomposes the process of graph generation into two separate RNNs---one for generating a sequence of nodes, and the other for the sequence of edges. \begin{figure}[tb!] \centering \includegraphics[width=0.99\linewidth,bb=0in 0in 13.13in 21.39in]{figures/fig2-pdf.pdf} \vspace{.3cm} \caption{(A) Example graph with three distinct communities. (B) Graphs $G_1$, $G_5$, and $G_{10}$ are generated using the Infinity Mirror framework described in Fig.~\ref{fig:framework} for various models. Chung-Lu and Kronecker immediately lose the community structure of the source graph. Kronecker progressively makes the graph more dense. CNRG and SBM are able to retain the input graph's community structure, albeit with some appreciable deterioration. NetGAN is able to capture the topology of the input graph but fails to generate graphs beyond the first iteration.} \label{fig:toy-example} \vspace{-.2cm} \end{figure} \subsection{Graph Comparison Metrics} Graph models are typically evaluated by their ability to predict nodes and edges. Although the prediction task is important, it does not measure a model's ability to capture a graph's topological structure. Another evaluation approach involves comparing a source graph $G$ to a new graph $\hat{G}$ generated from $\mathcal{M}$ using a measure of graph similarity or divergence. Here, the choice of metric influences the differences and biases that are exposed within the model. The simplest graph comparison metrics are computed by comparing distributions of first-order graph properties like the graph's degree and PageRank distributions. In addition to visually inspecting these distributions, graph modelers also employ quantitative metrics like the Jensen-Shannon (JS) divergence. More advanced metrics compare two graphs by examining properties of their adjacency matrices. There are two conventional approaches in this space: (1) known node-correspondence metrics, which assume every node in $G$ has a known corresponding node in $\hat{G}$, and (2) unknown node-correspondence metrics, where there is no assumed node correspondence. \textsc{DeltaCON} is an example of a known node-correspondence metric that compares node affinities between $G$ and $\hat{G}$~\citep{koutra2013deltacon,koutra2016deltacon}. Affinities are measured using belief propagation, which associates every node with a vector measuring its influence on its $k$-hop neighbors. A score is produced by comparing the vectors of corresponding node affinities. Unfortunately, most graph models do not generate graphs with a known node-correspondence. Although best-guess node correspondence can be predicted if needed, known node-correspondence metrics like \textsc{DeltaCON} and the cut distance~\citep{liu2018cut} are not well-suited for the present work. Fortunately, there also exist many unknown node-correspondence metrics. Examples include Portrait divergence, $\lambda$-distance, and NetLSD~\citep{bagrow2019information,wilson2008study,tsitsulin2018netlsd}. We can also directly compare the graphlet counts~\citep{ahmed2015efficient} between $G$ and $\hat{G}$, or compute their graphlet correlation distance (GCD)~\citep{prvzulj2007biological} by counting node orbitals. The Network Laplacian Spectral Descriptor (NetLSD) is a permutation-invariant graph comparison method that simulates a heat diffusion processes on each graph. NetLSD produces a high-dimensional vector that corresponds to the sum of the heat in discretized timesteps over the simulation, and the Euclidean distance between these vectors can be used to compare two or more graphs. Finally, loss functions from recent graph neural network models compare $G$ to $\hat{G}$ by collating derived graph features like power-law exponents, diameters, and node centrality scores~\citep{bojchevski2018netgan}. In each case, the features extracted by a model and the generative process by which predictions are made carry inherent biases, which may elude even the most comprehensive performance or comparison metric. \section{Infinity Mirror Test} \label{sec:method} The Infinity Mirror~\citep{aguinaga2016infinity} test seeks to expose a graph model's implicit biases by iteratively computing hereditary chains of graphs generated by the model. For a graph model $\mathcal{M}$ and source graph $G_0$, we define a chain $\langle G_1, G_2, \dots, G_\ell \rangle$ of length $\ell$ by computing: $$G_{i + 1} = \mathcal{M}(G_i, \Theta_i)$$ \noindent at each iteration $i$ of the chain, where $\Theta_i$ denotes the features extracted from $G_i$ by the model $\mathcal{M}$. Fig.~\ref{fig:framework} illustrates this iterative fit-and-generate process. Because each subsequent graph is a lossy reflection of a previous graph, which itself may have been a lossy reflection of one prior, we expect that this chain of graphs will diverge from the source graph as the chain grows longer. By inspecting the divergence along the chain of generated graphs, patterns of model error or bias should become easier to detect. This chain of graphs can be evaluated from several different perspectives. The most straightforward way to measure the error in a chain is by comparing the initial graph $G_0$ to the last graph $G_\ell$ using a graph similarity metric. This provides insight into the total degradation resulting from model-specific errors and biases. A natural extension of this idea is to compare consecutive graphs in the chain. Let $\mu$ represent a specific graph comparison metric and $\Delta_i = \mu(G_{i - 1}, G_i)$, then each chain will provide a sequence $\mathbf{\Delta} = \langle \Delta_1, \dots \Delta_\ell \rangle$. This vector of distances can then be analyzed to extract information from one or multiple chains; for example, $\sum_i{\Delta_i}$ can be used as a proxy for the accumulated error measured by $\mu$ under repeated applications of $\mathcal{M}$. One might also consider accumulated error in $\mathbf{\Delta}$ as a kind of anti-convergence process, wherein the quality of $\mathcal{M}$ can be measured by stability in the chain. Analogously, analyzing the features $\Theta_i$ that a model learns when generating a chain might shine a light on the inner workings of a model, which might not be reflected by merely comparing output graphs to each other. However, this would require a more tailored, heuristic approach than we can provide in the present work as different generative models learn different sets of features that are often incomparable. \para{Kronecker Graphs.} Next, we apply the Infinity Mirror test on the Kronecker graph model, which is known to produce graphs that approximate a log-normal degree distribution (with a heavy tail)~\citep{seshadhri2013depth}. Although this property of the Kronecker graph model is often desirable, it is no doubt a bias that is encoded into the model. If we provide a source graph that does not follow a log-normal degree sequence, we expect the degree sequence of $\mathbf{\Delta}$ to diverge relative to the source graph. \begin{figure}[t!] \vspace*{5em} \centering \input{figures/kron_transition} \vspace*{0.5em} \input{figures/example_kron_dist} \vspace*{0.75em} \input{figures/example_kron_overtime} \caption{ (A) A generic $2\times 2$ Kronecker initiator matrix $\mathcal{I} = [a\, b; c\, d], 0 \le a,b,c,d < 1$ can be used to generate an adjacency matrix of size $2^n \times 2^n$ by using Kronecker products. (B) State transition diagram corresponding to the initiator matrix $\mathcal{I}$ in (A) visually representing the recursive growth process of Kronecker graphs. (C) Degree distribution on the Flights graph illustrated over seven fit-and-generate iterations of the Kronecker model. The Kronecker initiator matrix from \texttt{KronFit} is positioned over the individual ridge plots. (D) Jensen-Shannon divergence of the $i^\textrm{th}$ graph compared to source graph $JS(G_0,G_i)$ (red line) and of the $i^\textrm{th}$ graph compared to the $i-1^\textrm{th}$ graph $JS(G_{i-1},G_i)$ (green line). This example shows hidden bias in the Kronecker graph model: the degree distribution tends to flatten and oscillate after a few iterations. } \label{fig:kronexample} \end{figure} In the Kronecker model, graphs are modeled as a repeated Kronecker product of a $k \times k$ initiator matrix $\mathcal{I}$ (usually, $k = 2$) as shown in Fig.~\ref{fig:kronexample}(A). Every entry of $\mathcal{I}$ can be thought of as a transition probability between two states, as seen in Fig.~\ref{fig:kronexample}(B). The \texttt{KronFit}\footnote{\texttt{KronFit} and \texttt{KronGen} can be obtained from SNAP Stanford} utility can be used to fit the initiator matrix to an input graph, while the \texttt{KronGen} utility can be used to generate new graphs from an initiator matrix, by performing repeated Kronecker products of the initiator matrix. As a result, it can only generate graphs with nodes which are in powers of $k$. For example, consider the plots in Fig.~\ref{fig:kronexample}(C) which illustrate the degree distributions of a chain of graphs obtained by performing the Infinity Mirror test on a graph of airline flights\footnote{\url{https://openflights.org/data.html}} using the Kronecker model. The subplot labeled $G_0$ shows the degree distribution of the original Flights graph. We then fed the Flights graph to \texttt{KronFit} and generated a graph from the learned initiator matrix (\texttt{KronGen}) to create a new graph $G_1$~\citep{leskovec2010kronecker}. The plot labeled $G_1$ illustrates the degree distribution of this new graph. The degree distributions of $G_0$ and $G_1$ look visually similar. The next step is to compute some distribution similarity measure to analytically compare the two distributions (we use the Jensen-Shannon (JS) divergence), concluding that the graph model has some error $\epsilon$. Rather than stopping here, the Infinity Mirror methodology continues this fit-and-generate process. So, we input $G_1$ into the Kronecker model and generated a new graph $G_2$. Its degree distribution is illustrated in the plot labeled $G_2$. Likewise, the plots labeled $G_3,G_4,\ldots, G_7$ illustrate the degree distribution of subsequent iterations. A visual inspection of these plots shows that the degree sequence of the Kronecker model degenerates into an ever-spreading oscillating distribution. We also note that the entries in the Kronecker initiator matrices monotonically increase in magnitude across generations, signifying the increase in edge density~\citep{leskovec2010kronecker}. Fig.~\ref{fig:kronexample}(D) provides an analytical view of the visual plots on top as the number of iterations continues to $10$. The cumulative JS divergence compares the degree distribution of $G_0$ to $G_i$, thereby accounting for the error over multiple iterations; Conversely, the iterative JS divergence compares the degree sequence of $G_{i-1}$ to $G_{i}$, thereby accounting for errors in each iteration. The iterative error shows that each fit and generate procedure produces some amount of error, which is expected when performing any modeling. However, it is important to note that the cumulative error is not simply a summation of each iteration error. It is certainly possible for an iterative error made by some later iteration to correct an earlier error and lead to a decrease in the cumulative error. In this case, we show that the cumulative error starts off low, but diverges asymptotically. In summary, this iterative test can not only capture model-induced error, it can also reveal bias encoded in the model, such as the Kronecker model's dispersing degree distribution previously uncovered and formalized by Seshadhri \textit{et al.}~\citep{seshadhri2013depth}. \newpage \begin{figure*}[tb!] \centering \input{figures/degree_js} \input{figures/legend-degree} \caption{Jensen-Shannon (JS) divergence of degree distribution (top) and PageRank distribution (bottom) over 10 fit-and-generate iterations on three real-world datasets and two synthetic datasets. Plots represent mean JS divergence over 50 chains; confidence intervals are not plotted for clarity but do not exceed $\pm$0.028 in the worst case. The area above the Erd\H{o}s-R\'{e}nyi curves is shaded in gray to indicate worse than random performance. Some graph models tend towards total divergence over 10 iterations, indicating that they degenerate (in interesting ways). Other models are stable, indicating that they perform well on this data on the degree and PageRank metrics.} \label{fig:degree} \end{figure*} \section{Experiments} In this section, we apply the Infinity Mirror test to several graph models using relevant graph properties and metrics. The Infinity Mirror test reveals interesting error patterns in many graph models and also suggests hidden biases worthy of further investigation. Our open-source implementation can be found on GitHub\footnote{\url{www.github.com/satyakisikdar/infinity-mirror}}. \para{Data.} We perform experiments over five source graphs, denoted $G_0$. These include three real-world graphs commonly found in the graph modeling literature: OpenFlights (Flights), an email graph from a large European research institution (Email), and a network of chess competitions (Chess). We also examine synthetic graphs: a 3000-node tree (Tree) where each node has 2, 3, or 4 children with equal probability, and a ring of cliques (Clique-Ring) where each node in a 500-node ring is replaced by a 4-clique ($K_4$). Summary statistics on the datasets can be found in Tab.~\ref{tab:dataset}. \begin{table}[htb] \centering \caption{Dataset summary statistics. Avg CC is the average local clustering, and Avg PL is the average unweighted shortest path length.} \vspace{0.1cm} \footnotesize{ \begin{tabular}{@{} l rrr rr @{}} \toprule \textbf{Dataset} & \textbf{$\mathbf{|V|}$} & \textbf{$\mathbf{|E|}$} & \textbf{\# Triangles} & \textbf{Avg. CC} & \textbf{Avg. PL} \\ \midrule Flights & 2,905 & 15,645 & 72,843 & 0.45 & 4 \\ Email & 986 & 16,064 & 105,461 & 0.40 & 2.5 \\ Chess & 7,115 & 55,779 & 108,584 & 0.18 & 4 \\ Clique-Ring & 2,000 & 3,500 & 2,000 & 0.75 & 250 \\ Tree & 2,955 & 2,954 & 0 & 0 & 12 \\ \bottomrule \end{tabular} } \label{tab:dataset} \end{table} \para{Graph Models.} There are hundreds of possible graph models to which the Infinity Mirror test may be applied; however, the current work is not a survey of graph models; instead, we sample archetypal graph models from among the various options available. These include Chung Lu model~\citep{chung2002average}, clustering-based node replacement graph grammars (CNRG)~\citep{sikdar2019modeling}, block two-level Erd\H{o}s R\'{e}yni (BTER)~\citep{seshadhri2012bter}, degree-corrected stochastic block models (SBM)~\citep{karrer2011sbm}, hyperedge replacement graph grammars (HRG)~\citep{aguinaga2016growing, aguinaga2018learning}, Kronecker graphs~\citep{leskovec2010kronecker, leskovec2007scalable}, bottom-up graph grammar extractor (BUGGE)~\citep{hibshman2019towards}, generative adversarial network (NetGAN)~\citep{bojchevski2018netgan}, graph linear autoencoder (LinearAE)~\citep{salha2020simple}, graph convolutional neural networks (GCNAE)~\citep{kipf2016variational}, and graph recurrent neural networks (GraphRNN)~\citep{you2018graphrnn}. Random graphs generated using the Erd\H{o}s-R\'{e}nyi model with an edge probability equal to the density of the input graph are also included as a baseline. \para{Methodology.} For each combination of $\mathcal{M}$ and $G_0$, we create 50 independent fit-and-generate chains, each of length 10 (\textit{i.e.}, $G_1, G_2,\ldots,G_{10}$). The 50 independent chains are almost certainly different because each graph model incorporates some stochasticity during feature extraction, graph generation, or both. GraphRNN does not conform to the above format, because it learns from and generates batches of graphs at a time. For this model, we initially feed in 50 identical copies of $G_0$, which are used to generate a batch of 50 different $G_1$s; in this manner, every iteration of GraphRNN works on batches of 50 graphs for both input and output. In a small number of cases, some graph models (like NetGAN in Fig.~\ref{fig:toy-example}) degenerate to such an extent that they can no longer be refit on their output. In those cases, we plot as much data as possible before the model fails. \begin{figure*}[tb!] \centering \input{figures/deltacon} \input{figures/legend-degree} \caption{Portrait divergence (top) and $\lambda$-distance (bottom) over 10 fit-and-generate iterations on three real-world datasets and two synthetic datasets. Confidence intervals are not plotted for clarity, but do not exceed $\pm$0.021 in the worst case. The area above the Erd\H{o}s-R\'{e}nyi curves is shaded in gray to indicate worse than random performance. Like the degree and PageRank distributions in Fig.~\ref{fig:degree}, many graph models degenerate, but some remain stable.} \label{fig:deltacon} \end{figure*} \subsection{Degree and PageRank Metrics} In this section, following the Kronecker example, we show how the degree and PageRank distributions change over the iterations of the Infinity Mirror. The degree of a node is the number of connections it has in the graph, and the degree distribution describes the probability of a node having a given degree in a graph. For directed graphs, it is common to plot in-degree and out-degree distributions; for simplicity, in the present work, we consider only the total degree (in-edges plus out-edges). The degree distribution is a critical component in a graph's overall topology. The Chung-Lu model focuses exclusively on generating graphs with a degree distribution that conforms to an input degree distribution. Likewise, the Kronecker graph model's degree distribution has been rigorously analyzed and found to generate graphs with oscillating degree distributions that approximate a log-normal shape with a heavy tail. Early work on graph topology by Erd\H{o}s and R\'{e}nyi found that random graphs have a binomial degree distribution~\citep{erdos1960evolution}. Then Albert and Barab\'{a}si found that many large real-world graphs exhibit a power-law degree distribution~\citep{albert2002statistical}, which has been challenged recently by a comprehensive analysis showing that many degree distributions may look like they have power-law degree distributions, but have fat-tails~\citep{broido2019scale}. Graph models claiming to be comprehensive aught to accurately encode a graph's degree distribution regardless of its shape. The five plots in the top row of Fig.~\ref{fig:degree} show the mean JS divergence over the 50 independent trials between the degree distribution of the source graph $G_0$ and each new graph $G_i$ (\textit{i.e.}, the cumulative error from Fig.~\ref{fig:kronexample}). We compute error bars at the 95\% confidence level, but they are not plotted to maintain clarity. Over all datasets and models, the maximum 95\% confidence interval was $\pm0.028$, and most were $\pm0.01$. As expected, we find the Chung-Lu model, which directly and exclusively models the degree distribution, performs well on real-world graphs, but poorly on the synthetic graphs. This is likely because the Chung-Lu model is restrictive to graphs with a power-law degree distribution. However, the degree distribution of the synthetic graphs is multinomial and, therefore, not well modeled by the Chung-Lu model. The CNRG graph grammar model performs well at generating graphs that match the degree distribution of synthetic graphs. The random graphs of Erd\H{o}s and R\'{e}nyi are included as a baseline. We set the number of nodes and edges in the random graph generator equal to the number of nodes and edges in the source graph. As expected, the performance of the random graphs stays the same over various iterations. We expected that the performance of most graph models would degenerate towards the performance of the random graph. However, we show that some graph models quickly degenerate past the performance of the random model. In addition to the degree distribution, the bottom row in Fig.~\ref{fig:degree} show the results of the JS Distance of the PageRank distributions of $G_0$ and $G_i$. The PageRank algorithm assigns a weight to each node PR$(v)$ signifying the probability of a random walker over the graph's edges landing on that node. A node's PageRank score is highly correlated to its (in-) degree, but contains additional information about the graph's topology. However, unlike degree distribution, the PageRank is a real-numbered value, so the JS divergence cannot be directly calculated. In our analysis we create $100$ equal length bins from $0$ to $\underset{v \in \{V_0\cup V_i\}}{\max}(\textrm{PR}(v))$ and compute the JS divergence on these two PageRank distributions. As expected, the performance of each model using the PageRank distribution is similar to the degree distribution. In summary, the degree and PageRank distributions uncover known biases in the Kronecker and Chung-Lu graph generators. Specifically, that degree distributions of the Kronecker graph model oscillate and have a heavy tail, and that the Chung-Lu graph model works well on real-world networks that have (approximately) a power-law degree sequence, but do not accurately model non-scale-free synthetic graphs. \subsection{Portrait Divergence and $\lambda$-Distance} Degree and PageRank distributions describe a graph from an important but limited perspective. Indeed, similar values of degree and PageRank statistics do not necessarily imply a similar network topology~\citep{prvzulj2007biological}. A more thorough examination that compares the topology and internal substructures between the source graph and each new iteration is needed to describe each model in more detail. Among the many options~\citep{tantardini2019comparing}, we use Portrait divergence~\citep{bagrow2019information} and $\lambda$-distance~\citep{wilson2008study}, which are unknown node-correspondence graph distance measures to compare the topology of two graphs. The Portrait divergence is based on a portrait of a graph~\citep{bagrow2008portraits}, which is a matrix $B$ with entries $B_{\ell,k}$ such that $\ell=0,1,\ldots,d$, where $d$ is the graph diameter, and $k=0,1,\ldots,N-1$ is the number of nodes having $k$ nodes at the shortest path distance $\ell$. Simply put, the portrait of a graph measures the distribution of its shortest path lengths. Because the shortest path lengths are correlated with edge density, degree distribution, etc., the network portrait is a comprehensive (and visually compelling) summary of a graph's topology. Furthermore, the graph portrait provides for a probability $P(k,\ell)$ of randomly choosing $k$ nodes at a distance $\ell$, and therefore provides a probability distribution over all nodes in a graph. The Portrait divergence is therefore defined as the JS divergence of portrait distributions from two graphs~\citep{bagrow2019information}. \begin{figure}[tb!] \centering \input{figures/heatmap} \vspace*{.2cm} \includegraphics[width=.99\linewidth]{figures/figure1-crop.pdf} \vspace*{.2cm} \input{figures/legend_pca} \caption{(Top) PCA weights for the graphlet vectors. (Bottom) 2-D PCA of graphlet vectors on all five datasets (represented by shape) and all 12 graph models (represented by separate plots), showing all 10 iterations (represented by color). The original graphs are plotted in green. Each mark represents the coordinate of a generated graph averaged over all trials. These illustrations show how graphs degenerate comparatively over multiple iterations.} \label{fig:pca} \end{figure} The $\lambda$-distance is similar to Portrait divergence. It is defined as the Euclidean distance between the eigenvalues of two graphs. In the present work, we use the graph Laplacian $\mathcal{L} = D - A$ (\textit{i.e.}, the difference between the degree and adjacency matrices) instead of the adjacency matrix due to its desirable properties (\textit{e.g.}, lower co-spectrality between non-isomorphic graphs)~\citep{wilson2008study}. Results of Portrait divergence and $\lambda$-distance are plotted in Fig.~\ref{fig:deltacon}. Like in Fig.~\ref{fig:degree}, each mark represents the mean over 50 trials on each source graph and model over 10 iterations. Again, confidence intervals are not plotted for clarity but do not exceed $\pm$0.021 in the worst case. Close examination of these results again shows that some models degenerate, and others remain consistent---depending on the source graph and model. Although these plots show that models degenerate, they do not show \textit{how} they change like in Fig.~\ref{fig:kronexample}. \subsection{Tracking Degeneracy: Graphlets} Graph modelers have also found that the number and types of various graphlets significantly contribute to the graph's topology. To that end, Yaverouglu et al. introduced the Graphlet Correlation Distance (GCD) that compares two graphs based on the Spearman correlation of the graphlet orbits of each node~\citep{yaverouglu2014revealing}. Unfortunately, the GCD algorithm requires significant processing resources, so instead, we computed the total graphlet counts for all possible connected 2, 3, and 4-node configurations within each graph using the Parallel Parameterized Graphlet Decomposition (PGD) algorithm~\citep{ahmed2015efficient}, \textit{i.e.}, we counted all the edges, closed-triangles, open-triangles, 3-paths, etc. for each graph. Then we calculate the Relative Graphlets Frequency Distance (RGFD) as the sum of the absolute difference in graphlet counts between two graphs~\citep{prvzulj2004modeling}. This produces a $9$-dimensional vector---one entry for each graphlet. Likewise, the Network Laplacian Spectral Descriptor (NetLSD) summarizes a graph's features into a 250 dimensional vector derived from the solution of a heat equation that resembles the dynamics of a random walker. Each entry in the vector is a discretized sample from the heat equation summed over all nodes as the energy in the system dissipates over the edges in the graph~\citep{tsitsulin2018netlsd}. \begin{figure*}[tb!] \centering \input{figures/lsd} \vspace{.2cm} \input{figures/legend-degree} \caption{Relative Graphlet Frequency divergence (RGFD) (top) and NetLSD Distance (bottom) over 10 fit-and-generate iterations on three real-world datasets and two synthetic datasets. Confidence intervals are not plotted for clarity, but become large as iterations increase.} \label{fig:lsd} \end{figure*} In either case, the description vectors can be reduced with principal component analysis (PCA) and visualized. Fig.~\ref{fig:pca} show the results of PCA on the graphlet vectors with each model separated out. Each mark in the plot for a specific model, therefore, represents the reduced vector, averaged over 50 trials for each iteration. Different datasets are represented with different shapes, while different iterations follow a gradient of blue to red, with blue representing the first iteration. The coordinates of the original datasets are marked in green to serve as a reference. PCA was used instead of t-SNE or other dimension reduction techniques because its reduced vectors are a simple linear combination of weights on the original vector. This provides a somewhat understandable representation for each reduced vector if the original vector also carries semantic meaning. Fortunately, in the case of graphlet vectors, the original vector represented normalized graphlet counts. The top part of Fig.~\ref{fig:pca} shows the weights for each element that, when combined, map each mark to its 2-dimensional point. Interpreting PCA weights is fraught with difficulty, but in this case, the findings are pretty clear: the $x$-axis is highly correlated with the 4-clique and negatively correlated with 4-path and 3-star, while the $y$-axis is highly correlated with 3-star and 4-clique, negatively correlated with $4$-tailed-triangles. Both axes are uncorrelated with the 4-cycle. Representing axes in this way allows the reader to begin to draw conclusions from the plot in Fig.~\ref{fig:pca}. We call-out two interesting findings as examples. First, from the HRG plot, we observe that the markers tend to shift upwards in the $y$-axis with increasing iterations, as evidenced by the change in marker colors from blue to red. This could be due to an increase in the number of $4$-cliques and $3$-stars. Simply put, the HRG model appears to be biased towards generating more cliques. This can be validated by the observation that the \textit{hyperedges} in the HRG model are formed directly from a clique-tree. Second, the graph autoencoder based models (GCNAE and LinearAE) tend to diverge quickly from the input graphs, away from all the models, to occupy a region with high values of $x$. This transition, for some datasets like the Flights network, is gradual, as seen by the trail of "+"s in the GCNAE and LinearAE plots. High $x$ values could be the result of a large number of $4$-cliques and a lack of $4$-paths and $3$-stars, indicating an increase in the density of edges in the generated graphs. These prompted us to examine the topological degeneracy of the graphs from yet another perspective in Sec.~\ref{sec:aplcc}, looking at how average clustering and average shortest path lengths evolve across iterations for different models. There are certainly additional conclusions that may be drawn from the PCA plots, but we leave these for the reader. Semantic analysis of PCA on NetLSD vectors may also be possible, but we do not consider such analysis in the present work. In addition to PCA, we can also compare the $9$- and $250$-dimensional vectors of each generated graph with the respective vectors from the source graph. Indeed, the Euclidean distance comparing these vectors of two graphs is the definition of the Relative Graphlet Frequency Distance (RGFD) and NetLSD distance described in their original work. Because the Euclidean calculations used to compute the RGFD and NetLSD distances are not bounded, it is difficult to compare models across source graphs directly. However, comparisons among models on the same graph are still valid. With that caveat in mind, results of RGFD distance and NetLSD distance are plotted in Fig.~\ref{fig:lsd}. Like earlier plots, each mark represents the mean over 50 trials on each source graph and model, over 10 fit-and-generate iterations. The confidence intervals are not plotted for clarity. However, confidence intervals widen in the RGFD plots and become quite large ($\approx$0.08) in the final iterations. The growth in confidence intervals indicates that some models are not consistent over multiple trials. CNRG produced graphs that were isomorphic to the source graph on the Clique-Ring data resulting in distances of 0, which are not permitted on a log-scale. We instead plotted these results across the bottom of the plots. Like earlier plots, most models tend toward an asymptote near the random graph baseline. We are surprised to find that many models perform worse than the random baseline, even in early generations. \begin{figure}[tb!] \centering \includegraphics[width=.99\linewidth]{figures/figure2-crop.pdf} \vspace*{.5cm} \input{figures/legend_pca} \caption{Variation of average clustering (CC) and average path length (APL) across all five datasets (represented by shape) and all 12 graph models (represented by separate plots), showing all 10 iterations (represented by color). The original graphs are plotted in green. Each mark represents the coordinate of a generated graph averaged over all trials. These illustrations show how graphs degenerate comparatively over multiple iterations.} \label{fig:aplcc} \end{figure} \subsection{Tracking Degeneracy: Clustering and Geodesics} \label{sec:aplcc} A graph's topology is entirely determined by how nodes are spatially positioned in relation to each other. How nodes \emph{cluster} together can have a dramatic impact on how the network is interpreted in a given domain. Similarly, the (unweighted) shortest path lengths, also known as \emph{geodesics}, play an influential role in scenarios both abstract and real-world. In this section, we analyze how graphs' average clustering and average shortest path lengths change as the Infinity Mirror test is applied. Average clustering measures the amount of triadic closure in a graph. Real-world social networks often contain a lot more triangles, and therefore have higher average clustering compared to an Erd\H{o}s-R\'{e}nyi graph having the same number of nodes and edges~\citep{klimek2013triadic}. Similarly, distances between nodes, as measured by the lengths of shortest paths, are indicative of how far apart or close together the nodes in a graph are, with meaningful implications in many applications. Graphs mined from real-world data, such as social and biological networks, often exhibit a low average shortest path length, known as the \emph{small world} property~\citep{watts1998collective}. Synthetic graphs (\textit{e.g.}, trees, cycles), on the other hand, can have much longer geodesics. If a graph model hopes to capture the global nature of interactions in a network, then the average path length is an important property to preserve. Tab.~\ref{tab:dataset} has the average clustering, average shortest path lengths used in the paper. In Fig.~\ref{fig:aplcc}, we have plotted the average clustering (CC) against the average path length (APL) of twelve generative models on five datasets as they experience 10 iterations of the Infinity Mirror test. Points plotted are aggregated means across the 50 independent chains of the Infinity Mirror, with the initial graph $G_0$ for each dataset colored green and subsequent iterations $G_1$ through $G_{10}$ colored in a gradient from dark blue to red. Datasets are distinguished by different shaped markers. Notably, we can see that HRG displays a gradual progression from smaller CCs to larger ones while staying within a relatively stable window of APL values across datasets. Kronecker displays a similarly gradual progression, whereby the APL values consistently and monotonically decrease as the clustering coefficients creep higher over the iterations. This further validates our previous observation that Kronecker tends to create highly dense graphs as the model is iteratively fit. The situation for the autoencoders GCNAE and LinearAE is more cut-and-dry. We can see that, regardless of where the dataset is initially located in CC$\times$APL space, the resulting chains are tightly grouped in the bottom right of the plot, indicating very high clustering and short average distances between nodes. Importantly, this transition occurs suddenly, with only a few of the very early iterations falling outside of that lower-right region. The Erd\H{o}s–R\'{e}nyi random baseline and Chung-Lu display a similarly sudden and consistent grouping of points towards the lower left of the graph, which corresponds with the common knowledge that these random graph models tend to have low clustering and small inter-node distances. CNRG performs markedly well on these metrics. We can see that the points for each dataset stay fairly near their initial starting point for a few iterations before gradually tending to decrease clustering. On all of the datasets, either CC or APL is very well preserved, while the other metric slowly drifts away from the initial values (except on Clique-Ring, for which CNRG generates isomorphic copies). Interestingly, both BUGGE and BTER seem to have qualitatively similar behavior on the same datasets, tending to suddenly shift them to roughly the same regions. SBM displays a tendency to decrease clustering on most datasets, while also startingly decreasing the APL of Clique-Ring in particular. Finally, GraphRNN and NetGAN display peculiar behavior. GraphRNN displays neither the tight, sudden grouping nor the gradual, consistent decay of some of the other models. Instead, the points seem to generally congregate near the bottom of the plot, indicating a consistent decrease in APL but inconsistent behavior in terms of clustering. For some datasets, like Clique-Ring, clustering is significantly diminished for a time before increasing again near the end of the 10 iterations, while for the Tree dataset, clustering seems to be slowly increasing. On the other hand, NetGAN could only be evaluated on the Clique-Ring dataset due to model failure on the others. It significantly decreased both CC and APL on this dataset before marginally raising APL towards the end. \subsection{Tracking Degeneracy: Learned Model Spaces} \begin{figure*}[tb!] \centering \input{figures/model-study.tex} \caption{Model parameters for iterations 1, 5, and 10 fit on the Clique-Ring dataset using Kronecker, SBM, BUGGE, and CNRG. Kronecker initiator matrices tends towards denser graphs. The SBM model tends towards fewer, sparser communities. Higher probabilities are redder, and only the non-zero elements on the block matrices are drawn. We only draw the right-hand side of the two most frequent BUGGE production rules, which show that a $K_5$ is encoded (instead of a $K_4$ from the source graph). CNRG generates graphs that are isomorphic to the source graph where $\bar{C}_{500}$ is a 500 node cycle. Rule frequencies are denoted by $\times$.} \label{fig:models} \end{figure*} Graph metrics like degree and PageRank distribution from Fig.~\ref{fig:degree}, Portrait and $\lambda$-distance from Fig.~\ref{fig:deltacon}, and Graphlet and NetLSD distances from Fig.~\ref{fig:lsd} generally show that models tend to degenerate as they are repeatedly asked to model their generated graph. The result from Fig.~\ref{fig:pca} offers clues to the ways in which they degenerate, but these plots investigate the output of the models, not the model itself. Next, we investigate how the models themselves change in order to gain further insights into the biases encoded into each model. Unfortunately, only a handful of the graph models studied in the present work contain interpretable parameters. For example, the model parameters of neural networks (\textit{i.e.}, GraphRNN, LinearAE, GCNAE, and NetGAN) are well known to be difficult to interpret. The BTER, HRG, and Chung-Lu parameters carry semantic meaning but are still difficult for a human to interpret. Likewise, the Erd\H{o}s-R\'{e}nyi model is just the number of nodes and edges, which do not degenerate over iterations. What remains are the Kronecker, SBM, BUGGE, and CNRG models. We display the interpretable graph model parameters $\Theta$ for iterations 1, 5, and 10 of the Clique-Ring source graph in Fig.~\ref{fig:models}. The Kronecker model shows the initiator matrix, which generates a graph by repeatedly computing the Kronecker product and stochastically drawing an edge in the resulting matrix according to the value in each cell. We find that the entries in the initiator matrix tend towards 0.999 for three of the elements and 0.775 for the remainder. This leads to the generation of increasingly dense graphs, similar to what we observed in Fig.~\ref{fig:kronexample} and Fig.~\ref{fig:aplcc}. The SBM models graph communities directly in a reduced block matrix. New graphs are generated by drawing tight-knit groups according to the probabilities in each block and connecting disparate communities according to their off-diagonal probabilities. We show that, as the iterations increase, the number of detected communities decreases. In addition to that, we observe that the off-diagonal elements are minuscule, leading to the creation of graphs with few and sparsely interconnected components---eventually leading to small disconnected islands. Node replacement graph grammar models of the Clique-Ring produced by BUGGE and CNRG are easily interpretable. These models encode context-free grammars of graph substructures where a node represented on the left-hand-side of a production rule is replaced with the graph on the right-hand-side of the rule. CNRG first encodes the individual 4-cliques into separate nonterminal nodes (bottom rule) and then encodes the 500-node ring into a single starting rule. In this way, CNRG is able to capture the \textit{exact} topology of the graph and is, therefore, able to generate an isomorphic copy over multiple iterations. BUGGE treats all edges as bi-directed, including in the production rules, which show an interesting bias. In the first iteration $\Theta_1$, the top rule encodes cliques of arbitrary size, and the bottom rule encodes a chain of cliques. Because the top rule in the first iteration does not limit either the number or the size of individual cliques, we observe in later iterations that 5-cliques start appearing frequently. These rules still preserve the clique-ring structure, but the size of the individual cliques starts to vary. \section{Conclusions} \label{sec:findings} In summary, this work presents a new methodology for analyzing graph models by repeatedly fitting and generating. This iterative fit-and-generate processes can reveal hidden model biases, facilitating their critical examination. For example, we find that graph autoencoders and convolutional neural networks quickly densify to almost complete graphs in the limit. Conversely, NetGAN and GraphRNN models sparsify and shrink a graph in the limit and degenerate quickly. Interestingly, the graphs produced by the Kronecker and HRG models do not monotonically degenerate; sometimes, their performance improves after multiple generations. It is unclear why this might be; further research is needed to indicate when and why this improvement occurs. The parameters of CNRG, BUGGE, and SBMs can be more closely inspected to further reveal biases that are encoded into each of these models. Finally, it is our hope that these findings will be used to more deeply understand the statistical biases that are encoded into graph models and aide in the future development of more robust graph models. \section*{Acknowledgements} This work is supported by grants from the US National Science Foundation (\#1652492), DARPA (FA8750-20-2-1004), and the US Army Research Office (W911NF-17-1-0448).
{'timestamp': '2020-09-21T02:17:25', 'yymm': '2009', 'arxiv_id': '2009.08925', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08925'}
arxiv
\section{Introduction} \noindent Scene appearance is directly dependent on the light source properties, such as the spectral composition of emitted light, and the position and direction of the light source, whose interaction with the scene objects provoke shaded surfaces or dark cast shadows that become essential visual cues to understand image content. Esti\-ma\-ting the properties of the light conditions from a single image is an initial step to improve subsequent computer vision algorithms for image understanding. In this paper we perform a preliminary study to estimate color and position of light in a simple and unified approach, that is based on the shading properties of the image where we assume a single scene illuminant. Estimating the color of the light from a single image has been focus of attention in previous research. Computational color constancy (CC) has been studied in a large number of works \cite{FOSTER2011Color,Finlayson2006, gijsenij2011computational} where the problem was tackled from different points of views \cite{gijsenij2011computational}. A first approach was to extract statistics from RGB image values under different assumptions to estimate the canonical white. A second approach was to introduce spatio-statistical information like gradients or frequency content of the image. One last group of CC algorithms was to try to get the information from physical cues of the image (highlights, shadows, inter-reflections, etc). In the last years, new approaches have been based on deep learning frameworks where the solution is driven by the data with physical constrains in the loss functions. An updated comprehensive compendium and comparison of CC algorithm performances can be found in \cite{cheng2014illuminant,Lou2015DeepColor,das2018color,Yan2018MultipleIE}. In this work we propose one more approach based on a deep architecture, but color of the light source is jointly estimated with the light direction. Estimating the direction of the light has also been tackled from different areas like, computer graphics, computer vision or augmented reality. Single image light direction estimation can be divided in two different kinds of approaches. First, those in which light probes with known reflectance and geometric properties are used. A Specular sphere is commonly used to represent light position in different computer graphics applications \cite{Debevec1998RenderingSO,Agusanto2003PhotorealisticRF,Schnieders2011LightSE}. But, random shaped objects to detect light position were used by Mandl et-al in \cite{Mandl2017LearningLF}, jointly with a deep learning approach to get the light position with each of these random shaped object. Second, we find those works in which no probe is used, and where multiple image cues such as shading, shape and cast shadows are the basis to estimate light direction. Some examples of these works can be found in computer vision literature \cite{Lalonde2009EstimatingNI,samaras2003incorporating,Panagopoulos2011IlluminationEA,panagopoulos2009robust,arief2012realtime}. More recently, some deep learning methods have been proposed to estimate scene illumination and have been used for different computer graphics tasks. Gardner et al.\cite{gardner2017learning} introduced a method to convert low dynamic range (LDR) indoor images to high dynamic range (HDR) images, first they used a deep network to localize the light source in LDR image environmental map and then they used another network with these annoted LDR images to convert them to HDR image. Following a similar approach, Geoffroy et al. \cite{hold2017deep} introduced a method to convert outdoor LDR images to HDR images. They trained their network with a set of panorama images and predicted HDR environmental maps with sky and sun positions. Later on, Geoffroy et al \cite{gardner2019deep} extended their previous idea for indoor lighting but replaced the environmental maps with light geometric and photometric properties. Sun et al. \cite{Sun2019SingleIP} introduced an encoder-decoder based network to relight a single portrait image, the encoder predicts the input image environmental map and an embedding for the scene information, while the decoder builds a new version of the image scene with the target environmental map and obtains a relighted portrait. Very recently, Muramann et al. \cite{murmann2019dataset} have introduced the \textit{Multi-illuminant dataset} of $1000$ scenes each one acquired under $25$ different light position conditions, and they used a deep network to predict a right sided illuminated image from its corresponding left sided illuminated image. In this work we will test our proposal on this new wild dataset after providing a procedure to compute the light direction from each sample. To sum up, we can state that a large range of works have tackled the problem of estimating color and direction of the scene light source from different points of views and focusing on specific applications. In this work we propose an easy end-to-end approach to jointly characterize the light source of a scene, both for color and direction. We pursuit to measure the level of accuracy we can achieve, in order it can be applied to a wide range of images, without using probes in the scene and becoming a robust preliminary stage to be subsequently combined with any task. To this end, the paper is organized as follows: first we introduce a new synthetic dataset, secondly we use it to train a deep architecture that estimates light properties from a single image, finally we show how our proposal performs on three different scenarios, synthetic, real indoor and natural images. \section{A synthetic dataset}\label{sec:dataset} \noindent In order to train our end-to-end network that estimates light conditions we developed a new image dataset similar to SID \cite{sial2020deep}, which was created for intrinsic image decomposition. This dataset is formed by a large set of images of surreal scenes where Shapenet objects \cite{shapenet} are enclosed in the center of multi-sided rooms with highly diverse backgrounds provided by flat textures on the room walls, resulting in a large range of different light effects. From now one we will refer to this dataset as SID1, and we will propose a new one better adapted to our problem, using the same methodology and software provided by the authors, which is based on an open source Blender rendering engine to synthesize images. Our new dataset will be called SID2 dataset. The main difference is that it introduces more than one object in each scene, with the aim of increasing the number of strong light effects and interactions. Additionally, we also introduce more variability in the distance from the light source to the scene center. The dataset is formed by $45,000$ synthetic images with the corresponding ground truth data: direction and color of the light source. \begin{figure} \begin{tabular}{c} \includegraphics[width=0.45\textwidth]{images/generation_setup.png} \\ \end{tabular} \caption{Image Generation Setup. Camera and light positions are given in spherical coordinates $(r, \vartheta,\varphi)$.} \label{Figure:generation_setup} \end{figure} We did several assumptions in building the dataset: (a) objects are randomly positioned around the scene center but always close to the room ground floor to have realistic cast shadows; (b) light source direction goes from scene center to a point onto an imaginary semi-sphere of a random radius and with random RGB color; (c) camera is randomly positioned at a random distance from the center of the scene and always with the focal axis pointing to the scene center. In Figure \ref{Figure:generation_setup} we show the diagram of the synthetic world we defined for the generation of SID2. More specifically, we took $45,000$ 3D objects from Shapenet dataset \cite{shapenet}. Likewise in \cite{sial2020deep} we did not use textured surfaces, we used a diffuse bidirectional scattering distribution function (BSDF) with random color and roughness values for each mesh texture in each object. This roughness parameter controls how much light is reflected back from each object surface. We randomly picked from $1$ to $3$ objects in each image. They were placed at random locations within the camera view range. We placed an empty object in the center of the scene to ensure non-overlapping between the rest of objects. Light direction was randomly defined in spherical coordinates $(r_l,\vartheta_l,\varphi_l)$, being radius, pan and tilt, respectively. We took random values within the ranges of $[20m,50m]$ $[30^{\circ},90^{\circ}]$ and $[0^{\circ},360^{\circ}]$ respectively, in steps of $1^{\circ}$ for pan and $5^{\circ}$ for tilt. Light intensity and chromaticity was randomly selected, but chromaticity was constrained to be around the Planckian locus to simulate natural lighting conditions. Camera position is also denoted in spherical coordinates as $(r_c,\vartheta_c,\varphi_c)$, where $r_c$ was fixed at $20m$ and pan, $\vartheta_c=0^{\circ}$, the tilt range randomly varied within $[10^{\circ},70^{\circ}]$. In the final ground-truth (GT), light pan and tilt are provided with reference to the camera position, in order not to depend on real world positions which are usually not available in real images. Backgrounds were generated in the same way as in \cite{sial2020deep}. \begin{comment} \begin{equation} Pan = \vartheta_c -\vartheta_l \\ Tilt = \theta_c - \theta_l \end{equation} \textcolor{magenta}{HASSAN, IT IS BETTER YOU DO THE GENERATION SETUP, HERE YOU HAVE THE SETUP FOR JOSA.} JOSA content from here ...... \textcolor{blue}{To generate this dataset, we used $20,000$ shapenet\cite{shapenet} objects, each object was captured $3$ times by changing light source pan position. As contrast to previous work, the camera is fixed at $15m$ width and $10m$ height and tilted at an angle of $50$\degree. This camera position simulate natural human eye position to see any ground object. Most of camera natural scenes are generally taken at this position. In this settings, light source is position randomly around the object in semi sphere at radius of $20m$. Light source can take two random angles i.e. pan and tilt, pan angle is selected from range of $[0\degree,360\degree]$ at step size of 1\degree and tilt angle is selected from $[30\degree,80\degree]$ at step size of $5$\degree. Light source can also take random intensity values as well. Background objects were selected from $4$ to $6$ sided rooms and these background can rotate randomly around their center in $z$ axis. Each object in shapenet have different height and we made sure that object bottom touches the floor of our indoor environment. In this way we made sure that object shadows touches the objects and are always visible at different light positions. } \textcolor{magenta}{\textbf{Generation setup:} Each object was captured twice, by using two camera positions separated by $180$ degrees in the horizontal pan axis. The camera were randomly positioned around the object over a semi-spherical surface. In this way, we can get two different views of the same object. To set the scene lighting we put $4$ white light sources with fixed location and orientation, we just randomly changed the intensity, that is what most affects the intrinsic shading. Two of the light sources having lower intensity range while higher for the two other to create more shading effects.} \end{comment} \section{Our deep architecture} \noindent We propose an inception-based encoder-decoder architecture to predict light parameters. In Figure \ref{fig:deep architecture} we give an scheme, where we can see that our encoder has five modules combining 3 types of layers: inception, convolution and pooling. The encoder input is the image that is transformed to a higher dimensional feature space, from which three decoders convert this embedding to a common feature space of pan, tilt and color of light source. Pan and tilt output predictions are given as functions of angle differences. We use the functions $\sin(\vartheta_c -\vartheta_l)$ and $\cos(\vartheta_c -\vartheta_l)$ to bound the pan output. Similarly, tilt prediction is represented as difference of angles $\sin(\varphi_c - \varphi_l)$ and $\cos(\varphi_c - \varphi_l)$. Finally color is predicted here as R, G and B values. We used the split inception module from \cite{szegedy2016rethinking}, which replaces $n \times n$ convolution filters with $1 \times n$ and $n \times 1$ filter, to achieve faster convergence with overall less parameter. Our global loss function to estimate illumination parameters is based on three terms: \begin{equation} Loss(x,\hat{y}) = \alpha_1 L_{Pan}(x,\hat{y}) + \alpha_2 L_{Tilt}(x,\hat{y}) + \alpha_3 L_{Color}(x,\hat{y}) \end{equation} where $x$ is the input image, $\hat{y}$ is a 7 dimensional vector giving the estimation of the scene light properties represented by $x$, $\alpha_i$ are the weights for the different loss terms defined for pan, tilt and color, and which are respectively given by: \begin{equation} \begin{array}{llll} L_{Pan}(x,\hat{y}) = MSE((\hat{y}_1 - \sin(\vartheta_c^x -\vartheta_l^x)) + (\hat{y}_2 - \cos(\vartheta_c^x -\vartheta_l^x))) & \\ L_{Tilt}(x,\hat{y}) = MSE\{(\hat{y}_3 - \sin(\varphi_c^x -\varphi_l^x)) + (\hat{y}_4 - \cos(\varphi_c^x -\varphi_l^x)\} & \\ L_{Color}(x,\hat{y}) = \arccos((\hat{y}_5 \cdot x_{RGB}) / \|\hat{y}_5\| * \|(x_{RGB}\|) \end{array}\nonumber \end{equation} $L_{Pan}$ and $L_{Tilt}$ are computed as the mean square error ($MSE$) between the estimations for pan, $\hat{y}_1$ and $\hat{y}_2$, and for tilt, $\hat{y}_3$ and $\hat{y}_4$, and a function of the difference between the camera and light positions for the ground-truth of $x$. The third loss term, $L_{Color}$, is the mean angular error between the estimated RGB values, $\hat{y}_5$, and the color of the light for $x$ image provided in the ground-truth. This network has been trained using Adam optimizer \cite{AdamKingmaB14}, with initial learning rate $0.0002$ which is decreased with factor of $0.1$ on reaching plateau. Weights are initialized using He Normal\cite{He2016DeepRL}. All experiments in next sections were trained using a batch size of $16$. In the following sections we show the results of several experiments to evaluate the architecture performance on different datasets and conditions. \begin{figure} \centering \includegraphics[width=0.48\textwidth]{images/Network2b.png} \caption{Deep Architecture. Inception module from \cite{szegedy2016rethinking}} \label{fig:deep architecture} \end{figure} \section{Experiment 1: Synthetic dataset} \noindent In this first experiment we trained and tested the proposed architecture on two different datasets: SID1 (single object) and SID2 (multiple objects). The results are shown in Table \ref{tab:Exp_SID}, where we separately compute different angular errors. Direction error is given separately in the pan and tilt components, and the global angular error for direction estimation. We can see that all the estimations are improved when the network is trained on a more complex dataset, like SID2, where multiple objects light interactions provide richer shading cues. However, there is slight improvement for color estimation, performance is similar for both datasets. In Figure \ref{Figure:SID_examples} we show qualitative results on SID2 dataset. Images are ordered from smaller (left) to larger (right) direction estimation error. \begin{table}[h!] \tiny \centering \resizebox{\columnwidth}{!}{\begin{tabular}{|c|c|c|c|c|} \hline Dataset & Pan & Tilt & Direction & Color \\ \hline \hline SID1 & $14.63$ & $9.86$ & $16.98$ & $1.05$\\ \hline SID2 & $10.46$ & $9.21$ & $14.22$ & $1.02$ \\ \hline \end{tabular}} \caption{\textit{Table 1.} Estimation Errors (in degrees) for light source direction and color with the proposed architecture trained on SID1 and SID2.} \label{tab:Exp_SID} \vspace{4mm} \end{table} Intuitively as the light becomes more zenithal, the shadows shorten and cast shadows present more uncertainty to estimate light direction. We analysed the performance of the method at different tilt locations of the light source in the input image, from the ground (level 1: $[30^\circ$, $50^\circ]$) up to the zenithal area (level 3: $[70^\circ$, $90^\circ]$). This effect is confirmed in Table \ref{tab:my_label2}, where estimated errors in direction clearly increase from level 1 to level 3. \begin{table}[!h] \tiny \centering \resizebox{\columnwidth}{!}{\begin{tabular}{|c|c|c|c|c|} \hline Tilt range & Pan & Tilt & Direction & Color \\ \hline \hline Level 1 & $4.92$ & $5.14$ & $7.57$ & $1.04$\\ \hline Level 2 & $8.51$ & $5.14$ & $11.97$ & $0.90$ \\ \hline Level 3 & $22.36$ & $18.33$ & $28.33$ & $1.00$\\ \hline \end{tabular}} \caption{\textit{Table 2.} Estimation Errors (in degrees) for light direction and color at different tilt levels.} \label{tab:my_label2} \vspace{4mm} \end{table} Similarly, we analysed the performance at different pan levels, each level covers $90\degree$ of pan area. Level 1 is when light comes from center front, level 2 from right, level 3 from back and level 4 is when light comes from left side. Tilt angle was kept between $30\degree$ and $70\degree$ to analyze pan error while minimizing zenithal tilt error effects. Table \ref{tab:my_label3} shows results for this experiment, both direction and color error are consistent in all levels of pan. \begin{table}[!h] \centering \tiny \resizebox{\columnwidth}{!}{\begin{tabular}{|c|c|c|c|c|} \hline Pan range & Pan & Tilt & Direction & Color \\ \hline \hline Level1 & $6.87$ & $5.10$ & $9.10$ & $0.98$\\ \hline Level2 & $6.24$ & $5.12$ & $8.80$ & $0.96$ \\ \hline Level3 & $6.35$ & $5.09$ & $9.46$ & $1.03$\\ \hline Level4 & $6.01$ & $5.16$ & $9.03$ & $0.97$\\ \hline \end{tabular}} \caption{\textit{Table 3.} Estimation Errors (in degrees) for light direction and color at different pan levels.} \label{tab:my_label3} \vspace{0.4cm} \end{table} \section{Experiment 2. Multi-illumination dataset} \noindent Once we have evaluated our method in synthetic images, we want to analyze whether it generalises for real images. We have tested our method on the \textit{Multi-illuminant dataset} (MID) \cite{murmann2019dataset}, that contains $1000$ different indoor scenes, all of them containing a diffuse and a specular sphere at random locations. Light source is mounted above the camera and can be rotated at different predefined pan and tilt angles, creating different light conditions. The dataset provides the orientation of the light source for each acquired image, but since the light can bounce off the walls, the direction of the incident light on the scene is not defined by the light source angles and it needs to be recomputed. We have defined a procedure to compute the incident light direction from the specular sphere present in all the scenes, whose highlights provide enough information to collect our GT data (tilt and pan angle between light and camera). The color of the light is obtained from the average color of the diffuse sphere. To obtain the light direction we used the ideas proposed by \cite{Schnieders2011LightSE} where they assume that the angle of incident light is equal to the angle of outgoing light at the specular highlight on a spherical ball. We use a reference image in each scene where light and camera both are pointed in the same direction towards the center of the scene. We also assumed that the light is mounted at $10\degree$ height with respect to scene center. The angles obtained from this reference images allow to correct the angle displacement due to the sphere position shifting inside the image on the rest of scene images. \begin{table}[!h] \centering \small \resizebox{\columnwidth}{!}{\begin{tabular}{|l|c|c|c|c|} \hline Dataset (Error) & Pan & Tilt & Direction & Color \\ \hline \hline Masked MID (Mean) & $21.38$ & $10.14$ & $22.72$ & $0.63$ \\ Masked MID (Median) & $13.74$ & $7.64$ & $17.80$ & $0.40$ \\ \hline UnMasked MID (Mean) & $14.28$ & $6.96$ & $15.44$ & $0.36$ \\ UnMasked MID (Median) & $8.20$ & $4.83$ & $10.83$ & $0.24$ \\ \hline \end{tabular}} \caption{\textit{Table 4.} Estimation errors in degrees on two versions of MID dataset (with Masked or UnMasked spheres).} \label{tab:wild1} \vspace{0.4cm} \end{table} Starting from the network trained on SID2 it was fine tuned on this dataset under two different conditions: a) keeping the reference spheres in the image, and b) masking them. Although specular spheres are not present in real images, the first configuration should provide an upper bound of our method performance on wild images. Table \ref{tab:wild1} shows the results on this experiment. As expected, network performance is much higher when complete images are used as inputs. We can also observe that results on color estimation are better than on SID2, mainly due to the stability of single white light source in the dataset. To analyze the results removing the influence of the outliers, we also reported median error on this dataset. Results are as good as the ones obtained only using synthetic images on the upper bound. Qualitative results are provided in Figure \ref{Figure:wild_examples}. Top row depicts the original image, second row are the spheres generated from the GT information, and the third row shows the synthetic spheres generated with the obtained prediction. Finally, we perform a last experiment on this dataset by dividing the test set in two: (a) images with incident light from the front, and (b) from the back. Table \ref{tab:wild2} also shows the errors computed for these two sets. Both color and direction errors are higher when the light comes from the back of the scene and a big area of the image becomes saturated. We want to note here that the GT we created present a low accuracy for the subset of images with back light sources.This is due to the inherent uncertainty derived from what can be inferred from spheres illuminated from the back. Therefore, this MID dataset division is highly recommended to analyse results derived from this GT. \begin{table}[!h] \centering \tiny \resizebox{\columnwidth}{!}{\begin{tabular}{|c|c|c|c|c|} \hline Light position & Pan & Tilt & Direction & Color\\ \hline \hline Front & $11.51$ & $6.33$ & $13.09$ & $0.34$ \\ \hline Back & $32.90$ & $11.21$ & $31.23$ & $0.52$ \\ \hline \end{tabular}} \caption{\textit{Table 5.} Estimation errors in degrees dividing MID dataset in front and back light.} \label{tab:wild2} \vspace{0.4cm} \end{table} \renewcommand{\arraystretch}{1.5} \newcommand\sizephotosyn{0.15} \begin{figure*}[h!] \begin{center} \setlength{\tabcolsep}{1pt} \begin{tabular}{rcccccc} \raisebox{1.2cm}{(a)} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/gt/im1.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/gt/im2.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/gt/im3.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/gt/im8.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/gt/im4.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/gt/im5.png} \\[-0.1cm] \raisebox{1.2cm}{(b)} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/pdcn/im1.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/pdcn/im2.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/pdcn/im3.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/pdcn/im8.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/pdcn/im4.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/pdcn/im5.png} \\[-0.1cm] \raisebox{1.2cm}{(c)}& \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/diff/im1.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/diff/im2.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/diff/im3.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/diff/im8.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/diff/im4.png} & \includegraphics[width=\sizephotosyn\textwidth]{images/Synthetic/diff/im5.png} \\[-0.1cm] \hline\hline $Direction$ & $0.57$ & 1.58 & $4.3$ & $8.55$ & $8.81$ & $30.0$ \\[-0.2cm] $Color$ & $1.27$ & $0.78$ & $1.64$ & $1.8$ & $0.22$ & $0.24$ \\ \hline \end{tabular} \end{center} \caption{Direction and Color estimation examples on SID2 dataset: (a) Original images, (b) Generated images with estimated light properties, (c) RGB Image subtraction between (a) and (b). Bottom rows are the corresponding computed errors for direction and color in degrees, ordered from smaller (left) to larger (right) direction estimation error.} \label{Figure:SID_examples} \end{figure*} \newcommand\sizephoto{0.225} \begin{figure*}[h!] \begin{center} \setlength{\tabcolsep}{1pt} \begin{tabular}{rcccc} \raisebox{1.0cm}{(a)} & \includegraphics[width=\sizephoto\textwidth]{images/real/data/im1.jpg} & \includegraphics[width=\sizephoto\textwidth]{images/real/data/im2.jpg} & \includegraphics[width=\sizephoto\textwidth]{images/real/data/im3.jpg} & \includegraphics[width=\sizephoto\textwidth]{images/real/data/im4.jpg}\\[-0.1cm] \raisebox{0.3cm}{(b)} & \includegraphics[width=\sizephoto\textwidth]{images/real/gt/im1.png} & \includegraphics[width=\sizephoto\textwidth]{images/real/gt/im2.png} & \includegraphics[width=\sizephoto\textwidth]{images/real/gt/im3.png} & \includegraphics[width=\sizephoto\textwidth]{images/real/gt/im4.png}\\[-0.1cm] \raisebox{0.3cm}{(c)}& \includegraphics[width=\sizephoto\textwidth]{images/real/pdcn/im1.png} & \includegraphics[width=\sizephoto\textwidth]{images/real/pdcn/im2.png} & \includegraphics[width=\sizephoto\textwidth]{images/real/pdcn/im3.png} & \includegraphics[width=\sizephoto\textwidth]{images/real/pdcn/im4.png}\\ [-0.1cm]\hline\hline $Direction$ & $3.16$ & $5.60$ & $20.12$ & $25.05$ \\[-0.2cm] $Color$ & $0.16$ & $0.21$ & $1.30$ & $0.35$ \\ \hline \end{tabular} \end{center} \caption{Direction and Color estimation examples on Multi-illumination dataset: (a) Original images, (b) Ground-truth plotted on corresponding spheres, (c) Estimations provided by our proposed architecture. Bottom rows are computed errors for direction and color in degrees.} \label{Figure:wild_examples} \end{figure*} \section{Experiment 3. Natural images} \noindent Previous experiments show the performance of our method on synthetic and real indoor images. Here, we show a few qualitative results on real outdoor images. In Figure \ref{Figure:real_examples} we show some examples with strong outdoor cast shadows, in order to visually evaluate the prediction we depict a synthetic pole at the left top corner. In these examples camera is assumed to be at $45\degree$ tilt from ground. Left side four images are from SBU shadow dataset \cite{vicente2016large} and the two on the right have been captured with a mobile device. \newcommand\sizephotosynb{0.16} \begin{figure*}[h!] \begin{center} \setlength{\tabcolsep}{1pt} \begin{tabular}{cccccc} \includegraphics[width=\sizephotosynb\textwidth]{images/real_result1.png} & \includegraphics[width=\sizephotosynb\textwidth]{images/real_result2.png} & \includegraphics[width=\sizephotosynb\textwidth]{images/real_result3.png} & \includegraphics[width=\sizephotosynb\textwidth]{images/real_result4.png} & \includegraphics[width=\sizephotosynb\textwidth]{images/real_result5.png} & \includegraphics[width=\sizephotosynb\textwidth]{images/real_result6.png} \\[-0.1cm] \end{tabular} \end{center} \caption{Examples of light direction estimation on natural images. Predicted direction is plotted top left in each image.} \label{Figure:real_examples} \end{figure*} \begin{comment} \begin{figure} \includegraphics[width=0.47\textwidth]{images/real_result.png} \\ \caption{Examples of light direction estimation on natural images. Predicted direction is plotted top left in each image.} \label{Figure:real_examples} \end{figure} \end{comment} \section{Conclusions} In this work we have proved the plausibility of using a simple deep architecture to estimate physical light properties of a scene from a single image. The proposed approach is based on training a deep regression architecture on a large synthetic and diversified dataset. We show that the obtained regressor can generalize to real images and can be used as a preliminary step for further complex tasks. \begin{comment} The process involved a first analysis on a problem specific synthetic dataset. We used an existing general framework that allows to generate synthetic image datasets for specifics purposes. The output is a 45K image with light properties. The evaluation on real images was conducted on an adapted multi-illuminant existing dataset. We defined a procedure to extract the real light properties starting form a physical configuration of a single light source. Finally we evaluate the approach on images complety different from those used in the training phases. Although the experiment is limited, the results shows the validity of the proposal. \end{comment} \begin{comment} \section*{Acknowledgments} This work has been supported project TIN2014-61068-R and FPI Predoctoral Grant (BES-2015-073722), project RTI2018-095645-B-C21 of Spanish Ministry of Economy and Competitiveness and the CERCA Programme / Generalitat de Catalunya. \end{comment} \bibliographystyle{plain} \small
{'timestamp': '2020-09-21T02:17:53', 'yymm': '2009', 'arxiv_id': '2009.08941', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08941'}
arxiv
\section{Introduction} \label{sec:intro} \subsection{Scientific Background} The integration of mobile health (mHealth) devices into behavioral health research has fundamentally changed the way researchers and interventionalists are able to collect data as well as deploy and evaluate intervention strategies. Leveraging mobile and sensing technologies, just-in-time adaptive interventions (JITAI) or ecological momentary interventions are designed to provide tailored support to participants based on their mood, affect, and socio-environmental context \citep{heron2010ecological, nahum2017just}. In order to deliver theory-based interventions at critical moments, researchers collect intensive longitudinal data using ecological momentary assessment (EMA) methods, which aim to capture psychological, emotional, and environmental factors that may relate to a behavioral outcome in near real-time. In practice, JITAIs' effectiveness depends on accurately identifying high-risk situations by the user or by pre-determined decision rules to initiate the delivery of intervention components. Decision rules for efficacious interventions rely on a thorough understanding of the factors that characterize a subject's risk for a behavioral outcome, the dynamics of these risk factors' relation with the outcome over time, and the knowledge of possible strategies to target a risk factor \citep{nahum2017just}. In the analysis of this paper, we investigate a behavioral health intervention study that targets smoking cessation. Historically, smoking cessation studies have used health behavior theory \citep{shiffman2002immediate,timms2013dynamical} or group-level trends of smoking antecedents \citep{piasecki2013smoking} to determine when a JITAI should be triggered. However, this approach is limited since current health behavior models are inadequate for guiding the dynamic and granular nature of JITAIs \citep{riley2011health,klasnja2015microrandomized}. Additionally, the design of efficacious smoking cessation interventions is challenged by the complexity of smoking behaviors around a quit attempt and misunderstandings of the addiction process \citep{piasecki2002have}. More recently, smoking behavior researchers have capitalized on the ability of mHealth techniques to collect rich streams of data capturing subjects' experiences close to their occurrence at a high temporal resolution. The structure, as well as the complexity, of these data provide unique opportunities for the development and implementation of more advanced analytical methods compared to traditional longitudinal data analysis methods used in behavioral research (e.g., mixed models, growth curve models) \citep{trail2014functional}. For example, researchers have applied reinforcement learning \citep{luckett2019estimating} and dynamic systems approaches \citep{trail2014functional,rivera2007using, timms2013dynamical} to design and assess optimal treatment strategies using mHealth data. Additionally, \cite{koslovsky2018bayesian}, \cite{de2017use} and \cite{berardi2018markov} have applied hidden and observed Markov models to study transitions between discrete behavioral states, \cite{shiyko2012using} and \cite{dziak2015modeling} have used mixture models to identify latent structures, and \cite{kurum2016time} have employed joint modeling techniques to study the complexity of smoking behaviors. Greater insights into the dynamic relation between risk factors and smoking behaviors have been generated by the application of functional data techniques \citep{ trail2014functional,vasilenko2014time,koslovsky2017time, tan2012time}. These methods are well-suited for high-dimensional data with unbalanced and unequally-spaced observation times, matching the format of data collected with EMAs. They also require little assumptions on the structure of the relations between risk factors and behavioral outcomes. One popular approach uses varying-coefficient models, which belong to the class of generalized additive (mixed) models. These semiparametric regression models allow a covariate's corresponding coefficient to vary as a smooth function of other covariates \citep{hastie1993varying}. For example, \cite{selya2015nicotine} examined how the relation between the number of cigarettes smoked during a smoking event and smoking-related mood changes varies as a function of nicotine dependence. More frequently, penalized splines have been employed in varying-coefficient models to investigate how the effect of a covariate varies as a function of time, leading to time-varying effect models (TVEM) \citep{tan2012time,lanza2013advancing,koslovsky2017time, shiyko2012using, mason2015time,vasilenko2014time}. These approaches allow researchers to identify the critical moments that a particular risk factor is strongly associated with smoking behaviors, information that can be used to design tailored intervention strategies based on a subject's current risk profile. \subsection{Model Overview} While there are various inferential challenges that functional data analysis models can address, in the application of this paper we focus on incorporating three recurring themes in behavioral research to explore the relations between risk factors and smoking behaviors: \begin{enumerate} \item \textit{Model Assumptions} - Numerous smoking behavior research studies have relied on semiparametric, spline-based methods to learn the relational structure between risk factors and outcomes \citep{tan2012time,vasilenko2014time}. \item \textit{Variable Selection} - One of the main objectives of intensive longitudinal data analysis is to identify or re-affirm complex relations between risk factors and behavioral outcomes over time \citep{walls2005models}. \item \textit{Latency} - A common aim in smoking behavior research studies is to identify latent structure in the data, such as groups or clusters of subjects with similar smoking behaviors over time \citep{mccarthy2016repeated, cursio2019latent, geiser2013analyzing, dziak2015modeling, brook2008developmental}. \end{enumerate} To incorporate and expand upon these features in our analysis, we develop a flexible Bayesian varying-coefficient regression modeling framework for longitudinal binary responses that uses variable selection priors to provide insights into the dynamic relations between risk factors and outcomes. We embed spike-and-slab variable selection priors as mixtures of a point mass at zero (spike) and a diffuse distribution (slab) \citep{george1993variable,brown1998multivariate} and adopt the formulation of \cite{scheipl2012spike} to deconstruct the varying-coefficients terms, in our case time-varying effects, into a main effect, linear interaction term, and non-linear interaction term. Unlike previous approaches in behavioral health research that use time-varying effect models, our formulation allows us to gain inference on whether a given risk factor is related to the smoking behavior while also learning the type of relation. Additionally, by performing selection on fixed as well as random effects, our method is equipped to identify relations that vary over time and across subjects. For this, we exploit a P\'olya-Gamma augmentation scheme that enables efficient sampling without sacrificing interpretability of the regression coefficients as log odds ratios \citep{polson2013bayesian}. Furthermore, we adopt a Bayesian semiparametric approach to model fixed and random effects by replacing the traditional spike-and-slab prior with a nonparametric construction to cluster risk factors that have similar strengths of association. \subsection{ Just-in-Time Adaptive Interventions for Smoking Abstinence} Although multiple studies have examined momentary predictors of smoking lapse \citep{shiffman2000dynamic,piasecki2003smoking,businelle2014predicting}, JITAIs for smoking cessation are still nascent. Thus far, studies have used participant-labeled GPS coordinates to trigger supportive messages to prevent smoking \citep{naughton2016context}, or have tailored messages to the duration and intensity of participant's self-reported side effects while taking varenicline \citep{mcclure2016evaluating}. Using our proposed approach, we analyze ILD collected in a study investigating the utility of a novel, smartphone-based smoking cessation JITAI (\textit{SmartT}). The \textit{SmartT} intervention \citep{businelle2016ecological} uses a lapse risk estimator to identify moments of heightened risk for lapse, and tailors treatment messages in real-time based upon the level of imminent smoking lapse risk and currently present lapse triggers. To our knowledge, no other studies have used EMA data to estimate risk for imminent smoking lapse and deliver situation-specific, individually-tailored treatment content prior to lapse. In this study, adult smokers (N=81) recruited from a smoking cessation research clinic were randomized to the \textit{SmartT} intervention, the National Cancer Institute's QuitGuide (\textit{NCI QuitGuide}), or weekly counseling sessions (\textit{usual care}), and followed over a five-week period spanning one week prior to a scheduled quit attempt to four weeks after. At the beginning of the assessment period, baseline measures were collected, and subjects were shown how to complete EMAs on a study-provided smartphone. Throughout the assessment period, subjects completed daily diaries and received four random EMAs from the smartphone to complete each day. For each EMA, subjects were prompted on their recent smoking behaviors, alcohol consumption, as well as various questions regarding their current psychological, social, and environmental factors that may contribute to an increased risk of smoking behaviors. Findings indicate that our approach is well-positioned to help researchers evaluate, design, and deliver tailored intervention strategies in the critical moments surrounding a quit attempt. In particular, results confirm previously identified temporal relations between smoking behaviors around a quit attempt and risk factors. They also indicate that subjects differ in how they respond to different risk factors over time. Furthermore, we identify clusters of active risk factors that can help researchers prioritize intervention strategies based on their relative strength of association at a given moment. Importantly, our approach generates these insights with minimal assumptions regarding which risk factors were related to smoking in the presence of others, the structural form of the relation for active terms, or the parametric form of regression coefficients. The rest of the paper is organized as follows. In section \ref{sec:methods}, we present our modeling approach and describe prior constructions. In section \ref{sec:case}, we investigate the relations between risk factors and smoking behaviors in the critical moments surrounding a scheduled quit attempt using mHealth data. In section \ref{sec:simul}, we conduct a simulation study investigating the variable selection and clustering performance of our proposed method on simulated data. In section \ref{sec:sens}, we evaluate prior sensitivity of our model. In section \ref{sec:remarks}, we provide concluding remarks. \section{Methods} \label{sec:methods} The objective of our analysis is to identify relations between a set of risk factors (i.e., baseline and EMA items) and a binary outcome (i.e., momentary smoking) repeatedly collected over time. For this, we employ a Bayesian variable selection framework that allows a flexible structure for the unknown relations. We achieve this by performing selection not only on main effects, but additionally on linear and non-linear interaction terms as well as random effects. In this work, we refer to fixed and random effects in the context of hierarchical or multilevel models, where fixed effects are constant across subjects and random effects differ at the subject-level. We chose this terminology based on its familiarity within both frequentist and Bayesian paradigms, but point out that the fixed or population-level effects are treated as random variables in our model, and thus follow a probability distribution. \subsection{A Varying-Coefficient Model for Intensive Longitudinal Data Collected with EMAs} Let $y_{ij} \in \{0,1\}$ represent momentary smoking for subject $i = 1,\dots, N$, and $ \boldsymbol{x}_{ij}$ and $\boldsymbol{z}_{ij} $ represent $P$- and $D$-dimensional vectors of risk factors collected on each subject at time $j = 1,\dots, n_i$, respectively. To maintain temporality in our particular application (see section \ref{sec:case} for more details), we model the relation between momentary smoking by the next assessment and current, potential risk factors as a varying-coefficient model of the type \begin{equation}\label{VICM} logit(P(y_{i,j+1} = 1|\boldsymbol{x}_{ij},\boldsymbol{z}_{ij},u_{ij})) = \sum_{p=1}^{P}f_p(u_{ij}) x_{ijp} + \boldsymbol{\alpha}^{\prime}_i\boldsymbol{z}_{ij}, \end{equation} where $f_p(u)$ are smooth functions of a scalar covariate $u$, and $\boldsymbol{\alpha}_i$ represents subject specific random effects. Similar temporal assumptions have been made previously in smoking behavior research studies \citep{bolman2018predicting,minami2014relations, shiffman1996first,shiffman2013conceptualizing,shiyko2014modeling}. Note that in general, researchers may use the framework of \ref{VICM} to model the relation between a binary outcome and potential risk factors collected concurrently, in addition to lagged trends, as is typical in longitudinal studies \citep{fitzmaurice2012applied}. With this formulation, we include varying-coefficient terms for each of the $P$ risk factors based on $u$. However in general, we can specify varying-coefficient terms that depend on $u^{\prime} \ne u$, and thus the number of varying-coefficient terms in the full model is not strictly $P$. If $u$ is chosen to represent time, then this model is commonly referred to as a \textit{time-varying effect model} in smoking behavior research \citep{tan2012time,vasilenko2014time,dziak2015modeling,koslovsky2017time}. Note that $ \boldsymbol{z}_{ij}$ is typically a subset of $\boldsymbol{x}_{ij} $ \citep{kinney2007fixed,cheng2010real,hui2017hierarchical} and that incorporating a 1 in $ \boldsymbol{x}_{ij}$ and $\boldsymbol{z}_{ij} $, allows for an intercept term that varies as a function of $u$ and a random intercept term, respectively. Additionally, this formulation can handle time-invariant risk factors, such as baseline items, by fixing $x_{ijp}$ ($z_{ijd}$) to $x_{ip}$ ($z_{id}$) for all observations $j$. We approximate the smooth functions with spline basis functions. Specifically, \begin{equation}\label{smooth} f_p(u_{ij})= \boldsymbol{ \mathcal{U}}_{ij}^{\prime} \boldsymbol{\phi}_p, \end{equation} where $\boldsymbol{ \mathcal{U}}_{ij}$ is a spline basis function for $u_{ij}$, and $ \boldsymbol{\phi}_p$ is a $r_p$-dimensional vector of corresponding spline coefficients. For simplicity, the splines are constructed with an equal number of equally spaced knots that depend on the minimum and maximum values of $\boldsymbol{u}$. \subsection{Penalized Priors for the Spline Coefficients}\label{Spline} Using a combination of variable selection and shrinkage priors, our approach generates insights on the underlying structure of the smooth functions by reconstructing them as the summation of main effect, linear interaction, and non-linear interaction components. Formally, we rewrite Equation (Eq.) \eqref{smooth} as \begin{equation}\label{smoothII} f_p(u_{ij}) = \beta^{*}_p\boldsymbol{ \mathcal{U}}_{ij}^{*\prime}\boldsymbol{\xi}_p + \beta_p^{\circ}u_{ij} + \beta_{0p}, \end{equation} where the constant term $\beta_{0p}$ captures the main effect of $\boldsymbol{x}_p$, $\beta_p^{\circ}$ represents the effect of the linear interaction between $\boldsymbol{u}$ and $\boldsymbol{x}_p$, and $\beta^{*}_p\boldsymbol{\xi}_p$ is a parameter-expanded vector of coefficients corresponding to the non-linear interaction term. To derive the non-linear component in Eq. \eqref{smoothII}, we start by penalizing the spline functions in Eq. \eqref{smooth} with a second-order Gaussian random walk prior following \begin{equation}\label{smoothprior} \boldsymbol{ \mathcal{U}} \boldsymbol{\phi}_p |s^2 \sim N(\boldsymbol{0},s^2\boldsymbol{ \mathcal{U}}\boldsymbol{P}^{-}\boldsymbol{ \mathcal{U}}^{\prime}), \end{equation} where $\boldsymbol{\mathcal{U}}$ is a $\sum_{i = 1}^N (n_i-1) \times r_p$-dimensional matrix with each row corresponding to $\boldsymbol{\mathcal{U}}_{ij}^{\prime}$ for the $i^{th}$ subject at the $j^{th}$ assessment, $s^2$ controls the amount of smoothness, and $\boldsymbol{P}$ is the appropriate penalty matrix \citep{lang2004bayesian}. Next, we take the spectral decomposition of $\boldsymbol{ \mathcal{U}}\boldsymbol{P}^{-}\boldsymbol{ \mathcal{U}}^{\prime} =$ $\begin{bmatrix} \boldsymbol{U}_+ & \boldsymbol{U}_{\circ} \end{bmatrix}$ $\begin{bmatrix} \boldsymbol{V}_+ & \boldsymbol{0}\\ \boldsymbol{0} & \boldsymbol{0} \end{bmatrix}$ $\begin{bmatrix} \boldsymbol{U}_+ \\ \boldsymbol{U}_{\circ}\end{bmatrix},$ where $\boldsymbol{U}_+$ is a matrix of eigenvectors with corresponding positive eigenvalues along the diagonal of matrix $\boldsymbol{V}_+$, and $\boldsymbol{U}_{\circ}$ are the eigenvectors associated with the zero eigenvalues. Now, we can re-define the smooth functions in Eq. \eqref{smooth} as the sum of non-linear (penalized) interaction, linear (non-penalized) interaction, and main effect terms as presented in Eq. \eqref{smoothII}, where the penalized term is written as $\boldsymbol{\mathcal{U}}^*\boldsymbol{\varphi}_p^*$ with $\boldsymbol{\mathcal{U}}^* = \boldsymbol{U}_+\boldsymbol{V}_+^{1/2}$. By assuming independent normal priors for $\boldsymbol{\varphi}_p^*$, a proper prior for the penalized terms that is proportional to Eq. \eqref{smoothprior} can be obtained. We take two additional measures to enhance the computational efficiency of the resulting MCMC algorithm. First, only eigenvalues/vectors that explain a majority of the variability in Eq. \eqref{smoothprior} are used to construct $\boldsymbol{\mathcal{U}}^*$. Additionally, we apply a parameter-expansion technique for the penalized terms in $f_p (\cdot)$, setting $\boldsymbol{\varphi}_p^* = \beta^{*}_p\boldsymbol{\xi}_p$, where $\beta^{*}_p$ is a scalar and $\boldsymbol{\xi}_p$ is a vector with the same dimension as $\boldsymbol{\varphi}_p^*$. This technique enables us to perform selection on the penalized terms as a group rather than determining their inclusion separately. By rescaling $\beta^{*}_p$ and $\boldsymbol{\xi}_p$ at each MCMC iteration, such that $|\boldsymbol{\xi}_p|$ has mean equal to one, $\boldsymbol{\xi}_p$ maintains the shape of the smooth function and $\beta^{*}_p$ represents the term's strength of association, while preserving identifiability, similar to \cite{scheipl2012spike}. For variable selection, we impose spike-and-slab prior distributions on the $3*P = T$-dimensional vector $\boldsymbol{\beta} = (\beta^*_1,\beta^{\circ}_1,\beta_{01},\dots, \beta^*_P,\beta^{\circ}_P, \beta_{0P})^{\prime}$. In general, the spike-and-slab prior distribution is composed of a mixture of a Dirac delta function at zero, $\delta_0(\cdot)$, and a known distribution, $\mathcal{S}(\cdot)$, such as a normal with mean zero and diffuse variance \citep{george1993variable,brown1998multivariate}. A latent indicator variable, $\nu_t$, representing a risk factor's inclusion or exclusion in the model determines whether the risk factor's regression coefficient is set to zero (spike) or free to be estimated in the model (slab). Specifically for a given coefficient $\beta_t$, we assume \begin{eqnarray} \label{eq:prior_beta} \beta_t|\nu_t \sim \nu_t\cdot \mathcal{S}(\beta_t) + (1-\nu_t)\delta_0(\beta_t). \end{eqnarray} To complete the prior specification for this portion of the model, we assume that the slab component, $\mathcal{S}(\beta_t)$, follows a $N(0,\tau^2)$ with variance $\tau^2$, and that the inclusion indicators are distributed as $\nu_t|\theta_t \sim \mbox{Bernoulli}(\theta_t)$, with prior probability of inclusion $\theta_t \sim \mbox{Beta}(a_{\nu_t},b_{\nu_t})$. Integrating out $\theta_t$ we obtain $\nu_t \sim$ Beta-Binomial$(a_{\nu_t},b_{\nu_t})$, where hyperparameters $a_{\nu_t}$ and $b_{\nu_t}$ are set to control the sparsity in the model. Lastly, each element of $\boldsymbol{\xi}_p $, $\xi_{pr}$, is assumed to follow a $N(\mu_{pr},1)$, with mean $\mu_{pr} =\pm1$ with equal probability. Placing a majority of the prior mass for each $ \xi_{pr}$ around $\pm 1$ is motivated by the role it plays in the expansion of $\boldsymbol{\varphi}_p^*$, as described above. \subsection{Prior Specification for the Random Effects} We perform selection on the random effects, $\boldsymbol{\alpha}_i$, using the modified Cholesky decomposition approach of \cite{chen2003random}. Specifically, we reparameterize the random effects \begin{equation} \boldsymbol{\alpha}_{i} = \boldsymbol{K}\boldsymbol{\Gamma}\boldsymbol{\zeta}_i, \end{equation} where $\boldsymbol{K}$ a positive diagonal matrix with elements $\boldsymbol{\kappa} = (\kappa_1,\dots, \kappa_D)^{\prime}$, and $\boldsymbol{\Gamma}$ a lower triangle matrix with diagonal elements set to one and free elements otherwise. To perform variable selection, we set the prior for $\boldsymbol{\kappa}$ to follow a similar spike-and-slab prior distribution as in section 2.2, where the slab distribution $\mathcal{S}(\kappa_d) = FN(m_0,v_0)$. Here, $FN$ represents a folded normal distribution defined as $$FN(m_0,v_0) = (2\pi v_0)^{-1/2}\exp(-(\kappa_d - m_0)^2/(2v_0)) + (2\pi v_0)^{-1/2}\exp(-(\kappa_d + m_0)^2/(2v_0)),$$ where $m_0 \in \mathbb{R}$ and $v_0 > 0 $ are location and scale parameters, respectively. Note that we forgo the parameter-expansion approach of \cite{kinney2007fixed}, which introduces a redundant multiplicative parameter in the implied random effect covariance matrix, in favor of a model that enables meaningful inference for $\boldsymbol{\kappa}$ and ultimiately their cluster assignments. Similar to section \ref{Spline}, we let the corresponding inclusion indicators $\lambda_d$ follow a Beta-Binomial$(a_{\lambda_d},b_{\lambda_d})$ to induce sparsity on the random effect terms. Lastly, we assume the $D(D-1)/2$-dimensional vector of free elements in $\boldsymbol{\Gamma}$ follow $N(\boldsymbol{\gamma}_0, V_{\gamma}) \cdot I(\boldsymbol{\gamma} \in \mathcal{Z}) $, where $I$ represents an indicator function, and $\mathcal{Z}$ represents the parameters with corresponding random effects included in the model. For example, if the $d^{th}$ random effect is included (i.e., $\lambda_d = 1$), then $\gamma_{d1},\dots,\gamma_{d,d-1}\mbox{ and } \gamma_{d+1,d}, \dots \gamma_{D,d} \in \mathcal{Z}$. Lastly, we assume $\boldsymbol{\zeta}_i \sim N(\boldsymbol{0},\boldsymbol{I}).$ \subsection{Spiked Nonparametric Priors} To complete our approach, we investigate nonparametric prior constructions for the spike-and-slab components of the reparameterized fixed and random effects by assuming that the slab component follows a Dirichlet process (DP). These priors are commonly referred to as spiked DP (SDP) priors \citep{canale2017pitman,kim2009spiked,savitsky2010spiked,dunson2008bayesian}. In the context of our model, SDP priors allow us to simultaneously select influential risk factors while clustering effects with similar relations to the smoking outcome. The formulation we use here is sometimes refers to as an ``outer" SDP prior, since the point mass at zero is outside of the base distribution of the DP. Alternatively, the ``inner" construction places the spike-and-slab prior inside the DP, serving as the base distribution. The inner formulation provides the opportunity for coefficients to cluster at zero, but does not force a point mass at zero explicitly. As such, the likelihood that a coefficient is assigned to the trivial cluster grows with the number of coefficients excluded from the model. Alternatively, the outer formulation is a more informative prior, since it explicitly assigns a point mass at zero, and, in addition, carries less computational demands since it does not require auxiliary variables for MCMC sampling \citep{neal2000markov, savitsky2010spiked}. We refer readers to \cite{canale2017pitman} for a detailed explanation of the structural differences between the two prior formulations. First, we assume the regression coefficients associated with the main effects and linear interaction terms follow a SDP to provide insights on risk factors that share underlying linear trends with momentary smoking by the next assessment over the course of the study. Specifically, we assume the slab component in Eq. \eqref{eq:prior_beta} is a Dirichlet process prior $H \sim DP(\vartheta,H_0)$, with base distribution $H_0 = N(0,\tau^2)$ and concentration parameter $\vartheta$. Furthermore, we assume a hyperprior $\vartheta \sim G(a_{\vartheta},b_{\vartheta})$, with $a_{\vartheta},b_{\vartheta} > 0$. For the nonlinear interaction terms, we avoid the SDP since it would produce uninterpretable cluster assignments due to the parameter-expansion approach taken to improve selection performance. For example, similar values for $\beta_t^*$ and $\beta_{t'}^*$ may correspond to vastly different $\boldsymbol{\varphi}^*_t$ and $\boldsymbol{\varphi}^*_{t'}$, depending on their respective $\boldsymbol{\xi}$ and spline basis functions. Similarly, placing a DP prior on the individual components in $\boldsymbol{\xi}$, or even $\boldsymbol{\varphi}$, would not provide interpretable results on the overall nonlinear effect. We take a similar approach for the random effects. Here, we assume the slab components for the diagonal elements of $\boldsymbol{K}$, $\mathcal{S}(\kappa_d) = W$, $W \sim DP( \mathcal{A}, W_0),$ where $W_0 \sim FN(m_0,v_0)$, and $\mathcal{A}$ is the concentration parameter of the DP. To complete the prior assumptions for the random effects portion of the model, let $\mathcal{A} \sim G(a_{\mathcal{A}}, b_{\mathcal{A}})$, where $a_{\mathcal{A}},b_{\mathcal{A}}>0$ are shape and rate parameters, respectively. There is evidence that relaxing parametric assumptions for random effects using DP priors may cause inferential challenges as the mean of the random effects are non-zero almost surely \citep{li2011center,yang2012bayesian,cai2017bayesian}. Our approach differs in that we do not directly replace the typical normal assumption for random effects with a nonparametric prior. Instead, we place a nonparametric prior on the covariance decomposition components, $\boldsymbol{K}$, while letting $\boldsymbol{\zeta}_i$ follow a normal distribution centered at zero. As such, our approach avoids any identifiability issues with the fixed effects while still relaxing the parametric assumption on the reparameterized random effects, $\boldsymbol{K \Gamma \zeta}_i$. It is important to note that by doing this we are adopting a Bayesian semiparametric modeling structure, since the random effects are linear combinations of spiked Dirichlet process and normal random variables \citep{muller2007semiparametric}. \subsection{Posterior Inference} For posterior inference, we implement a Metropolis-Hastings within Gibbs algorithm. The full joint model is defined as $$ f(\boldsymbol{y}|\boldsymbol{\varrho},\boldsymbol{\omega},\boldsymbol{x},\boldsymbol{u},\boldsymbol{z})p(\boldsymbol{\omega})p(\boldsymbol{\beta}|\boldsymbol{\nu})p(\boldsymbol{\nu})p(\vartheta)p(\boldsymbol{K}|\boldsymbol{\lambda})p(\boldsymbol{\lambda})p(\mathcal{A})p(\boldsymbol{\xi}|\boldsymbol{\mu})p( \boldsymbol{\mu})p(\boldsymbol{\zeta})p(\boldsymbol{\Gamma}),$$ where $\boldsymbol{\varrho} = \{\boldsymbol{\beta}, \boldsymbol{\xi}, \boldsymbol{K}, \boldsymbol{\Gamma},\boldsymbol{\zeta} \}$. We use the P\'olya-Gamma augmentation of \cite{polson2013bayesian} to efficiently sample the posterior distribution for the logistic regression model. Following \cite{polson2013bayesian}, we express the likelihood contribution of $y_{i,j+1}$ as $$f(y_{i,j+1}|\cdot) = \frac{(e^{\psi_{ij}})^{y_{i,j+1}}}{(1 + e^{\psi_{ij}})} \propto \exp({k_{i,j+1}\psi_{ij}})\int_{0}^{\infty}\exp(-\omega_{i,j+1}\psi_{ij}^2/2)p(\omega_{i,j+1}|n_{i,j+1},0)\partial \omega, $$ where $k_{i,j+1} = y_{i,j+1} - n_{i,j+1}/2$, $p(\omega_{i,j+1}|n_{i,j+1},0) \sim PG(n_{i,j+1},0)$, and $PG$ is the P\'olya-Gamma distribution. Using the notation presented in the previous sections, we set $$\psi_{ij} = \sum_{p=1}^{P}(\beta^{*}_p\boldsymbol{ \mathcal{U}}_{ij}^*\boldsymbol{\xi}_p + \beta_p^{\circ}u_{ij} + \beta_{0p})x_{ijp} + \boldsymbol{z}_{ij}^{\prime} \boldsymbol{K} \boldsymbol{\Gamma} \boldsymbol{\zeta}_i.$$ The MCMC sampler used to implement our model is outlined below in Algorithm 1. A more detailed description of the MCMC steps as well as a graphical representation of the model are provided in the Supplementary Material. After burn-in and thinning, the remaining samples obtained from running Algorithm 1 for $\tilde{T}$ iterations are used for inference. To determine a risk factor's inclusion in the model, its marginal posterior probability of inclusion (MPPI) is empirically estimated by calculating the average of its respective inclusion indicator's MCMC samples \citep{george1997approaches}. Note that inclusion for both fixed and random effects is determined marginally for $\beta_t$ and $\lambda_d$, respectively. Commonly, covariates are included in the model if their MPPI exceeds 0.50 \citep{barbieri2004optimal} or a Bayesian false discovery rate threshold, which controls for multiplicity \citep{newton2004detecting}. \begin{algorithm} \caption{MCMC Sampler}\label{MCMC} \begin{algorithmic}[1] \State Input data $\boldsymbol{y},\boldsymbol{x},\boldsymbol{u},\boldsymbol{z}$ \State Initialize parameters: $\boldsymbol{\varrho}, \boldsymbol{\omega}, \boldsymbol{\nu},\boldsymbol{\lambda},\vartheta, \mathcal{A}, \boldsymbol{\mu}$ \State Set $DP_{\bar{\boldsymbol{\beta}}}$ and $DP_{\boldsymbol{K}}$ to True or False to indicate DP for slab on fixed or random effects, respectively. \For{iteration $\tilde t = 1,\dots,\tilde T$} \For{$i = 1,\dots,N$} \For{ $j = 1,\dots,n_i-1$} \State Update $\omega_{i,j+1} \sim PG(1,\psi_{ij})$ \EndFor \EndFor \If {$DP_{\bar{\boldsymbol{\beta}}}$ } \State Update cluster assignment of $\bar{\boldsymbol{\beta}}$ following \cite{neal2000markov} algorithm 2. \EndIf \State Jointly update $\boldsymbol{\beta}$ and $\boldsymbol{\nu}$ with Between and Within Step following \cite{savitsky2011variable}. \State Update $\boldsymbol{\xi}$ from FCD $N(\mu_{\boldsymbol{\xi}},V_{\boldsymbol{\xi}})$. \For{ $p = 1,\dots,P$} \State Rescale $\boldsymbol{\xi}_p^*$ and $\beta_p^*$ so $\boldsymbol{\varphi}_p^*$ remains unchanged. \EndFor \For{$p = 1,\dots,P$} \For{ $r = 1,\dots,r_p$} \State Set $\mu_{pr} = 1$ with probabilty $1/(1 + \exp(-2\xi_{pr}))$. \EndFor \EndFor \State Update $\vartheta$ by the two-step Gibbs update of \cite{escobar1995bayesian}. \If {$DP_{\boldsymbol{K}}$ } \State Update cluster assignment of $DP_{\boldsymbol{K}}$ following \cite{neal2000markov} algorithm 2. \EndIf \State Jointly update $\boldsymbol{K}$ and $\boldsymbol{\lambda}$ with Between and Within Step following \cite{savitsky2011variable}. \State Update $\mathcal{A}$ following two-step Gibbs update of \cite{escobar1995bayesian}. \State Update $\boldsymbol{\Gamma}$ from FCD $N(\hat{\boldsymbol{\gamma}},\hat{V}_{\gamma})\cdot I(\boldsymbol{\gamma} \in \mathcal{Z})$. \For{ $i = 1,\dots, N $ } \State Update $\boldsymbol{\zeta}_i$ from FCD $N(\hat{\boldsymbol{\zeta}}_i,\hat{V}_{\zeta_i})$. \EndFor \EndFor \end{algorithmic} \end{algorithm} \section{Case Study} \label{sec:case} In this section, we study the smoking behaviors in a group of adult smokers recruited from a smoking cessation research clinic. The overall research goal of this study was to identify and investigate the structural form of the relations between a set of risk factors and smoking over a five-week period surrounding a scheduled quit attempt, using intensive longitudinal data collected with EMAs. \subsection{Data Analysis} In the study design, momentary smoking, our outcome of interest, was defined as whether or not a subject reported smoking in the 4 hours prior to the current EMA. However at each EMA, a subject was prompted on their \textit{current} psychological, social, environmental, and behavioral status. Thus to maintain temporality in this study, we assessed the relations between momentary smoking and measurements collected in the previous EMA. As such, regression coefficients are interpreted as the log odds of momentary smoking by the next assessment for a particular risk factor. In this study, we investigated psychological and affective factors including \textit{urge} to smoke, feelings of \textit{restlessness}, \textit{negative affect} (i.e., irritability, frustration/anger, sadness, worry, misery), \textit{positive affect} (i.e., happiness and calmness), being \textit{bored}, \textit{anxiousness}, and \textit{motivation to quit smoking}. Additionally, we investigated numerous social and environmental factors such as whether or not the subject was \textit{interacting with a smoker}, if cigarettes were easily available (\textit{cigarette availability}), and whether or not the subject was drinking alcohol (\textit{alcohol consumption}). Also, we included a set of baseline, time-invariant measures (i.e., heaviness of smoking index (\textit{HSI}), \textit{age} (years), being \textit{female}, and treatment assignment) into the model. For each of these risk factors, we included a fixed main effect, linear interaction, and non-linear interaction term as well as a random main effect and linear interaction term. All interactions investigated in this analysis were between risk factors and assessment time (i.e., $u_{ij} = t_{ij}$), and $t_{ij}$ were centered so that $t=0$ represents the beginning of the scheduled quit attempt. Only complete EMAs with corresponding timestamps were included in this analysis, resulting in 9,634 total observations with the median number of assessments per individual 151 (IQR 101.5-162). All continuous covariates were standardized to mean zero and variance one before analysis to help reduce multicollinearity and place covariates on the same scale for interpretation. The spline functions were initially generated with 20 basis functions, but only the eigenvalues/eigenvectors that captured 99.9\% of the variability were included in the model to reduce the parameter space and computation time, similar to \citep{scheipl2012spike}. This reduced the column space of the penalized covariates $\boldsymbol{\mathcal{U}}^*$ to 8 in our application. We applied our model with the traditional spike-and-slab prior, as well as the spiked DP. When fitting each model, we chose a non-informative prior for the fixed and random effects' inclusion indicators, $a_{\nu_t} = b_{\nu_t} = a_{\lambda_d} = b_{\lambda_d} = 1$. This assumption reflects the exploratory nature of our study aimed at learning potential relations between risk factors and smoking behaviors with little or no information regarding their occurrence in the presence of other risk factors. We assumed a mildly informative prior on the fixed regression coefficients by setting $\tau^2= 2$. This places a 95\% prior probability of included regression coefficients between an odds ratio of 0.06 and 16. Additionally, we set $ v_0= v^*= 10$, $m_0 = m^* = 0$, and ${\Gamma} \sim N( \boldsymbol{\gamma}_0 = \boldsymbol{0},\boldsymbol{V}_{\gamma}=\boldsymbol{I} )$. Lastly, when using the SDP prior, the hyperparameters for the concentration parameters $\vartheta$ and $\mathcal{A}$ were set to $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 1$. For posterior inference, we ran our MCMC algorithm with and without SDP priors for both fixed and random effects for 10,000 iterations, treating the first 5,000 as burn-in and thinning to every 10$^{th}$ iteration. Trace plots of the parameters' posterior samples indicated good convergence and mixing. Additionally, we observed a relatively high correlation ($\sim 97$\%) between the posterior probabilities of inclusion obtained from two chains initiated with different parameter values, and potential scale reduction factors, $\hat{R}$, for each of the selected $\boldsymbol{\beta}$ and $\boldsymbol{K}$ below 1.1 \citep{gelman1992inference}, further demonstrating that the MCMC procedure was working properly and the chains converged. To assess model fit, a residual plot and a series of posterior predictive checks were performed in which we compared replicated data sets from the posterior predictive distribution of the model to the observed data \citep{gelman2000diagnostic}. Overall, we found strong evidence of good model fit. See the Supplementary Materials for details. Inclusion in the model was determined using the median model approach \citep{barbieri2004optimal} (i.e., marginal posterior probability of inclusion (MPPI) $\geq 0.50 $). For the SDP model, clusters of regression coefficients were determined using sequentially-allocated latent structure optimization to minimize the lower bound of the variation of information loss \citep{wade2018bayesian,dahl2017}. To compare the predictive performance of both models, we performed a leave-one-out cross-validation approximation procedure, following the approach proposed by \cite{vehtari2017practical}. This approach approximates leave-one-out (LOO) cross-validation with the expected log pointwise predictive density (epld). By using Pareto smoothed importance sampling (PSIS) for estimation, it provides a more stable estimate compared to the method of \cite{gelfand1996model}. We used the R package \texttt{loo} \citep{vehtari2016loo}, which requires the pointwise log-likelihood for each subject $i = 1, \dots , N$ at each observation $j = 1, \dots, n_i$ calculated at each MCMC iteration $s = 1, \dots, S$, and produces an estimated $\widehat{\mbox{epld}}$ value, with larger values implying a superior model. \subsection{Results} Overall, we found better predictive performance for the model with SDP priors versus the traditional spike-and-slab priors, $\widehat{\mbox{epld}}_{SDP} = -2985.1 $ and $\widehat{\mbox{epld}}_{SS} = -3062.7 $, respectively. Plots of the marginal posterior probabilities of inclusion for the fixed and random effects selected using our proposed approach with SDP priors are found in Figure \ref{fig:MPPI}. Figure \ref{fig:curves} presents the time-varying effects selected using the same model. Compared to \textit{usual care}, we found a higher odds of momentary smoking by the next assessment for those assigned to the \textit{NCI QuitGuide} group prior to the quit attempt. However immediately after the quit attempt, we observed a lower odds of momentary smoking by the next assessment for those assigned to the \textit{NCI QuitGuide} group, which gradually increased to the initial level over the remainder of the study (top left panel). Similarly, we observed a positive relation between having the \textit{urge} to smoke and momentary smoking by the next assessment prior to the quit attempt that diminished during the three weeks following the quit attempt, before sharply increasing during the fourth week post-quit (top right panel). Throughout the assessment period, we observed a positive relation between \textit{negative affect} and momentary smoking by the next assessment that increased during the first week post-quit, leveling off at an odds ratio of 1.75 until the third week after the quit attempt. We additionally found a positive relation between \textit{cigarette availability} and the odds of momentary smoking by the next assessment that strengthened over the assessment window. For a 1 SD increase in \textit{cigarette availability}, the odds of momentary smoking by the next assessment increased by 300\% for the typical subject one week after the quit attempt, holding all else constant. In the two lower panels of Figure \ref{fig:curves} we observe a relatively weak, oscillating effect of being \textit{bored} and \textit{interacting with a smoker} on momentary smoking by the next assessment, respectively. In addition to these effects, the model identified a constant effect for \textit{alcohol consumption} in the last hour and \textit{motivation to quit smoking} over the assessment period. A similar set of fixed effect relations were identified by our model without the SDP prior, with the exception of not selecting being \textit{bored}. \begin{figure} \centering \includegraphics[scale=0.39]{MPPI_fixed.png} \includegraphics[scale=0.39]{MPPI_random.png} \caption{Smoking Cessation Study: Marginal posterior probabilities of inclusion (MPPI) for fixed ({\it top}) and random ({\it bottom}) effects. Selected fixed effects in ascending order: NCI (NL-INTX), urge to quit (NL-INTX), cigarette availability (all), interacting with a smoker (NL-INTX), negative affect (NL-INTX, main), being bored (NL-INTX), alcohol consumption (main), motivation to quit (main), HSI (NL-INTX). Selected random effects in ascending order: urge (main), cigarette availability (main), being bored (main), motivation to quit (main), SmartT (L-INTX), interacting with a smoker (L-INTX), being bored (L-INTX). Dotted lines represent the inclusion threshold of 0.50. NL-INTX: non-linear interaction, L-INTX: linear interaction } \label{fig:MPPI} \end{figure} \begin{figure} \centering \includegraphics[scale=0.3]{SmartT_NCI.png} \includegraphics[scale=0.3]{SmartT_Urge.png}\\ \vskip 2mm \includegraphics[scale=0.3]{SmartT_Negative.png} \includegraphics[scale=0.3]{SmartT_Cigarettes.png}\\ \vskip 2mm \includegraphics[scale=0.3]{SmartT_Bored.png} \includegraphics[scale=0.3]{SmartT_Interacting.png} \caption{Smoking Cessation Study: Time-varying effects on momentary smoking by the next assessment of those covariates selected by our model with SDP priors. Shaded regions represent pointwise 95\% CI. Dashed lines indicate an odds ratio of one. } \label{fig:curves} \end{figure} Compared to standard TVEMs, our approach deconstructs the structure of the relations between risk factors and smoking behaviors over time, aiding the interpretation of the underlying trends. This information may help the development and evaluation of tailored intervention strategies targeting smoking cessation using mHealth data. For example, \textit{negative effect} has an obvious positive association with momentary smoking by the next assessment that wavers around an odds ratio of 1.2 to 1.5 for a majority of the study. However based on Figure \ref{fig:curves}, it is unclear whether or not the effect linearly diminishes over time. By performing selection on the main effect, linear interaction, and non-linear interaction terms separately, we are able to obtain an actual point estimate for the constant effect of \textit{negative affect} (OR 1.40) as opposed to subjectively assuming a range of values from the plot. Additionally, since the linear interaction term was not selected, we can claim that the effect was not linearly decreasing over time and that it was simply wavering around the constant effect throughout the study. Tables \ref{tab:one} and \ref{tab:two} present the estimated variances and corresponding 95\% credible intervals (CI) for the random effects selected using SDP priors and traditional spike-and-slab priors, respectively. Using SDP priors, our method identified a random main effect for \textit{urge} to smoke, \textit{cigarette availability}, being \textit{bored}, and \textit{motivation to quit smoking} as well as a random linear interaction between being assigned to the \textit{SmartT} treatment group, \textit{interacting with smokers}, and being \textit{bored} with time. Thus even though we did not discover an overall difference in the odds of momentary smoking by the next assessment for those assigned to the \textit{SmartT} treatment versus \textit{usual care}, we observed evidence that the subjects responded differently to the \textit{SmartT} treatment across the assessment window. With the traditional spike-and-slab priors, we found similar results overall. However, the model only selected a random main effect for \textit{interacting with smokers} and additionally suggested a random effect for \textit{anxiousness}. By using SDP priors, our approach is capable of clustering covariates that share similar linear trends with momentary smoking by the next assessment over time. In practice, this information can be used to help construct decision rules when designing future intervention strategies. In our analysis, only five main effect and linear interaction terms were selected, and each of them were allocated to their own cluster. With this knowledge, researchers can prioritize targeting risk factors based on their relative strength of association at a given moment. Had some of these risk factors' effects been clustered together, researchers may rely more heavily on other pieces of information, such as the cost or success rates for a particular intervention strategy, when assessing which risk factors to target during a high-risk moment. \begin{table} \centering \footnotesize \begin{tabular}{ccc} \hline \textbf{Random Effect} & \textbf{$\hat{\sigma}^2$} & \textbf{95\% CI} \\ \hline Intercept & 0.923 & (0.539, 1.528) \\ Urge & 0.152 & (0.031, 0.278) \\ Cigarette Availability & 0.865 & (0.394, 1.467) \\ Bored & 0.183 & (0.076, 0.398) \\ Motivation to Quit Smoking & 0.156 & (0.045, 0.311) \\ SmartT $\times$ Time & 0.077 & (0.010, 0.210) \\ Interacting with a Smoker $\times$ Time & 0.016 & (0.002, 0.050) \\ Bored $\times$ Time & 0.002 & (0.000, 0.005) \\ \hline \end{tabular} \caption{Smoking Cessation Study: Estimated variances with corresponding 95$\%$ credible intervals (CI) for selected random effects with SDP priors based on MPPI $\geq 0.50$.} \label{tab:one} \end{table} \begin{table} \centering \footnotesize \begin{tabular}{ccc} \hline \textbf{Random Effect} & \textbf{$\hat{\sigma}^2$} & \textbf{95\% CI} \\ \hline Intercept & 1.317 & (0.676, 2.487) \\ Urge & 0.099 & (0.011, 0.248) \\ Cigarette Availability & 0.905 & (0.503, 1.607) \\ Interacting with a Smoker & 0.848 & (0.286, 1.924) \\ Bored & 0.244 & (0.065, 0.517) \\ Anxiousness & 0.140 & (0.001, 0.361) \\ Motivation to Quit Smoking & 0.212 & (0.076, 0.448) \\ SmartT $\times$ Time & 0.062 & (0.016, 0.155) \\ Bored $\times$ Time & 0.002 & (0.000, 0.004) \\ \hline \end{tabular} \caption{Smoking Cessation Study: Estimated variances with corresponding 95$\%$ credible intervals (CI) for selected random effects with traditional spike-and-slab priors based on MPPI $\geq 0.50$.} \label{tab:two} \end{table} Similar to previous studies investigating the temporal relation between risk factors and smoking behaviors around a quit attempt, our results show a convex relation between \textit{urge} to smoke and momentary smoking after the quit attempt, a positive association with \textit{cigarette availability} throughout the quit attempt, and a positive, increasing relation between \textit{negative affect} and momentary smoking during the first week after the quit attempt \citep{koslovsky2017time,vasilenko2014time}. Existing TVEMs approaches, however, typically model the repeated measures structure of the data by simply including a random intercept term in the model, neglecting to investigate random main effects or interaction terms. They also do not incorporate variable selection. Our approach, on the other hand, delivers insights on how relations vary over time as well as how they vary across individuals. \subsection{Sensitivity Analysis} \label{sec:sens} To investigate our model's sensitivity to prior specification, we set each of the hyperparameters to default values and then evaluated the effect of manipulating each term on the results obtained in section \ref{sec:case}. For the default parameterization, we set the hyperparameters for the prior inclusion indicators $\boldsymbol{\nu}$ and $\boldsymbol{\lambda}$ to $a_{\nu_t}=b_{\nu_t}=a_{\lambda_d}=b_{\lambda_d} = 1$. For interpretation, $a_{\nu_t}=b_{\nu_t}=1$ implies that the prior probability of inclusion for a fixed effect is $a_{\nu_t}/(a_{\nu_t} + b_{\nu_t})=0.50$. The default values for the variance of the normal distribution for the slab of $\boldsymbol{\beta}_0$ and $\boldsymbol{\beta}^{\circ}$ as well as the base distribution for $\boldsymbol{\beta}^{*}$ were each fixed at $5$. Additionally, the mean and variance for the random effect terms' proposal and prior distributions were set to $0$ and $5$, respectively. The hyperparameters for the concentration parameters $\vartheta$ and $\mathcal{A}$ were set to $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 1$. Lastly, we assumed ${\Gamma} \sim N( \boldsymbol{\gamma}_0 = \boldsymbol{0},\boldsymbol{V}_{\gamma}=\boldsymbol{I} )$. We ran our MCMC algorithm for 10,000 iterations, treating the first 5,000 iterations as burn-in and thinning to every $10^{th}$ iteration for the SDP model, similar to our case study. For each of the fixed and random effects, inclusion in the model was determined using the median model approach \citep{barbieri2004optimal}. Since the true model is never known in practice, we evaluated each model parameterization in terms of sparsity levels and overlap with the results reported in the case study section. Specifically, we present the total number terms selected for both fixed and random effects (\# Fixed and \# Random). We also provide the proportion of active risk factors in our case study that were also included by each model and the proportion of inactive risk factors that were also excluded by each model, for fixed (f-IN and f-EX) and random effects (r-IN and r-EX) as well as overall (IN and EX). Results of the sensitivity analysis are reported in Table \ref{tab:four}. Compared to the results presented in the case study, we found relatively consistent overlap in the risk factors included and excluded by each model overall. We observed moderate sensitivity to hyperparameter values in terms of percent overlap for fixed and random effects of risk factors included in the model, an artifact of the relatively weak associations identified for some of the risk factors. Notably, risk factors showing stronger associations with momentary smoking at the next assessment (e.g., \textit{negative affect}, \textit{cigarette availability}, and \textit{motivation to quit smoking}) were selected by the model regardless of prior specification. Likewise, weaker relations between momentary smoking at the next assessment and risk factors, such as \textit{being bored} and \textit{interacting with a smoker}, were more sensitive to hyperparameters. We also observed that the number of selected fixed and random effects increased (decreased) as the prior probability of inclusion increased (decreased), as expected. In practice, there are a variety of factors researchers should consider when setting the prior probability of inclusion, including the aim of the research study, the desired sparsity of the model, prior knowledge of covariates inclusion, as well as results from simulation and sensitivity analyses to name a few. From a clinical perspective, $\tau^2=10$ reflects a relatively diffuse prior for a given risk factor (i.e., odds ratio between 0.002 and roughly 500). To further investigate the model's sensitivity to regression coefficients' variances, we set $\tau^2=v_0=1000$, and found somewhat similar results to the model with $\tau^2 =v_0 = 10$ overall (i.e., IN = 0.8, EX = 0.8). Here, we unexpectedly found non-montonic behavior in the proportion of included and excluded terms as a function of the coefficients' variance, which might also reflect our model's sensitivity to relatively weak associations as previously noted. In theory, the selection of random effects may be sensitive to the order in which the columns of $\boldsymbol{Z}$ are ordered, since the Cholesky decomposition is itself, order dependent \citep{muller2013model}. In our case study, we did not observe any differences regarding which random effects were selected with a random permutation of the $\boldsymbol{Z}$ columns. In section \ref{sec:sens}, we further demonstrate our model's robustness to the ordering of $\boldsymbol{Z }$ on simulated data. \begin{table} \centering \footnotesize \begin{tabular}{cccccc} \hline & $a_{v_t} = a_{\lambda_d} = 1$, $b_{v_t} = b_{\lambda_d} = 9$ & & $\tau^2 = v_0 = 2$ & & $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 0.1$ \\ \cline{2-2} \cline{4-4} \cline{6-6} \# Fixed & 4 & & 8 & & 6 \\ \# Random & 5 & & 5 & & 7 \\ IN & 0.60 & & 0.70 & & 0.80 \\ f-IN & 0.44 & & 0.67 & & 0.56 \\ r-IN & 0.50 & & 0.50 & & 0.83 \\ EX & 0.80 & & 0.60 & & 1.00 \\ f-EX & 1.00 & & 1.00 & & 1.00 \\ r-EX & 0.78 & & 0.78 & & 0.89 \\ & $a_{v_t} = a_{\lambda_d} = 9$, $b_{v_t} = b_{\lambda_d} = 1$ & & $\tau^2 = v_0 = 10$ & & $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 10$ \\ \cline{2-2} \cline{4-4} \cline{6-6} \# Fixed & 10 & & 7 & & 6 \\ \# Random & 8 & & 5 & & 4 \\ IN & 1.00 & & 0.60 & & 0.80 \\ f-IN & 0.78 & & 0.67 & & 0.56 \\ r-IN & 0.83 & & 0.50 & & 0.33 \\ EX & 0.60 & & 1.00 & & 1.00 \\ f-EX & 0.83 & & 0.80 & & 1.00 \\ r-EX & 0.67 & & 0.78 & & 0.78 \\ \hline \end{tabular} \caption{Case Study Data: Sensitivity results for the proposed model with SDP across various prior specifications. Total number of terms selected for both fixed and random effects are indicted as \# Fixed and \# Random, respectively. The proportion of active (inactive) risk factors presented in the case study that were also included (excluded) by each model is reported as f-IN and r-IN (f-EX and r-EX), for fixed and random effects, respectively. Finally, the overall proportion of active (inactive) risk factors presented in the case study that were also included (excluded) by each model is represented as IN (EX). } \label{tab:four} \end{table} \section{Simulation Study} \label{sec:simul} In this section, we evaluate our model in terms of variable selection and clustering performance on simulated data similar in structure to our case study data. We compared our method with and without SDP priors on varying-coefficient and random effects to two other Bayesian methods which are designed to handle this class of models. The first is the method of \cite{scheipl2012spike}, which has previously shown promising results performing function selection in structural additive regression models using continuous spike-and-slab priors. Their approach differs from ours in that they assume parameter-expanded normal-mixture-of-inverse-gamma (peNMIG) distribution priors for selection, inspired by \cite{ishwaran2005spike}, and design a Metropolis-Hastings with penalized iteratively weighted least-squares algorithm for updating regression coefficients within the logistic framework. A popular alternative to spike-and-slab priors to induce sparsity in high-dimensional regression settings is to assume global-local shrinkage priors on the regression coefficients (see \cite{van2019shrinkage, bhadra2019lasso} for detailed reviews). At the request of a reviewer, we additionally compared our proposed model to a reparameterized version with shrinkage priors \citep{carvalho2009handling}. To achieve this, we replaced the spike-and-slab priors on $\boldsymbol{\beta}$ with horseshoe priors, which belong to the class of global-local scale mixtures of normal priors \citep{polson2010shrink}. For random effects, $\boldsymbol{K}$, we assumed a similar global-local structure for the scale parameters of the folded-normal distribution, $v_0$. To our knowledge, the theoretical properties and selection performance of global-local scale mixtures of non-normal priors have yet to be explored. However we conjectured that the global-local framework should effectively shrink inactive random effects towards zero and allow active terms to be freely estimated. Details of the resulting model and accompanying MCMC algorithm are found in the Supplementary Material. We simulated $N = 100$ subjects with $20$-$40$ observations randomly spaced across an assessment window with $t_{ij} \in [0,1]$, without loss of generality. For each observation, we generated a set of 15 covariates, $\boldsymbol{x}_i$, comprised of an intercept term and 14 continuous covariates simulated from a $N_{14}(\boldsymbol{0},\Sigma)$, where $\Sigma_{st} = w^{|s-t|}$ and $w = 0.3$. To simulate time-varying covariate trajectories, we randomly jittered half of the elements within $\boldsymbol{x}_i$ by $N(0,1)$. Additionally, we set $\boldsymbol{z}_{ij} = \boldsymbol{x}_{ij}$. Thus, each full model contained 15 main effects, linear interactions, non-linear interactions, and random main effects, corresponding to 60 potential terms (or groups of terms for the non-linear interaction components) to select. The first 5 functional terms in the true model were defined as \begin{itemize} \item $f_1(t_{ij}) = \pi\sin(3\pi t_{ij}) + 1.4t_{ij} - 1.6$ \item $f_2(t_{ij}) = \pi\cos(2\pi t_{ij}) + 1.6$ \item $f_3(t_{ij}) = - \pi t\sin(5\pi t_{ij}) + 1.7t_{ij} - 1.5$ \item $f_4(t_{ij}) = - 1.5t_{ij} + 1.6$ \item $f_5(t_{ij}) = - 1.6,$ \end{itemize} and the random effects $\boldsymbol{a}_i \sim N(\boldsymbol{0}, \Sigma_{\alpha})$ with $\sigma_{kk} = 0.75$ and $\sigma_{jk} = 0.4$ for $j,k = 1,\dots, 5$. Thus in the true model, $\psi_{ij} = \sum_{p = 1}^5f_p(t_{ij})x_{ijp} + \boldsymbol{z}_{ij}^{\prime}\boldsymbol{a}_i$. Note that to impose an inherent clustering for the main effects and linear interaction terms, their values were specified to center around $\pm 1.5$. We ran each of the MCMC algorithms on 50 replicated data sets, using 7,500 iterations, treating the first 3,750 iterations as burn-in and thinning to every $10^{th}$ iteration for each model. The spline functions were generated similar to our application. We set the hyperparameters for the inclusion indicators, $a_{\nu_t} =b_{\nu_t} =a_{\nu_t} =b_{\nu_t} = 1 $, imposing a non-informative prior for selection of fixed and random effect terms. Additionally, we fixed the regression coefficient hyperparameters to $\tau^2 = 2$ and $m_0 = 0$ with $v_0 = 10$. For the concentration parameters $\vartheta$ and $\mathcal{A}$, we assumed $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 1$. Before analysis, the covariates were standardized to mean $0$ and variance $1$ For each of the models with spike-and-slab priors, inclusion in the model for both fixed and random effects was determined using the median model approach \citep{barbieri2004optimal}. For the horseshoe model, fixed effects were considered active if their corresponding 95\% credible interval did not contain zero, similar to \cite{bhadra2019lasso}. The 95\% credible interval for random effects will almost surely not contain zero. As a naive alternative, we assumed a random effect was active in the model if its posterior mean exceeded a given threshold. For the sake of demonstration, we evaluated the performance of the model over a grid of potential threshold values, and presented the results for the best performing model overall. Notably, this solution is only feasible when the true answer is known, which is never the case in practice. Variable selection performance was evaluated via sensitivity (SENS), specificity (SPEC), and Matthew's correlation coefficient (MCC) for fixed and random effects separately. These metrics are defined as $$SENS = \frac{TP}{FN + TP}$$ $$SPEC = \frac{TN}{FP + TN}$$ $$MCC = \frac{TP \times TN - FP \times FN}{\sqrt{(TP + FP)(TP + FN)(TN + FP)(TN + FN)}},$$ where $TN$, $TP$, $FN$, and $FP$ represent the true negatives, true positives, false negatives, and false positives, respectively. For the SDP models, clusters of regression coefficients were determined using sequentially-allocated latent structure optimization to minimize the lower bound of the variation of information loss \citep{wade2018bayesian,dahl2017}. Once clusters were determined, clustering performance was evaluated using the variation of information, a measure of distance between two clusterings ranging from $0$ to $\log R$, where $R$ is the number of items to cluster and lower values imply better clustering \citep{meilua2003comparing}. Figure \ref{fig:simul} presents the estimated smooth functions obtained using our proposed method with SDP priors on a randomly selected replicated data set from the simulation study. Here, $f_1(t_{ij})$ represents the global intercept comprised of a main effect, linear interaction, and non-linear interaction term that were forced into the model. Of interest is the ability of the model to properly select the influential components in $f_2(t_{ij})$ and $f_3(t_{ij})$ and additionally capture their structure. Using the method proposed in \cite{dahl2017} to identify latent clusters of fixed main effect and linear interaction terms, our method successfully clustered the linear interaction in $f_1(t_{ij})$ and the main effects in $f_2(t_{ij})$ and $f_4(t_{ij})$, while incorrectly assigning the linear interaction term in $f_3(t_{ij})$ to its own cluster. Additionally, the main effects in $f_1(t_{ij})$, $f_3(t_{ij})$, and $f_5(t_{ij})$ were appropriately clustered together, while the linear interaction term in $f_4(t_{ij})$ was incorrectly assigning to its own cluster. The remaining, uninfluential terms were all allocated to the trivial group. Despite $f_1(t_{ij})$ and $f_3(t_{ij})$ having similar main effect and linear interaction terms, they are dramatically different in terms of their non-linear interaction terms. However by clustering their underlying linear trajectories, our model with SDP priors was able to uncover similarities in their relations with the outcome over time that traditional approaches would fail to discover. \begin{figure} \centering \includegraphics[width=4.5in,height=2.1in]{function_1.png} \\ \includegraphics[width=4.5in,height=2.1in]{function_2.png} \\ \includegraphics[width=4.5in,height=2.1in]{function_3.png} \caption{Simulated Data: Estimated smooth function $f_1(t_{ij}), f_2(t_{ij}), f_3(t_{ij})$ for a randomly selected replicate data set generated in the simulation study. The estimated smooth function is represented by a solid black line with pointwise 95\% credible regions in grey. Dashed lines represent the true log odds ratios as a function of time. } \label{fig:simul} \end{figure} Table \ref{tab:simul} reports results for our proposed method with SDP priors (PGBVSDP), our proposed method without SDP priors (PGBVS), peNMIG, and our model with horseshoe priors (PGHS) in terms of average sensitivity, specificity, and MCC for fixed (fSENS, fSPEC, fMCC) and random (rSENS, rSPEC, rMCC) effects across the replicate data sets with standard errors in parentheses. Additionally for the PGBVSDP model, we provide clustering performance results for fixed (fCLUST) and random effects (rCLUST). Since each of the random effects were simulated similarly, clusterings were compared to a single cluster for the non-zero terms. Overall, the methods had relatively similar results for fixed effects, with PGBVS and PGHS performing the best in terms of sensitivity (1.00 and 1.00) and MCC (0.96 and 0.99), respectively. Our method with SDP priors, PGBVSDP, obtained the highest specificity for fixed effects overall. Given that the maximum possible values fCLUST and rCLUST could take on were 3.4 and 2.7, respectively, we found fairly strong clustering performance for both fixed (0.39) and random (0.92) effects with PGBVSDP. We observed more variability in the selection of random effects across models. Random effect selection sensitivity was significantly lower compared to the fixed effects for all of the models. In terms of specificity (1-false positive rate) for random effects, our methods, regardless of prior formulation, dramatically outperformed peNMIG, with PGBVS obtaining the highest specificity overall (0.96). However, PGBVSDP and PGBVS had lower sensitivity with respect to random effects compared to PGHS. While PGHS performed well separating active from inactive random effects, recall that the truth was used to select the optimal selection threshold. The improved performance of PGBVS, PGBVSDP, and PGHS in terms of variable selection was achieved in considerably less computation time compared to peNMIG. Our core method was able to run 7,500 iterations in a fifth of the time compared to peNMIG, accessed via \cite{scheipl2011spikeslabgam}. Using the SDP priors, which requires additional updates for clustering the regression coefficients, we observed a two-fold increase in computation time for PGBVSDP compared to PGBVS. However on average, the PGBVSDP approach still achieved about a $50\%$ reduction in computation time compared to peNMIG. It is important to note that for comparison, all algorithms were run in series, even though the R package spikeSlabGAM \citep{scheipl2011spikeslabgam} provides functionality to run multiple chains in parallel. \begin{table} \centering \footnotesize \begin{tabular}{cccccccc} \hline & PGBVSDP & & PGBVS & & peNMIG & & PGHS \\ \cline{2-2} \cline{4-4} \cline{6-6} \cline{8-8} fSENS & 0.96 (0.09) & & 1.00 (0.02) & & 0.93 (0.11) & & 1.00 (0.00) \\ fSPEC & 0.99 (0.02) & & 0.98 (0.02) & & 0.94 (0.04) & & 0.96 (0.01) \\ fMCC & 0.94 (0.08) & & 0.96 (0.05) & & 0.83 (0.10) & & 0.99 (0.02) \\ fCLUST & 0.39 (0.21) & & - & & - & & - \\ rSENS & 0.76 (0.21) & & 0.62 (0.25) & & 0.46 (0.23) & & 0.86 (0.24) \\ rSPEC & 0.88 (0.10) & & 0.96 (0.05) & & 0.64 (0.16) & & 0.90 (0.11) \\ rMCC & 0.63 (0.26) & & 0.64 (0.23) & & 0.11 (0.33) & & 0.76 (0.21) \\ rCLUST & 0.92 (0.50) & & - & & - & & - \\ Time (s) & 4658 (271) & & 2235 (46) & & 10720 (1116) & & 3076 (74) \\ \cline{1-8} \end{tabular} \caption{Simulated Data: Results for the proposed model with and without the SDP on regression coefficients compared to peNMIG \citep{scheipl2012spike} and our model with horseshoe priors \citep{carvalho2009handling}. Results are averaged over 50 replicate data sets with standard deviations in parentheses. } \label{tab:simul} \end{table} \section{Sensitivity Analysis} \label{sec:sens} To assess the model's sensitivity to hyperparameter settings, we set each of the hyperparameters to default values and then evaluated the effect of manipulating each term on selection and clustering performance. For the default parameterization, we set the hyperparameters for the prior inclusion indicators $\boldsymbol{\nu}$ and $\boldsymbol{\lambda}$ to $a_{\nu_t}=b_{\nu_t}=a_{\lambda_d}=b_{\lambda_d} = 1$. The default values for the variance of the normal distribution for the slab of $\boldsymbol{\beta}_0$ and $\boldsymbol{\beta}^{\circ}$ as well as the base distribution for $\boldsymbol{\beta}^{*}$ were each fixed at $5$. Additionally, the mean and variance for the random effect terms' proposal and prior distributions were set to $0$ and $5$, respectively. The hyperparameters for the concentration parameters, $\vartheta$ and $\mathcal{A}$ $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 1$. Lastly, we assumed ${\Gamma} \sim N( \boldsymbol{\gamma}_0 = \boldsymbol{0},\boldsymbol{V}_{\gamma}=\boldsymbol{I} )$. We ran our MCMC algorithm on the 50 replicated data sets generated in the simulation study, using 7,500 iterations, treating the first 3,750 iterations as burn-in and thinning to every $10^{th}$ iteration for the SDP model. Results of the sensitivity analysis are reported in Table \ref{tab:sens}. As expected, we found that the sensitivity (specificity) increased (decreased) as the prior probability of inclusion for the fixed and random effects increased. The model did not seem sensitive to the variance assumed for the normal and folded normal priors assigned to the fixed and random effect slab distributions, respectively. Similarly, we found comparable results in terms of sensitivity and specificity for different values of the concentration parameters' hyperparameters. In terms of clustering, we saw marginally better variation of information measures with larger concentration parameter hyperparameters. However across simulations runs, we observed relatively high standard errors in terms of the variation of information measures. To assess potential sensitivity to the order of random effects in our simulations, we re-ran the simulation study with a random permutation of the columns of $\boldsymbol{Z}$. Similar to the case study, we found no evidence of sensitivity to random effect ordering with our model as the results were almost identical to those presented in Table 4 with PGBVSDP (rSENS = 0.76 (0.20), rSPEC = 0.87 (0.09), rMCC = 0.62 (0.20), rCLUST = 0.94 (0.42)). \begin{table} \centering \footnotesize \begin{tabular}{cccccc} \hline & $a_{v_t} = a_{\lambda_d} = 1$, $b_{v_t} = b_{\lambda_d} = 9$ & & $\tau^2 = v_0 = 2$ & & $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 0.1$ \\ \cline{2-2} \cline{4-4} \cline{6-6} fSENS & 0.92 (0.13) & & 0.97 (0.08) & & 0.94 (0.12) \\ fSPEC & 0.99 (0.02) & & 0.99 (0.02) & & 0.99 (0.02) \\ fMCC & 0.93 (0.10) & & 0.96 (0.07) & & 0.94 (0.09) \\ fCLUST & 0.45 (0.30) & & 0.35 (0.20) & & 0.45 (0.25) \\ rSENS & 0.50 (0.20) & & 0.79 (0.20) & & 0.54 (0.28) \\ rSPEC & 0.87 (0.09) & & 0.88 (0.08) & & 0.85 (0.10) \\ rMCC & 0.40 (0.26) & & 0.66 (0.23) & & 0.41 (0.29) \\ rCLUST & 1.30 (0.36) & & 0.91 (0.44) & & 1.25 (0.50) \\ & $a_{v_t} = a_{\lambda_d} = 9$, $b_{v_t} = b_{\lambda_d} = 1$ & & $\tau^2 = v_0 = 10$ & & $a_{\vartheta} = b_{\vartheta} = a_{\mathcal{A}} = b_{\mathcal{A}} = 10$ \\ \cline{2-2} \cline{4-4} \cline{6-6} fSENS & 0.99 (0.03) & & 0.96 (0.07) & & 0.94 (0.11) \\ fSPEC & 0.96 (0.03) & & 0.99 (0.02) & & 0.99 (0.02) \\ fMCC & 0.91 (0.06) & & 0.95 (0.07) & & 0.93 (0.11) \\ fCLUST & 0.40 (0.20) & & 0.39 (0.23) & & 0.41 (0.24) \\ rSENS & 0.85 (0.20) & & 0.78 (0.20) & & 0.74 (0.23) \\ rSPEC & 0.84 (0.10) & & 0.89 (0.10) & & 0.86 (0.10) \\ rMCC & 0.66 (0.19) & & 0.67 (0.25) & & 0.60 (0.27) \\ rCLUST & 0.84 (0.49) & & 0.89 (0.47) & & 0.97 (0.49) \\ \hline \end{tabular} \caption{Simulated Data: Sensitivity results for the proposed model with SDP on regression coefficients. Results are averaged over 50 replicated data sets with standard errors in parentheses.} \label{tab:sens} \end{table} \section{Conclusions} \label{sec:remarks} In this paper, we have investigated intensive longitudinal data, collected in a novel, smartphone-based smoking cessation study to better understand the relation between potential risk factors and smoking behaviors in the critical moments surrounding a quit attempt, using a semiparametric Bayesian time-varying effect modeling framework. Unlike standard TVEMs, our approach deconstructs the structure of the relations between risk factors and smoking behaviors over time, which aids in formulating hypotheses regarding dynamic relations between risk factors and smoking in the critical moments around a quit attempt. By performing variable selection on random effects, the approach delivers additional insights on how relations vary over time as well as how they vary across individuals. Furthermore, the use of non- and semiparametric prior constructions allows simultaneous variable selection for fixed and random effects while learning latent clusters of regression coefficients. As such, our model is designed to discover various forms of latent structures within the data without requiring strict model assumptions or burdensome tuning procedures. Results from our analysis have confirmed previously identified temporal relations between smoking behaviors and \textit{urge} to smoke, \textit{cigarette availability}, and \textit{negative affect}. They have also identified subject-specific heterogeneity in the effects of \textit{urge} to smoke, \textit{cigarette availability}, and \textit{motivation to quit}. Additionally, we have found that subjects differed in how they responded to the \textit{SmartT} treatment (compared to usual care), \textit{interacting with a smoker}, and being \textit{bored} over time. This has practical relevance as researchers can use this information to design adaptive interventions that prioritize targeting risk factors based on their relative strength of association at a given moment. They also reinforce the importance of designing dynamic intervention strategies that are adaptive to subjects' current risk profiles. Throughout this work, we have demonstrated how our method is well-suited to aide the development and evaluation of future JITAI strategies targeting smoking cessation using mHealth data. The existing \textit{SmartT} algorithm delivers treatment based on the presence of six lapse triggers, which are weighted based on their relative importance in predicting risk of lapse \citep{businelle2016ecological}. The results of this study allow for a more dynamic algorithm that takes into account not only the time-varying relationships between psychosocial and environmental variables and smoking lapse, but the different ways in which individuals experience a quit attempt. For example, the results suggest that providing momentary support to cope with \textit{urge} to smoke and \textit{negative affect} may be more useful if delivered in the early stages of a quit attempt, but become less important by week 4 post-quit. However, messages that address \textit{cigarette availability}, \textit{alcohol consumption}, and \textit{motivation to quit smoking} may be a more important focus for the entire quit attempt. Although the findings for this small sample may not be generalizable to larger, more diverse populations, these methods are the next step in developing a personalized smoking risk algorithm that can inform highly specific, individualized treatment to each smoker. It is important to note that selection of a risk factor by our proposed method (or any variable selection technique), does not imply clinical significance. Notably, the point-wise credible intervals often contained odds ratios of one and most risk factors were only influential for brief moments throughout the study period. While these results highlight the importance of understanding risk factors' dynamic relations with smoking to design tailored intervention strategies, we recommend using our method for hypothesis generation in practice and conducting confirmatory studies before generalizing results. Compliance rates for EMA studies typically range between 70\% and 90\%, with a recommended threshold of 80\% \citep{jones2006continuous}. In our case study, the compliance rate was 84\%. Additionally, 97.3\% of all assessments were completed once initiated, and subjects were unable to skip questions within an assessment. Since subjects were assessed multiple times per day, nonresponse was attributed more to situational context (e.g., driving) than smoking status. Thus for this study, we found the missing completely at random assumption for missing observations justified. However, future studies may consider the development of advanced analytical methods for EMA data sets that can handle different types of missingness assumptions and other potential biases, such as social desirability bias. In this analysis, we focus on time-varying effects due to their recent popularity in smoking behavior research \cite{tan2012time,shiyko2012using,vasilenko2014time,koslovsky2017time,lanza2013advancing,shiyko2014modeling}. A promising alternative for investigating the complexity of smoking behaviors around a quit attempt is the varying index coefficient model, which allows a covariate's effect to vary as a function of multiple other variables \citep{ma2015varying}. By incorporating variable selection priors, researchers could identify which variables are responsible for modifying a covariate's effect. Oftentimes behavioral researchers are interested in exploring other forms of latent structure, such as clusters of individuals who respond similarly to treatments or have similar risk profiles over time. Taking advantage of the flexibility and efficiency of our approach, future work could extend our core model to address these research questions by recasting it into a mixture modeling framework. In addition, while we have developed our method for binary outcomes due to their prevalence in smoking behavior research studies, our approach is easily adaptable to other data structures found within and outside of smoking behavior research, such as time to event data \citep{sha2006bayesian} and continuous outcomes. While our method borrows information across regression coefficients, we avoided imposing structure among covariates via heredity constraints, which restrict the model space for higher order terms depending on the inclusion status of the lower order terms that comprise them. Researchers interested in extending our approach to accommodate these, and other forms of, hierarchical constraints may adjust the prior probabilities of inclusion \citep{chipman1996bayesian}. Lastly, while we were hesitant to present variable selection results for PGHS, due to the limited understanding of global-local priors for non-Gaussian distributions, this showed good results in simulations. Furthermore, when applied to the case study data, we obtained promising predictive performance (i.e., $\widehat{\mbox{epld}}_{HS} = -2955.5$) that warrant future investigation of its theoretical properties. \section*{Acknowledgements} Matthew Koslovsky is supported by NSF via the Research Training Group award DMS-1547433. \section*{Supplementary Material} $\mbox{ }$ \\ \noindent \textbf{R-package for PGBVS:} \\ R-package PGBVS contains code to perform the methods described in the article. The package also contains functionality for reproducing the data used in the sensitivity and simulation studies and for posterior inference. The R package is located at \url{https://github.com/mkoslovsky/PGBVS}. \vspace{1cm} \noindent \textbf{Supplementary Information:} \\ This file contains a description of the full joint distribution of our model with a graphical representation, a detailed description of our proposed MCMC algorithm with and without SDP priors, and derivations for the prior marginal likelihood used to sample latent cluster assignments. Additionally, we include details of the goodness-of-fit analysis for the case study. \bibliographystyle{imsart-nameyear}
{'timestamp': '2020-09-22T02:01:58', 'yymm': '2009', 'arxiv_id': '2009.09034', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09034'}
arxiv
\section{Introduction} There have been many developments in estimating the average treatment effects (ATE). In various fields, the estimation of the ATE provides a central insight on the causal effect of a treatment (e.g., an intervention, an environmental policy, and so on) on an outcome, on average for the whole population. However, in addition to the ATE, it is critically important to identify subpopulations of the population that would benefit the most from a treatment and/or would be most vulnerable to an environmental exposure. In the context of air pollution, it is deemed important to public health to identify the subpopulations that are most vulnerable, so that effective interventions can be put in place to mitigate adverse health effects \citep{lee2018discovering}. % There is extensive literature on assessing heterogeneity of causal effects that is based on estimating the conditional average treatment effect (CATE). For each combination of covariates $\mathbf{X} = \mathbf{x}$ (i.e., subset of the features space), the CATE can be estimated with the same set of the causal assumptions that are needed for estimating the ATE \citep{athey2016}. Under the same identification assumptions, earlier works on estimating CATE rely on nearest-neighbor matching and kernel methods \citep{crump2008nonparametric, lee2009non}. \cite{wager2018estimation} discuss that these approaches may fail in handling a large number of covariates. This issue is often referred to as \textit{curse of dimensionality} \citep{bellman1961adaptive, robins1997toward}. Recently, other nonparametric approaches facilitate machine learning methods such as Random Forest \citep{breiman2001random} and Bayesian Additive Regression Tree (BART) \citep{chipman2010bart}. These approaches have been successful when the number of features is large. For instance, in their seminal contributions, \cite{foster2011subgroup} and \cite{hill2011bayesian} used forest-based algorithms for the prediction of the missing potential outcomes. In a similar spirit, \cite{hahn2020bayesian} proposed a BART-based approach but with a novel parametrization of the outcome surfaces. In more recent contributions, \cite{wager2018estimation} and \cite{athey2019generalized} developed forest-based methods for the estimation of heterogeneous treatment effects. They also provide asymptotic theory for the conditional treatment effect estimators and valid statistical inference. Despite the success in accurately estimating the CATE using machine learning methods, these tree ensemble methods offer little guidance about which covariates or, even further, subpopulations (i.e., subsets of the features space defined by multiple covariates) bring about treatment effect heterogeneity. Outputs/results obtained from existing methods are hard to interpret by human experts because parametrizations of the covariate space are complicated. This issue is well-known as \textit{lack of interpretability}. Increasing model interpretability is key to understanding and furthering human knowledge. However, effort to improve interpretability is so far lacking in the current causal inference literature dealing with the study of treatment effect heterogeneity. In this paper, we propose a novel Causal Rule Ensemble (CRE) method that ensures interpretability, while maintaining a high level of accuracy in estimation. The CRE method uses decision rules obtained from multiple trees, selects a key subset of rules to identify subpopulations contributing to heterogeneous treatment effects, and estimates CATE for each selected rule. Interpretability is usually a qualitative concept, and often defined as the degree to which a human can understand the cause of a decision or consistently predict the results of the model \citep{miller2018explanation, kim2016examples}. Decision rules are ideal for this non-mathematical definition of interpretability. A decision rule consists of simple \textit{if-then} statements regarding several conditions and corresponds to a specific subpopulation. A handful number of decision rules, called \textit{causal rules}, can be chosen by using high performance machine learning techniques, but are still easy to understand. We achieve the following three main goals: (1) discovering de novo causal rules that lead to heterogeneity of causal effects; (2) providing valid inference and large sample properties about CATE with respect to the newly discovered rules; and (3) assessing sensitivity to unmeasured confounding bias for the rule-specific causal effects. To do so, we follow \cite{athey2016}, and rely on a sample-splitting approach that divides the total sample into two smaller subsamples: one for discovering a set of interpretable decision rules that could lead to treatment effect heterogeneity (i.e., discovery sample) and the other for estimating the rule-specific treatment effects (i.e., inference sample). We also tailor a sensitivity analysis method proposed by \cite{zhao2019sensitivity} to assess the robustness of the rule-specific treatment effects to unmeasured confounding. Furthermore, the CRE method has several other advantages besides interpretability and estimation accuracy. It allows practitioners to represent treatment effect heterogeneity in a more flexible and stable way. This stability provides higher standards of replicability. Also, it is a powerful tool to disentangle the effect modifiers (namely, drivers of causal effect heterogeneity) from measured confounders. The reminder of the paper is organized as follows. In Section \ref{sec:interpretability}, we introduce the main definitions of CATE and interpretable decision rules. In Section \ref{sec:discovery}, we describe the algorithm used for the discovery of causal rules. Section \ref{sec:inference} introduces our innovative ideas regarding estimation and sensitivity analysis. In Section \ref{sec:simulations}, we conduct simulations studies. In Section \ref{sec:application}, we apply the proposed method to the Medicare Data. Section \ref{sec:discussion} discusses the strengths and weaknesses of our proposed approach and areas of future research. \section{Treatment Effect Heterogeneity, Interpretability and Sample-Splitting}\label{sec:interpretability} \subsection{Causal Treatment Effects} Suppose there are $N$ subjects. For each subject, let $Y_i$ be an outcome, $Z_i$ be a binary treatment, and $\mathbf{X}_i$ be a $K$-dimensional vector of covariates. Following the potential outcome framework \citep{neyman1923, rubin1974estimating}, we define two potential outcomes $Y_i(1)$ and $Y_i(0)$ as a function of the treatment assigned to each subject $i$ (i.e., $Y_i(Z_i)$). $Y_i(1)$ is the potential outcome for unit $i$ under treatment, while $Y_i(0)$ is the potential outcome under control. The fundamental problem is that the treatment effect $\tau_i = Y_i(1) - Y_i(0)$ cannot be observed from a given sample $(Y_i, Z_i, \mathbf{X}_i)$ since we can observe only one of the potential outcomes \citep{holland1986statistics}. Since either $Z_i=1$ or $Z_i=0$ is realized, the corresponding potential outcome $Y_i(Z_i)$ is observed, and the other potential outcome $Y_i(1 - Z_i)$ is \textit{counterfactual} and always missing. For instance, if $Z_i=1$, we can observe $Y_i(1)$, but cannot observe $Y_i(0)$. What we can observe is the realization of $Y_i$ that can be formalized as $Y_i = Z_i Y_i(1) + (1-Z_i)Y_i(0)$. It is extremely difficult to estimate $\tau_i$ as this quantity is never observed in reality. Instead, we consider the conditional average treatment effect (CATE) $\tau(x)$ defined as $\tau(x) = \mathbb{E} \left[Y_i(1) - Y_i(0) | \mathbf{X}_i = x \right]$ and the average treatment effect (ATE) defined as $\tau = \mathbb{E}_{X}[\tau(x)]$. Although $\tau(x)$ cannot be observed, $\tau(x)$ can be estimated under the assumption of no unmeasured confounders \citep{rosenbaum1983central}, \begin{equation} \left(Y_i(1), Y_i(0) \right) \independent Z_i \>\vert\> \mathbf{X}_i. \label{assump:unconfounded} \end{equation} This assumption means that the two potential outcomes depend on $\mathbf{X}_i$, but are independent of $Z_i$ conditioning on $\mathbf{X}_i$. By using the propensity score $e(x) = \mathbb{E}[Z_i \vert \mathbf{X}_i=x]$ \citep{rosenbaum1983central}, the CATE $\tau(x)$ can be identified as \begin{equation} \tau(x) = \mathbb{E} \left[\left( \frac{Z_i}{e(x)} - \frac{1-Z_i}{1-e(x)} \right) Y_i \>\vert\> \mathbf{X}_i =x \right]. \label{identification1} \end{equation} However, in practice we do not know whether a considered set $\mathbf{X}_i$ is sufficient for the assumption~\eqref{assump:unconfounded}. When there exists a source of unmeasured confounding, this assumption is violated, and the identification results do not hold. Sensitivity analysis provides a useful tool to investigate the impact of unmeasured confounding bias, which will be discussed in Section~\ref{ssec:sa}. \subsection{Interpretability and Decision Rules} Our primary goal is to provide an interpretable structure of $\tau(x)$ (discovery of treatment effect heterogeneity) and then estimate $\tau(x)$ in an efficient and precise manner (estimation of treatment effect heterogeneity). The functional form of $\tau(x)$ is not known, and may have a complicated structure varying across subgroups. A complex model can be considered to get a better estimate of $\tau(x)$, but such model may mask the truly informative structure of $\tau(x)$. Instead, it is possible to ``extract" (or ``approximate'') important subspaces of $\mathbf{X}$ that are responsible for the variation of $\tau(x)$, using a sparse representation of the conditional average treatment effect (CATE) defined by parsimonious subsets of the covariates space \citep{imai2013estimating}. The extracted subspaces may not perfectly describe the treatment effect heterogeneity, but provide a concise and informative summary, thus are more interpretable. This is often referred to as \textit{trade-off} between interpretability and accuracy. More specifically, weighing too much on achieving high accuracy in the estimation of the causal effect for a given covariate-profile generally comes at the cost of compromising interpretability. On the other hand, trying to improve interpretability might lead to too simple structures that are not representative of the true $\tau(x)$ structure, which in turn may reduce the statistical precision. It is important to find a good balance between interpretability and estimation accuracy. Our work focuses on finding this balance and, furthermore, improving interpretability while minimizing the loss of estimation accuracy. To do so, we consider decision rules as base learners, and describe the heterogeneous treatment effect as a linear combination of these learners. \begin{figure}[t!] \centering \begin{tikzpicture}[level distance=60pt, sibling distance=10pt, edge from parent path={(\tikzparentnode) -- (\tikzchildnode)}] \tikzset{every tree node/.style={align=center}} \Tree [.{Total sample} \edge node[auto=right,pos=.6]{Male$=0$}; {Female} \edge node[auto=left,pos=.6]{Male$=1$};[.{Male} \edge node[auto=right,pos=.6]{Young$=0$}; {Old male} \edge node[auto=left,pos=.6]{Young$=1$}; {Young male} ]] \end{tikzpicture} \caption{An example tree.} \label{fig:example_tree} \end{figure} We first introduce decision rules with formal definition. Let $S_k$ be the set of possible values of the $k$th covariate and $s_{k, m} \subseteq S_k$ be a specific subset corresponding to the $m$th rule. Then, each decision rule $r_m(x)$ can be represented as \begin{equation*} r_m(x) = \prod_{k: s_{k, m} \neq S_k} \mathbbm{1}(x_k \in s_{k, m}). \end{equation*} Define the covariate space $D = S_1 \times \cdots \times S_K$ as a Cartesian product of $K$ sets. A vector of covariates $\mathbf{X}_i$ must lie in $D$ for all $i$. Also, we define the subset $D_m$ corresponding to the rule $r_m(x)$, $D_m = s_{1, m} \times \cdots \times s_{K, m}$. Then, $r_m(x)=1$ if $x \in D_m$ and $r_m(x)=0$ otherwise. Decision rules as base learners are easily obtained from decision trees. For example, Figure~\ref{fig:example_tree} shows a toy example. The decision tree in this figure consists of several decision rules. Four decision rules can be extracted from this tree. For example, the young male group can be expressed as $r_4 = \mathbbm{1}( \text{Male} = 1) \times \mathbbm{1}( \text{Young} = 1)$. Other decision rules are listed in Table~\ref{tab:rules_example}. We note that $r_2$ represents the internal node of the male group. Each decision rule corresponds to either internal or terminal nodes (leaves) except for the initial node (root). Including rules corresponding to internal nodes may increase the total number of decision rules to consider, but it can be helpful not to miss important decision rules that are essential for describing the variability of $\tau(x)$. \begin{table} \centering \caption{Extracting rules from the example tree in Figure~\ref{fig:example_tree}} \begin{tabular}{cc} \hline Rules & Conditions \\ [0.05cm] \hline $r_1$ & Male$=0$ \\ $r_2$ & Male$=1$ \\ $r_3$ & Male$=1$ \& Young$=0$ \\ $r_4$ & Male$=1$ \& Young$=1$ \\ \hline \end{tabular} \label{tab:rules_example} \end{table} \subsection{Sample Splitting} Analysis of heterogeneous treatment effects or subgroup analysis are typically conducted for subgroups defined \textit{a priori} to avoid the cherry-picking problem that reports only subgroups with extremely high/low treatment effects \citep{cook2004subgroup}. However, defining subgroups a priori requires a fairly good understanding of the treatment effect, probably from previous literature. On top of that, another problem is that researchers may miss unexpected subgroups. To overcome these limitations, we propose to use data-driven machine learning approaches combined with honest inference \citep{athey2016}. In particular, we use a sample-splitting approach that divides the total sample into two smaller subsamples \citep{athey2016, lee2018discovering}: (1) discovery and (2) inference subsamples. By using the discovery subsample, decision rules are generated, and among them, a few candidates are selected. These selected rules are regarded as rules given a priori when making statistical inference using the remaining inference subsample. The main advantage of sample-splitting is to provide \textit{transparency} that is foundational to reproducibility and replicability. The discovery step is performed only using the data in the discovery subsample, which enables researchers to avoid damaging validity of a later inference step. Also, this separated discovery step can be considered as a pre-analysis step to increase efficiency. When causal rules selected by the discovery step represent treatment effect heterogeneity well, in the context of estimation, methods with sample-splitting often perform as good as methods without sample-splitting, or perform better in high-dimensional settings. \begin{algorithm}[h] \caption{Overview of the Causal Rule Ensemble (CRE) Method \label{alg:dis}} \begin{itemize} \item Randomly split the total sample into two smaller samples: the discovery and inference subsamples \item The Discovery Step (performed on the discovery subsample): \begin{enumerate} \item Rule generation (Section~\ref{ss:rule_gen}) \begin{enumerate} \item Estimate $\tau_i$ using existing methods for estimating the CATE \item Use $(\hat{\tau}_i, \mathbf{X}_i)$ to generate a collection of trees through tree-ensemble methods \item From the collection, extract decision rules $r_j$by removing duplicates \end{enumerate} \item Rule regularization (Section~\ref{subsection:rulediscovery}) \begin{enumerate} \item Generate a new vector $\tilde{\mathbf{X}}_i^*$ whose $j$th component corresponds to rules $r_j$ \item Apply stability selection to $(\hat{\tau}_i, \tilde{\mathbf{X}}_i^*)$ and select potentially important decision rules $\tilde{\mathbf{X}}$. \end{enumerate} \end{enumerate} \end{itemize} \begin{itemize} \item The Inference Step (performed on the inference subsample): \begin{enumerate} \item Estimate the CATE for the selected decision rules represented by $\tilde{\mathbf{X}}$ (Section~\ref{ss:estimation}) \item Sensitivity analysis for the estimated CATE from the previous step (Section~\ref{ssec:sa}) \end{enumerate} \end{itemize} \end{algorithm} \section{Discovery Step: Which Subgroups Are Potentially Important?}\label{sec:discovery} This section illustrates a step for discovering potentially important subgroups in terms of decision rules. In particular, we introduce a generic method that creates a set of decision rules and identifies the rule-generated structure. The discovery step consists of two parts: (1) rule generation and (2) rule regularization. For rule-generation, we create base learners that are building blocks to describe the heterogeneous structure of treatment effects. The rule regularization is used to choose \textit{necessary} bulding blocks, and needed for interpretability and stability. \subsection{Rule Generation} \label{ss:rule_gen} We use decision rules as base learners. Decision rules can be externally specified by using prior knowledge. However, we propose to employ a data-driven approach that uses hundreds of trees and extracts decision rules. This approach overcomes two drawbacks that classical subgroup analysis approaches have: (1) they strongly rely on the subjective decisions on which are the heterogeneous subpopulations to be investigated; and (2) they fail to discover new rules other than the ones that are \textit{a priori} defined by the researchers. To create base learners for $\tau(x)$, we estimate $\tau_i$ first. This estimation is not considered for making inference, but designed for exploring the heterogeneous treatment effect structure. Many different approaches for the estimation of $\tau(x)$ can be considered. There has been methodological advancement in directly estimating $\tau(x)$ by using machine learning methods such as Causal Forest \citep{wager2018estimation} or Bayesian Causal Forest (BCF) \citep{hahn2020bayesian}. The BCF method directly models the treatment effect such as $\tau_i = m_0(\mathbf{X}_i; \hat{e}) + \alpha(\mathbf{X}_i; \hat{e}) Z_i$ using the estimated propensity score $\hat{e}(\mathbf{X}_i)$. \cite{hahn2020bayesian} shows that BCF produces precise estimates of $\tau(x)$. This evidence is consistent with recent works showing an excellent performance of Bayesian machine learning methodologies in causal inference scenarios \citep{hill2011bayesian, hahn2018atlantic, logan2019decision, bargagli2019heterogeneous, starling2019targeted, nethery2019estimating}. The BCF method can be applied to the discovery sample to estimate $\tau_i$. We denote such estimates with $\hat{\tau}_i^{BCF}$. Alternative approaches for the estimation of $\tau(x)$ are discussed in Appendix \ref{Appendix:comparison}. Here, we want to highlight that the simulations' results show that the performance of the CRE algorithm in discovering the true causal rules is higher when we use BCF to estimate $\tau(x)$ (additional details on these simulations are provided in Appendix \ref{Appendix:comparison}). Once the unit level treatment effect $\hat{\tau}_i$ is obtained, one can fit a decision tree using the data $(\hat{\tau}_i, \mathbf{X}_i)$. After fitting a tree, decision rules can be extracted as discussed above. However, using a single tree is neither an efficient nor a stable way to find important decision rules. This is due to two main factors, the \textit{greedy} nature of tree-based algorithms and their lack of flexibility. Binary trees are greedy algorithms as they do not subdivide the population based on the overall best splits (the set of splits that would lead to the minimization of the overall criterion function), but they pick the best split at each step (the one that minimizes the criterion function at that particular step)\footnote{Optimal trees \citep{bertsimas2017optimal} accommodate for this shortcoming at the cost of an extremely higher computational burden.}. Moreover, binary trees may not spot \textit{simultaneous} patterns of heterogeneity in the data because of their binary nature. Imagine that the treatment effect differs by sex and high school diploma. The tree-based algorithm may be able to spot only one of the two drivers of heterogeneity if one affects the treatment effect more than the other. Even when both the heterogeneity drivers are discovered they are spotted in a suboptimal way as an interaction between the two variables (i.e., women with a high school diploma, men with no diploma, etc). To accommodate for these shortcomings of single trees, tree ensemble methods such as Random Forest \citep{breiman2001random} and Gradient Boosting \citep{friedman2001greedy} can be applied to obtain a collection of trees. \cite{nalenz2018tree} discuss that boosting and Random Forest are different in nature, thus using both approaches can generate a wider set of decision rules. Even after removing duplicate rules, this will lead to a more diverse set of candidate rules, thus will increases the probability to capture important rules. We follow \cite{friedman2008predictive} and \cite{nalenz2018tree} to use the same settings of the tuning parameters for gradient boosting and Random Forest. Also, we note that one should avoid using too lengthy (i.e., many conditions) or too many decision rules, which results in reducing interpretability. \subsection{Rule Regularization and Stability Selection} \label{subsection:rulediscovery} Denote $r_{m}(x)$ as the generated rules from Section~\ref{ss:rule_gen}, with $m=1, \ldots, M^*$. Since each rule $r_{m}(x)$ indicates whether $x$ satisfies the rule or not, it can take a value either 0 or 1. Define $\tilde{\mathbf{X}}^*$ as a new matrix whose columns are the decision rules. The number of rules, $M^*$, is usually larger than $K$ and depends on how heterogeneous $\tau(x)$ is. Although the original dataset $\mathbf{X}$ is not high-dimensional, $\tilde{\mathbf{X}}^*$ can be high-dimensional. The set of the generated rules is a set of potentially important rules. It can contain actually important decision rules that describe the true heterogeneity in the treatment effects. However, insignificant rules may be contained in the set. Then, rule selection is applied to distinguish between few important rules and many insignificant ones. This regularization step improves understanding of the heterogeneity and increases efficiency. Such step improves interpretability: if too many rules are selected, this information may be too complex to understand. We consider the following linear regression model of the form, \begin{equation} \tau(x) = \beta_0 + \sum_{m=1}^{M^*} \beta_m r_m(x) + \epsilon \label{eqn:model1} \end{equation} Since a linear model is considered, the model \eqref{eqn:model1} lends a familiar interpretation of the coefficients $\{ \beta_m\}_{0}^{M^*}$. Using this linear model, one can employ the following penalized regression to select important rules: \begin{equation} \underset{\beta_m}{\mathrm{argmin}} \bigg\{\beta_0 + \sum_{m=1}^{M^*} \beta_m r_m(x) \bigg\} \text{ subject to } ||\beta_m||_p\leq \lambda \label{eqn:modellasso} \end{equation} where $\lambda$ is the regularization parameter and $||\cdot||_p$ is the $l_p$-norm. However, variable selection has been known as a notoriously difficult problem. The Least Absolute Shrinkage and Selection Operator (LASSO) estimator \citep{tibshirani1996regression} has been popular and widely used over the past two decades in order to solve the problem in~\eqref{eqn:modellasso} by employing the $l_1$-norm ($\sum_{m=1}^{M^*}|\beta_m|$). The usefulness of this estimator among other penalization regression methods is demonstrated in various applications \citep{su2016identifying, belloni2016inference, chernozhukov2016locally, chernozhukov2017double}. Using a regularization parameter $\lambda$, we can see that the estimate $\hat{\bm{\beta}}$ shrinks toward to zero as $\lambda$ increases, which provides a sparse structure close to the true model. Consistency of LASSO variable selection has been studied in \cite{zhao2006model} and others. However, the biggest challenge is to choose a proper value of $\lambda$ for consistent selection. Cross-validation is usually accompanied to choose $\lambda$. However, it may fail for high-dimensional data \citep{meinshausen2006high}. Stability selection \citep{meinshausen2010stability} can be used to enhance the performance of the LASSO estimator. Roughly speaking, by using a subsampling scheme, selection probabilities of variables (decision rules in our paper) can be estimated. Given two parameters (i.e., cut-off threshold and the average number of selected variables), variable selection can be done in a comparatively robust and transparent way. Also, \cite{meinshausen2010stability} discussed that the solution of stability selection depends little on the initial regularization chosen, which is a desirable feature when selecting decision rules. Among initially generated $M^*$ decision rules, we assume that $M \> (\text{with } M <\!\!< M^*)$ decision rules are selected as an output from the discovery procedure. Then, we can define $\tilde{\mathbf{X}}$ as the matrix containing only the selected decision rules. Figure \ref{fig:trees} depicts the intuition behind these steps of rules discovery and selection. The Figure shows a simple forest composed of just five trees. Each node of each tree (with the exclusion of the roots) represents a causal rule (\textit{rules' discovery}), while the nodes highlighted in red represent the causal rules that are selected by the stability selection methodology (\textit{rules' selection}). \begin{figure}[H] \centering \includegraphics[width=1\textwidth]{ensemble_of_trees.jpg} \caption{Rules' discovery and selection in a simple forest.} \label{fig:trees} \end{figure} \section{Inference Step: Which Subgroups Are Really Different?}\label{sec:inference} \label{s:inference} Using the rules that were discovered and then selected in the discovery step, the remaining inference sample is used to make inference. We propose a generic approach to estimate the rule-specific treatment effect, and compare it with existing approaches. Furthermore, we propose a new sensitivity analysis method to assess the impact of unmeasured confounding bias on causal conclusion. \subsection{Estimating the subgroup-specific treatment effect} \label{ss:estimation} Decision rules are selected through the discovery step by using the linear model in~\eqref{eqn:model1}, $$ \bm{\tau} = \tilde{\mathbf{X}} \bm{\beta} + \bm\epsilon $$ with $\mathbb{E}(\bm{\epsilon} | \mathbf{x}) = 0$ and $\text{var}(\bm{\epsilon} | \mathbf{x}) = \sigma^2 \bm{I}$. The main goal of this inference step is to estimate $\bm{\beta}$ that represents rule-specific treatment effects. We estimate these CATE for the subpopulations corresponding to the selected rules. We use ordinary least squares (OLS) to estimate $\bm{\beta}$. However, this estimator cannot be obtained as the unit level treatment effect $\bm{\tau}$ is not known. Hence, we define a new vector $\bm{\tau}^* = (\tau_1^*, \ldots, \tau_N^*)^T$ that is an estimate of $\bm{\tau}$. The newly defined $\bm{\tau}^*$ is just an intermediate value used in the inference step. Although $\bm{\tau}^*$ is an estimate, to distinguish this with the fitted value obtained by using the linear model, we save hat notation. The estimate $\tau_i^*$ can be viewed as an observable quantity with some sampling error although $\tau_i^*$ is an estimated value. The quantity $\tau_i^*$ can be represented by \begin{equation} \tau_i^* = \tau_i + u_i \>\>\> \text{where}\>\>\> \mathbb{E}(u_i | \mathbf{x}_i) =0 \text{ and } \text{var}(u_i | \mathbf{x}_i) = w_i. \label{eqn:tau_model} \end{equation} In general, the variance $w_i$ is not constant across all individuals. By combining it with the model~\eqref{eqn:model1}, the modified linear model is obtained as \begin{equation} \tau_i^* = \beta_0 + \sum_{j=1}^{M} \beta_j \tilde{X}_{ij} + \nu_i = \tilde{\mathbf{X}}_i \bm{\beta} + \nu_i, \label{eqn:model2} \end{equation} where $\tilde{\mathbf{X}}_i$ is the $i$th row of $\tilde{\mathbf{X}}$ and $\nu_i = \epsilon_i + u_i$. \cite{lewis2005estimating} considered a similar linear model like the model~\eqref{eqn:model2} and found via simulation studies that the OLS estimator performs well in many cases. Also, they found that since the error $\nu_i$ is not homoscedastic, considering White or Efron's heteroscedastic-consistent standard error can provide an efficient estimate. Based on these findings, we also consider the OLS estimator for $\bm{\beta}$ that can be defined as \begin{equation} \hat{\bm{\beta}} = (\tilde{\mathbf{X}}^T \tilde{\mathbf{X}})^{-1} \tilde{\mathbf{X}}^T \bm{\tau}^*. \label{eqn:estimate} \end{equation} Also, the fitted value $\hat{\bm{\tau}}$ is defined as $\hat{\bm{\tau}} = \tilde{\mathbf{X}} \hat{\bm{\beta}} = \tilde{\mathbf{X}}(\tilde{\mathbf{X}}^T \tilde{\mathbf{X}})^{-1} \tilde{\mathbf{X}}^T \bm{\tau}^*$. The intermediate vector $\bm{\tau}^*$ can be chosen in various ways. However, to validate our estimator~\eqref{eqn:estimate}, each $\tau_i^*$ has to be unbiased with finite variance. Given that the matrix $\tilde{\mathbf{X}}$ is fixed, we can prove that the estimator $\hat{\beta}_j, j=1, \ldots, M$ is a consistent estimator of $\beta_j$ that is the average treatment effect for the subgroups defined by the decision rule $r_j$ if $r_j$ is not included in another rule $r_{j'}$. \begin{theorem} If $\tau_i^*$ satisfies the model~\eqref{eqn:tau_model} (Condition 1) and $\mathbb{E}(\tilde{\mathbf{X}}_i^T \tilde{\mathbf{X}}_i) = \mathbf{Q}$ is a finite positive definite matrix (Condition 2), then the estimator $\hat{\bm{\beta}} = (\tilde{\mathbf{X}}^T \tilde{\mathbf{X}})^{-1} \tilde{\mathbf{X}}^T \bm{\tau}^*$ is a consistent estimator for $\bm{\beta}$. \label{thm:consistency} \end{theorem} An example is to use the inverse probability weighting (IPW) or stabilized IPW (SIPW) approaches. Both $\tau_i^* = \hat{\tau}_i^{IPW}$ and $\tau_i^* = \hat{\tau}_i^{SIPW}$ satisfy the model~\eqref{eqn:tau_model}. Therefore, the following corollary can be obtained from Theorem~\ref{thm:consistency}. \begin{corollary} The estimator $\hat{\bm{\beta}}^{(S)IPW} = (\tilde{\mathbf{X}}^T \tilde{\mathbf{X}})^{-1} \tilde{\mathbf{X}}^T \bm{\tau}^*$ where $\tau_i^* = \hat{\tau}_i^{(S)IPW}$ is consistent. \end{corollary} We need additional assumptions to prove asymptotic normality of $\hat{\bm\beta}$. For a general covariate matrix, the following three conditions are required: \begin{enumerate} \setcounter{enumi}{2} \item $\mathbb{E}(\tilde{\mathbf{X}}_{ij}^4) < \infty$; \item $\mathbb{E}(\nu_i^4) < \infty$; \item $\mathbb{E}(\nu_i^2 \tilde{\mathbf{X}}_i^T \tilde{\mathbf{X}}_i) = \bm\Omega $ is a positive definite matrix. \end{enumerate} Since $\tilde{\mathbf{X}}_{ij}$ is either 0 or 1 in our setup, Condition (3) is satisfied by design. The following theorem represents the asymptotic distribution of $\hat{\bm\beta}$. \begin{theorem} If Conditions (1)-(5) hold, then $$ \sqrt{N} (\hat{\bm\beta} - \bm{\beta}) \overset{d}{\to} \mathcal{N}(0, \mathbf{V}) \:\:\: \text{as} \:\:\: N \to \infty $$ where $\mathbf{V} = \mathbf{Q}^{-1} \bm\Omega \mathbf{Q}^{-1}$. \end{theorem} The variance $\mathbf{V}$ usually has to be estimated. The variance-covariance matrix estimator $\hat{\mathbf{V}}_n = \hat{\mathbf{Q}}^{-1} \hat{\bm\Omega} \hat{\mathbf{Q}}^{-1}$ can be obtained by the sandwich formula where $\hat{\mathbf{Q}} = n^{-1} \sum_{i=1}^{N} \tilde{\mathbf{X}}_i^T \tilde{\mathbf{X}}_i$, $\hat{\bm\Omega} = n^{-1} \sum_{i=1}^{N} \hat{\nu}_i^2 \tilde{\mathbf{X}}_i^T \tilde{\mathbf{X}}_i$ and $\hat{\nu}_i = \tau_i^* - \tilde{\mathbf{X}}_i {\hat{\bm\beta}}$. This estimator is robust and often called the White's estimator \citep{white1980heteroskedasticity}. There are other approaches to obtain a heteroscedasticity consistent covariance matrix, which is discussed in \cite{long2000using}. For small samples, Efron's estimator \citep{efron1982jackknife}, known as HC3 estimator, can be considered alternatively. Also, if the variance $w_i$ is known from the large sample properties of existing methods for obtaining $\tau_i^*$, then feasible generalized least squares estimators \citep{lewis2005estimating} can be considered. Instead of estimation, hypothesis testing for identifying true decision rules can be considered. As we will see in a simulation study, true rules representing treatment effect heterogeneity are discovered and selected with high probability. However, at the same time, non-true rules are selected with high probability. If one wants to know which rules are really important for describing treatment effect heterogeneity, variable selection can be used to choose a final model for treatment effect heterogeneity. For instance, the null hypothesis $H_0: \bm{\beta} = 0$ can be tested by using a Wald-type test statistic $T_n = n \hat{\bm\beta}^T \hat{\mathbf{V}}_n^{-1} \hat{\bm\beta}$. If $T_n > \chi_{M, 1-\alpha}^2$, $H_0$ is rejected. \subsection{Sensitivity Analysis} \label{ssec:sa} The validity and consistency of the estimator $\hat{\bm{\beta}}$ rely on the assumption of no unmeasured confounders and correct specification of the propensity score model. However, in reality, there is no guarantee that these assumptions are satisfied. Also, such assumptions are not directly testable. Without further knowledge about unmeasured confounding, it is extremely difficult to quantify how much bias can occur. Instead of attempting to quantify the degree of unmeasured confounding in the given dataset, it is more realistic to see how our causal conclusion will change with respect to various degrees of such bias. In this subsection, we propose a sensitivity analysis to examine the impact of potential violations of the no unmeasured confounding assumption. We introduced a generic approach for estimating $\bm{\beta}$ in Section~\ref{ss:estimation}. However, in our sensitivity analysis, we consider the special case where $\tau_i^*$ is estimated as $\hat{\tau}_i^{SIPW}$. Define $\mathbf{W} = (\tilde{\mathbf{X}}^T \tilde{\mathbf{X}})^{-1} \tilde{\mathbf{X}}^T$ that is a $M \times N$ matrix. Also, let $W_j$ be the $j$th row of $\mathbf{W}$ and $W_{ji}$ be the $(j, i)$ element of $\mathbf{W}$. Our estimator $\hat{\beta}_j$ is explicitly represented by \begin{align*} \hat{\beta}_j &= \hat{\beta}_j(1) - \hat{\beta}_j(0) \quad \text{where}\\ \hat{\beta}_j(1) &= \left[\frac{1}{N} \sum_{i=1}^{N} \frac{Z_i}{\hat{e}(\mathbf{X}_i)} \right]^{-1} \left[\sum_{i=1}^{N} \frac{ W_{ji} Y_i Z_i}{\hat{e}(\mathbf{X}_i)} \right] \\ \hat{\beta}_j(0) &= \left[\frac{1}{N} \sum_{i=1}^{N} \frac{1-Z_i}{1- \hat{e}(\mathbf{X}_i)} \right]^{-1} \left[\sum_{i=1}^{N} \frac{ W_{ji} Y_i(1-Z_i)}{1 - \hat{e}(\mathbf{X}_i)} \right]. \end{align*} We consider the marginal sensitivity model that was introduced by \cite{tan2006distributional} and \cite{zhao2019sensitivity}. Let the true propensity probability $e_0(\mathbf{x}, y; a) = \text{P}_0 (Z=1 | \mathbf{X} = \mathbf{x}, Y(a)=y)$ for $a \in \{0, 1\}$. If the assumption of no unmeasured confounders holds, this probability would be the same as $e_0(\mathbf{x}) = \text{P}_0 (Z=1 | \mathbf{X} = \mathbf{x})$ that is identifiable from the data. Unfortunately, this assumption cannot be tested since $e_0(\mathbf{x}, y; a)$ is generally not identifiable from the data. For each sensitivity parameter $\Lambda$ that will be introduced in detail later, the maximum deviation of $e_0(\mathbf{x}, y; a)$ from the identifiable quantity $e_0(\mathbf{x})$ is restricted, and sensitivity analysis is conducted for each $\Lambda$ to see if there is any qualitative change of our conclusion. In addition to this non-identifiability of $e_0(\mathbf{x}, y; a)$, there is another difficulty in obtaining $e_0(\mathbf{x})$ non-parametrically when $\mathbf{X}$ is high-dimensional. In practice, $e_0(\mathbf{x})$ is estimated by a parametric logistic model in the form of $e_{\gamma}(\mathbf{x}) = \exp(\gamma' \mathbf{x})/\{1 + \exp(\gamma' \mathbf{x})\}$ where $e_{\gamma_0}(\mathbf{x})$ can be considered as the best parametric approximation of $e_0(\mathbf{x})$, and used for sensitivity analysis. Our sensitivity model assumes that the true propensity probability $e_0(\mathbf{x}, y; a) = \text{P}_0 (Z=1 | \mathbf{X} = \mathbf{x}, Y(a)=y)$ satisfies: \begin{equation} e_0(\mathbf{x}, y; a) \in \mathcal{E}_{\gamma_0}(\Lambda) = \left\{ 0 < e(\mathbf{x}, y; a) < 1: 1/\Lambda \leq OR\{e(\mathbf{x}, y; a), e_{\gamma_0}(\mathbf{x})\} \leq \Lambda \right\} \quad \text{for } a \in \{0, 1\} \label{eqn:sensi_model} \end{equation} where $e_{\gamma_0}(\mathbf{x}) = \text{P}_{\gamma_0}(Z=1 | \mathbf{X} = \mathbf{x})$ and $OR\{e(\mathbf{x}, y; a), e_{\gamma_0}(\mathbf{x})\} = \{(1-e(\mathbf{x}, y; a)) \cdot e_{\gamma_0}(\mathbf{x})\}/ \{e(\mathbf{x}, y; a)\cdot(1- e_{\gamma_0}(\mathbf{x}))\}$. The deviation of $e_0(\mathbf{x}, y; a)$ is symmetric with respect to the parametrically identifiable quantity $e_{\gamma_0}(\mathbf{x})$, and the degree of the deviation is governed by the sensitivity parameter $\Lambda \geq 1$. When $\Lambda = 1$, $e_0(\mathbf{x}, y; a) = e_{\gamma_0}(\mathbf{x})$ for all $a$, which implies that there is no violations of the assumptions. If the propensity score model is correctly specified, $e_{\gamma_0}(\mathbf{x}) = e_0(\mathbf{x})$. Also, if there is no unmeasured confounder, $e_0(\mathbf{x}, y; a) = e_0(\mathbf{x})$. Therefore, under the assumptions of correct propensity score model and no unmeasured confounder, $e_0(\mathbf{x}, y; a) = e_{\gamma_0}(\mathbf{x})$. Our sensitivity model considers violations of both assumptions. This sensitivity analysis model resembles the model proposed by \cite{rosenbaum2002observational}. The connection between the two models is illustrated in Section 7.1 in \cite{zhao2019sensitivity}. \begin{algorithm}[t] \caption{Constructing the confidence interval of $\beta_j$ for each sensitivity parameter $\Lambda$ \label{alg:ci}} \begin{enumerate} \item Generate a matrix $\mathbf{W} = (\tilde{\mathbf{X}}^T \tilde{\mathbf{X}})^{-1} \tilde{\mathbf{X}}^T$ \item In the $\ell$th of $L$ iterations: \begin{enumerate} \item Generate a bootstrapped sample: $(Z_i^{(\ell)}, Y_i^{(\ell)}, \mathbf{X}_i^{(\ell)})_{i=1, \ldots, N}$. \item Generate transformed outcomes $\tilde{Y}_{ji}^{(\ell)} = W_{ji} Y_i^{(\ell)}$ for all $i$, where $W_{ji}$ is the $(j,i)$ element of $\mathbf{W}$. \item Reorder the index such that the first $N_1 = \sum_{i=1}^{N} Z_i^{(\ell)}$ units are treated with $\tilde{Y}_{j1} \geq \ldots \geq \tilde{Y}_{j, N_1}$ and the rest are control with $\tilde{Y}_{j,N_1+1} \geq \ldots \geq \tilde{Y}_{j, N}$ \item Compute an estimate $\hat{\gamma}^{(\ell)}$ by fitting the logistic regression with $(Z_i^{(\ell)}, \mathbf{X}_i^{(\ell)})$ \item Solve the following optimization problems: $$ \text{min or max} \frac{\sum_{i=1}^{N_1} \tilde{Y}_{ji}^{(\ell)}[1 + q_i \exp\{-\hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}] }{\sum_{i=1}^{N_1} [1 + q_i \exp\{ -\hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}]} - \frac{\sum_{i=N_1+1}^{N} \tilde{Y}_{ji}^{(\ell)}[1 + q_i \exp\{\hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}] }{\sum_{i= N_1+1}^{N} [1 + q_i \exp\{ \hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}]} $$ subject to $1/\Lambda \leq q_i \leq \Lambda$, for $1 \leq i \leq N$, and denote the minimum as $L_j^{(\ell)}$ and the maximum as $U_j^{(\ell)}$ \end{enumerate} \item Construct the $(1-\alpha)$-coverage confidence interval $[L_j, U_j]$ where $L_j = Q_{\alpha/2} \left( L_j^{(\ell)} \right)$ and $U_j = Q_{1 - \alpha/2} \left( U_j^{(\ell)} \right), \ell =1, \ldots, L$ \end{enumerate} \end{algorithm} The $(1-\alpha)$-coverage confidence interval of $\beta_j$ can be constructed by using the percentile bootstrap. First, we denote $W_{ji} Y_i$ by $\tilde{Y}_i^{j}$ and treat $\tilde{Y}_i^j$ as if it is an observed outcome, then the confidence interval for each $\beta_j$ can be constructed through the procedure in Algorithm~\ref{alg:ci}. Confidence intervals have at least $100(1-\alpha)$ \% coverage probability even in the presence of unmeasured confounding. The validity of the percentile bootstrap confidence interval $[L_j, U_j]$ can be proved by using Theorem 1 in \cite{zhao2019sensitivity}. In Step (2e) of Algorithm~\ref{alg:ci}, the optimization problem can be efficiently solved by separating two simpler optimization problems. The minimum is obtained when the first part $\frac{\sum_{i=1}^{N_1} \tilde{Y}_{ji}^{(\ell)}[1 + q_i \exp\{-\hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}] }{\sum_{i=1}^{N_1} [1 + q_i \exp\{ -\hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}]}$ is minimized and the second part $\frac{\sum_{i=N_1+1}^{N} \tilde{Y}_{ji}^{(\ell)}[1 + q_i \exp\{\hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}] }{\sum_{i= N_1+1}^{N} [1 + q_i \exp\{ \hat{\gamma}^{(\ell)} \mathbf{X}_i^{(\ell)} \}]}$ is maximized. For instance, the minimization of the first part is achieved at $\{q_i: q_i = 1/\Lambda \text{ for } i=1, \ldots, b, \> \text{and } q_i = \Lambda \> \text{ for } i= b+1, \ldots, N_1 \}$ for some $b$. To find the minimum, it is required to check every possible value of $b$, and the computational complexity is $O(N_1)$. See Proposition 2 in \cite{zhao2019sensitivity} for more details. \section{Simulation} \label{sec:simulations} In this section, we introduce two simulation studies to assess the performance of the CRE method. In the first simulation study, we evaluate the discovery step in terms of how well the method performs in discovering the true underlying decision rules. In the second simulation study, we evaluate the overall performance of both the discovery and inference steps in terms of estimation accuracy. \subsection{Simulation study: Rules Discovery}\label{subsec:rule_discovery} In order to evaluate the ability of CRE in the discovery step we run a series of simulations in which we assess how many times CRE can spot the true underlying decision rules. First, we assess the \textit{absolute} performance of CRE; then we compare its performance with the one of the Honest Causal Tree (HCT) method \citep{athey2016}. The HCT method is a causal decision tree algorithm and discovers disjoint decision rules through a single tree. In order to evaluate the ability of discovering decision rules we consider, among the discovered rules, how many times true rules are captured. As we discussed in Section \ref{sec:discovery}, to apply the CRE method, many approaches can be considered to estimate the individual treatment effect $\tau_i$. We have found via simulation studies that the BCF approach has better performance than other approaches such as $\hat{\tau}_i^{IPW}$ or BART (in Appendix \ref{Appendix:comparison}, we show the comparative performances of BCF, BART, IPW and outcome regression). Thus, in this simulation study, we implement the BCF approach for the CRE method. We call this version of the CRE method \textit{CRE-BCF}. Also, for the data-generating process, we generate the covariate matrix $\mathbf{X}$ with 10 binary covariates from $X_{i1}$ to $X_{i,10}$. The binary treatment indicator $Z_i$ is drawn from a binomial distribution, $Z_i \sim \textit{Binom}(\pi_i)$ where $\pi_i = \text{logit}(-1 + X_{i1} - X_{i2} + X_{i3})$. Finally, the output is generated as $y = y_0\cdot (1 - z_i) + y_1\cdot z_i + f(\mathbf{X})$ where $f(\mathbf{X})$ is a linear function of the confounders $X_{i1}, X_{i2} \text{ and } X_{i3}$. We consider three factors: (i) the number of decision rules, (ii) the effect size $k$ from 0 to 2, and (iii) sample size $N=1000$ or 2000. In order to produce a more meaningful comparison between CRE-BCF and HCT, we restricted the data generating process to causal rules that are representable through a binary tree. In particular, the potential outcomes are generated by $Y_i(0) \sim N(X_{i1} + 0.5 X_{i2} + X_{i3}, 1)$ and $Y_i(1) = Y_i(0) + \tau(\mathbf{X}_i)$. For the case of two causal rules, $\tau = \tau(\mathbf{X}_i) = k$ if $X_{i1}=0,X_{i2}=0$, $\tau = -k$ if $X_{i1}=1, X_{i2}=1$, and $\tau=0$ otherwise. While in the case of four causal rules we have that $\tau = k$ if $(X_{i1}, X_{i2}, X_{i3}) = (0, 0, 1)$, $\tau = 2k$ if $(X_{i1}, X_{i2}, X_{i3}) = (0, 0, 0)$, $\tau = -k$ if $(X_{i1}, X_{i2}, X_{i3}) = (0, 1, 0)$, $\tau = -2k$ if $(X_{i1}, X_{i2}, X_{i3}) = (0, 1, 1)$ and $\tau=0$ otherwise. This scenario was chosen because it is the most favourable to the HCT algorithm. Moreover, we introduce variations in the set of covariates that are used to define the causal rules (we refer to these variables as effect modifiers) by switching $(X_1, X_2, X_3)$ with $(X_8, X_9, X_{10})$. This change represents the case where the effect modifiers are different from the confounders. Investigating this scenario is important since confounders may affect the ability of the algorithm to spot the correct causal rules. Figures \ref{figure:CRE-BCF_vs_HCT} and \ref{figure:CRE-BCF_vs_HCT_modification} depict the results in the case with the same variables for both confounders and effect modifiers and in the case of different variables, respectively. \begin{figure}[] \centering \includegraphics[width=1\textwidth]{CRE-BCF_vs_HCT.pdf} \caption{Average number of correctly discovered rules in the case where the same variables are used as confounders and effect modifiers. The first column depicts the case of two true rules while the second column the case of four true rules. In the first row the sample size is 1,000 while in the second it is 2,000.} \label{figure:CRE-BCF_vs_HCT} \end{figure} \begin{figure}[] \centering \includegraphics[width=1\textwidth]{CRE-BCF_vs_HCT_modification.pdf} \caption{Average number of correctly discovered rules in the case where the confounders are different from the effect modifiers. The first column depicts the case of two true rules while the second column the case of four true rules. In the first row the sample size is 1,000 while in the second it is 2,000.} \label{figure:CRE-BCF_vs_HCT_modification} \end{figure} When $(X_1, X_2, X_3)$ are both confounders and effect modifiers, CRE-BCF consistently outperforms HCT, while in the other scenario CRE-BCF is still performing better but the performance gap is narrower especially in the case with two true causal rules. In both the scenarios, the gap is wider as the number of true rules is four. This shows that HCT is consistently unable to detect all the four true rules. These simulations show that the usage of CRE-BCF results in an increase in the detection of the true causal rules especially when there is overlap between the confounders and effect modifiers. This is a very interesting feature of CRE-BCF as similar scenarios are very likely in real-world applications. For instance, it can be the case in pollution studies, that income is a confounder as poorer people live in neighbours with higher levels of pollution, and also an effect modifier as poorer people may have worst living conditions and, in turn, experience higher negative effects from pollution. Also, it is important to note that CRE provides a smaller number of detected rules (4 to 7) as compared to HCT (10 to 84). \subsection{Simulation study: Rule-specific Effects Estimation}\label{subsection:estimation} In this subsection, we evaluate the overall performance of the CRE method including both the discovery and inference steps. In the previous simulation study, we found that the BCF approach shows a great performance in discovering underlying decision rules. Also, it has been shown that the BCF approach estimates $\tau_i$ with great accuracy heuristically. Thus, in this simulation study, we use the BCF approach for both discovery and inference steps when applying the CRE method. In particular, in the discovery step, $(\mathbf{X}_i, \hat{\tau}_i^{BCF})$ is used in order to discover and select important decision rules. During the inference step, the intermediate variable $\tau_i^*$ is estimated by using the BCF approach (CRE-BCF). To compare, we consider a BCF approach that does not use the sample-splitting technique, and we call this \textit{original-BCF}. The original BCF provides the estimate $\hat{\tau}_i$, but does not provide an interpretable form of the heterogeneous treatment effects. On the contrary, the CRE-BCF not only provides a set of decision rules that significantly increase interpretability of findings, but also provides the estimate with respect to the discovered structure. It is difficult to compare the two methods in terms of interpretability, so in this simulation study, we compare them in terms of estimation accuracy. \cite{athey2016} recommends to use a (50\%, 50\%) ratio between the discovery and inference samples for sample-splitting, but \cite{lee2018discovering} shows through simulation studies that (25\%, 75\%) has better performance than (50\%, 50\%). We investigate six different ratios from (10\%, 90\%) to (50\%, 50\%). Note that the original-BCF can be considered as an extreme case of (0\%, 100\%). \begin{table} \centering \caption{RMSE comparison between the CRE and BCF methods} \begin{tabular}{c|cccccc|c} \hline & \multicolumn{7}{c}{Method} \\ $N$ & CRE50 & CRE40 & CRE30 & CRE25 & CRE20 & CRE10 & BCF \\ \hline 500 & 0.568 & 0.520 & 0.486 & \textbf{0.478} & 0.498 & 0.598 & 0.391 \\ 1000 & 0.399 & 0.366 & 0.347 & \textbf{0.343} & 0.344 & 0.406 & 0.355 \\ 1500 & 0.326 & 0.299 & 0.279 & \textbf{0.276} & 0.278 & 0.320 & 0.309 \\ 2000 & 0.283 & 0.258 & 0.239 & \textbf{0.231} & 0.234 & 0.262 & 0.237 \\ \hline \end{tabular} \label{tab:sim_overall} \end{table} For the data generating process, covariates, treatment, and potential outcomes are generated in the same way as in the previous simulation study. In this simulation, only difference is that we assume that there are two true underlying decision rules: (1) $X_{i1}=0, X_{i2}=0$ and (2) $X_{i1}=1, X_{i2}=1$. The treatment effect $\tau_i$ is defined as $\tau_i = 1$ if $X_{i1}=0, X_{i2}=0$, $\tau_i = -1$ if $X_{i1}=1, X_{i2}=1$, and $\tau_i=0$ otherwise. We consider four samples sizes, $N=500, 1000, 1500$ and $2000$. We consider the root mean squared error (RMSE) to compare the two methods. Table~\ref{tab:sim_overall} shows the performance comparison using RMSE. We consider 1000 simulated datasets for each sample size and provide the average of 1000 RMSE values. Among the considered ratios, (25\%, 75\%) provides the least RMSE for every sample size. The RMSE value decreases as the proportion of the discovery sample increases up to 25\%, and it starts to increase after 25\%. When the sample size is small (i.e., $N=500$), the RMSE for CRE25 is higher than that for BCF, however, it is lower when $N$ is moderately large. This simulation result shows that even though, for instance, the CRE25 method uses 75\% of the total sample for inference, it is as efficient as the original BCF that uses 100\% of the total sample for inference. \section{ Application to the Medicare data} \label{sec:application} We apply the proposed CRE method to the Medicare data in order to study the effect of long-term exposure to fine particulate matter (PM$_{2.5}$) on 5-year mortality. \cite{lee2018discovering} studied the treatment effect of exposure to PM$_{2.5}$ with 110,091 matched pairs and discovered treatment effect heterogeneity in a single tree structure by using the HCT approach. However, as pointed out in their discussion, a single tree unavoidably contains subgroups that are not informative for describing treatment effect heterogeneity due to the nature of tree algorithms. In particular, they found six disjoint subgroups, but only three of them are informative to describe the treatment effect heterogeneity. Also, as we discussed and showed in our simulation study, the HCT approach can be affected by sample-to-sample variations. For a brief overview of the matched Medicare data, it contains Medicare beneficiaries in New England regions in the United States between 2000 and 2006. The treatment is whether the two-year (2000-2001) average of exposure to PM$_{2.5}$ is greater than 12 $\mu g \slash m^3$. The outcome is five-year mortality measured between 2002-2006. For an individual, the outcome is 0 if he/she was died before the end of 2006 and 1 otherwise. There are four individual level covariates - sex (male, female), age (65-70, 71-75, 76-80, 81-85, 86+), race (white, non-white), and Medicaid eligibility (eligible, non-eligible). Medicaid eligibility is considered as a variable indicating socioeconomic status. If an individual is eligible for Medicaid, it is highly likely that he/she has lower household income, thus we use this variable as a proxy for low income. In the matched data, these four variables are exactly matched. There are also 8 ZIP code-level or 2 county-level covariates, and they are fairly balanced between the treated and control groups, see Table 2 in \cite{lee2018discovering} for the covariate balance. Namely, the additional variables used are body-mass-index (BMI), smoker rate, Hispanic population rate, Black population rate, median household income, median value of housing, \% of people below the poverty level, \% of people below high school education, \% of owner occupied housing and population density. Also, see \cite{di2016assessing} for general description about the Medicare data. We apply the CRE method to the same discovery and inference samples that are split by using a (25\%, 75\%) ratio and contain 27,500 and 82,591 matched pairs respectively. Since two individuals in a matched pair share the same covariates, but experience different treatment values, the observed outcomes can be considered as two potential outcomes for a hypothetical individual that represents the corresponding matched pair. The treated-minus-control difference can be considered as an estimate of $\tau_i$ for matched pair $i$. However, since our outcome is binary, the estimate $\hat{\tau}_i^{Matching}$ can take only one of three possible values $\{-1, 0, 1\}$. This discrete feature is undesirable under the linear regression model~\eqref{eqn:model1}. Instead, we ignore the matched structure and use $27500 \times 2 = 55000$ individuals in the discovery sample as if they were obtained independently. We use the logistic BART approach to estimate potential outcome functions $m_z(x) = \mathbb{E}[Y_i(z) | \mathbf{X}_i = x]$, $z=0, 1$. Then, the estimate $\hat{\tau}_i^{BART} = \hat{m}_1(\mathbf{X}_i) - \hat{m}_0(\mathbf{X}_i)$ is obtained. Note that for a continuous outcome, as shown in the simulation study, the BCF approach can be considered. \begin{table} \centering \caption{Discovering decision rules and estimating the coefficients for the decision rules} \begin{tabular}{ll|rcrc} \hline \multicolumn{2}{c}{Rules} & \multicolumn{4}{c}{Covariates}\\ & & \multicolumn{2}{c}{Individual} & \multicolumn{2}{c}{Indiv. + ZIP code} \\ \hline \# & Description & Est. & 95\% CI & Est. & 95\% CI \\ \hline & Intercept & 0.070 & (0.054, 0.087) & 0.077 & (0.061, 0.094) \\ $r_1$ & $\mathbbm{1}(\text{white} = 0)$ & -0.008 & (-0.027, 0.011) & & \\ $r_2$ & $\mathbbm{1}(65 \leq \text{age} \leq 75)$ & -0.012 & (-0.024, 0.000) & -0.009 & (-0.021, 0.002) \\ $r_3$ & $\mathbbm{1}(65 \leq \text{age} \leq 80)$ & -0.027 & (-0.045, -0.010) & -0.027 & (-0.045, -0.010)\\ $r_4$ & $\mathbbm{1}(65 \leq \text{age} \leq 85) \cdot \mathbbm{1}(\text{Medicaid}=0)$ & -0.033 & (-0.050, -0.016) & -0.031 & (-0.048, -0.015) \\ [0.1cm] $r_5$ & $\mathbbm{1}(\text{hispanic \%} =0) \cdot \mathbbm{1}(\text{education} =1)$ & & & -0.019 & (-0.038, 0.000)\\ [0.1cm] $r_6$ & $\mathbbm{1}(\text{hispanic \%} =0) \cdot \mathbbm{1}(\text{education} =1)$ \\ & $ \cdot \mathbbm{1}(\text{population density} =0)$ & & & -0.045 & (-0.067, -0.022)\\ \hline \end{tabular} \label{tab:est} \end{table} In the discovery step with the estimate $\hat{\tau}_i^{BART}$, we first apply the CRE method only with four individual-level covariates. Four decision rules, $r_1, r_2, r_3, r_4$, are discovered. Table~\ref{tab:est} shows the descriptions for these rules on the left column. Based on this finding, the model $\tau(x) = \beta_0 + \sum_{j=1}^{4} \beta_j r_j(x)$ is considered for the later inference step. The first rule is for non-white people that is only 7\% of the total population. The next three rules are defined by age, and $r_2$ is included in $r_3$. The intercept $\beta_0$ represents the treatment effect for the subgroup of Medicaid eligible white people aged between 81-85 and white people aged above 85. This subgroup corresponds to the single tree finding in \cite{lee2018discovering}. Furthermore, we extend the CRE method to the four individual-level and eight ZIP code-level covariates. The ZIP code-level covariates could not be considered in \cite{lee2018discovering} because pairs were matched exactly only on individual-level covariates. When applying the CRE method, five rules are discovered including the three previous rules, $r_2, r_3, r_4$ and two additional rules, $r_5, r_6$. The additional rules are defined by Hispanic population (10\% above or not), Education (did not complete high school 30\% above or not), and Population density (above the average or not). The rule $r_5$ means a subgroup of people living in areas where the proportion of hispanic is below 10\% and the proportion of people who did not complete high school is above 30\%. The rule $r_6$ is included in $r_5$, and means a subgroup of $r_5$ with the additional condition that the population density is below the average. Before making inference with the discovered rules, we want to emphasize two aspects in the discovery step of the CRE method. First, since the CRE method discovers decision rules instead of a whole tree, only important subgroups (decision rules) are selected, and other subgroups are represented by the intercept. For example, \cite{lee2018discovering} discovered six subgroups, but only a few of them are informative for describing the treatment effect heterogeneity. Second, the discovered rules are stable. Being stable means that if another discovery sample is chosen, the discovered rules are hardly changed while a discovered tree varies with its size and terminal nodes. This robustness to sample-to-sample variation makes findings replicable. This feature is extremely significant because higher standards of reproducibility are deemed important in the context of open science. Next, with the discovered decision rules, we use the remaining 82,591 pairs in the inference sample to estimate the rule-specific treatment effects. For the first rule set $\{r_1, \ldots, r_4\}$, the corresponding coefficients are estimated and reported in Table~\ref{tab:est}. To obtain the estimates and 95\% confidence intervals, we consider $\tau_i^* = \hat{\tau}_i^{SIPW}$ to claim the asymptotic normality and obtain the 95\% confidence intervals using the asymptotic distributions. Causal Forest method \citep{athey2019generalized} can be also considered since it guarantees the asymptotic normal distribution for $\bm{\beta}$. Note that the logistic BART approach can be considered as the discovery step, but the asymptotic properties are not guaranteed. On the first part of the right column of Table~\ref{tab:est}, all the coefficients except for the intercept have the negative sign. The intercept indicates that individuals who do not belong to the discovered rules $\{r_1, r_2, r_3, r_4 \}$ are significantly affected by exposure to air pollution. There is a 7 percentage point increase of mortality rate. Though the estimates for $r_1, r_2$ are negative, they are not statistically significant at a significance level $\alpha = 0.05$. However, the estimates for $r_3, r_4$ are significant, which means that people below 80 (i.e., $r_3$) and people below 85 not being eligible for Medicaid (i.e., $r_4$) are significantly less vulnerable than the others. When including ZIP code-level covariates, all the estimates for the discovered rules $\{r_2, r_3, r_4, r_5, r_6\}$ are negative. Similarly, $r_2$ is not significantly different. For the newly discovered $\{r_5, r_6\}$, only $r_6$ is statistically significant. Also, we want to emphasize the interpretation of the coefficients in the inference step. A non-significant estimate does not mean that the corresponding subgroup has the null treatment effect. In this context, non-significance means that the decision rule is no longer important for describing treatment effect heterogeneity. For instance, consider a subgroup of Black people above 85. This groups belongs to $r_1$ only. The estimate $\hat{\bm\beta}_1$ is shown as not significant. However, the treatment effect for this subgroup is $\hat{\bm\beta}_0 + \hat{\bm\beta}_1 = 0.062$ with the 95\% CI (0.041, 0.084) meaning that this subgroup is significantly affected by air pollution. For another example, a subgroup of Black people below 75 has the effect $\hat{\bm\beta}_0 + \hat{\bm\beta}_1 + \hat{\bm\beta}_2 + \hat{\bm\beta}_3 = 0.023$ (95\% CI: (0.003, 0.043)), which is still significant. Since we have the asymptotic distribution for $\bm{\beta}$, any subgroup's treatment effect can be examined. \begin{table} \centering \caption{Sensitivity analysis for the treatment effect heterogeneity by using the percentile bootstrap} \begin{tabular}{l|ccccc} \hline Rules & \multicolumn{5}{c}{Sensitivity Parameter $\Lambda$}\\ & $1.01$ & $1.02$ & $1.03$ & $1.04$ & $1.05$\\ \hline Inter. & (0.054, 0.100) & (0.045, 0.110) & (0.035, 0.121) & (0.024, 0.130) & (0.014, 0.140)\\ $r_2$ & (-0.026, 0.007) & (-0.031, 0.012) & (-0.036, 0.017) & (-0.041, 0.022) & (-0.047, 0.028)\\ $r_3$ & (-0.051, -0.003) & (-0.060, 0.004) & (-0.069, 0.014) &(-0.077, 0.023) & (-0.086, 0.033)\\ $r_4$ & (-0.054, -0.009) & (-0.062, 0.000) & (-0.071, 0.009) & (-0.078, 0.017) & (-0.087, 0.024)\\ $r_5$ & (-0.040, 0.004) & (-0.046, 0.012) & (-0.053, 0.016) & (-0.059, 0.020) & (-0.066, 0.026)\\ $r_6$ & (-0.072, -0.017) & (-0.080, -0.011) & (-0.085, -0.004) & (-0.091, 0.002) & (-0.098, 0.008) \\ \hline \end{tabular} \label{tab:sensi} \end{table} Finally, to evaluate the robustness of the above finding about the treatment effect heterogeneity, we conduct sensitivity analysis in the inference step by setting $\tau_i^* = \hat{\tau}_i^{SIPW}$. We use the following model for sensitivity analysis, $\tau_i = \beta_0 + \sum_{j=2}^{6} \beta_j r_j$. Under the sensitivity model~\eqref{eqn:sensi_model}, for each $\Lambda$, we obtain several sets of 95\% CIs for the coefficients. Table~\ref{tab:sensi} shows the 95\% CIs for $\Lambda$ from 1.01 to 1.05. As $\Lambda$ increases all the CIs get wider. When $\Lambda = 1.04$, all the coefficients contain zero and there is no evidence for the heterogeneity. In particular, $\Lambda=1.04$ means that if there is an unmeasured confounder that can make the estimated propensity score deviated from the true score by 1.04 in terms of the odds ratio scale, then our finding about the heterogeneity can be explained by this unmeasured bias. One further thing to note is that even if the heterogeneity can be explained by an unmeasured bias at $\Lambda = 1.04$, the treatment effect of the baseline subgroup (i.e., intercept) is significant. \section{Discussion} \label{sec:discussion} This paper proposes a new data-driven method for studying treatment effect heterogeneity that notably improves interpretability and provides helpful guidance about subgroups with heterogeneous effects in terms of decision rules. Moreover, the proposed CRE methodology accommodates for well-known shortcomings of binary trees by providing a more stable, flexible and robust methodology to discover and estimate heterogeneous effects. Indeed, CRE is stable to sample-to-sample variations, leading to more reproducible results, and its flexibility allows for the discovery of a wider set of causal rules. Also, CRE provides robust results for the detection of causal rules in the presence of overlap between confounders and effect modifiers. Though the CRE method makes inference using a smaller inference subsample due to sample-splitting, it maintains estimation precision at a similar level as other existing methods while providing an interpretable form of the treatment effect heterogeneity. The CRE method is a generic method that is completely compatible with existing methods for estimating CATE. The performance of CRE may vary with respect to the choice of existing methods to generate base decision rules in the discovery sample and intermediate values $\tau_i^*$ in the inference sample. Therefore, the CRE method can be thought of as a \textit{refinement} process of the outputs produced by existing methods. If an estimation method for the CATE has great precision, then it is highly likely that it detects the treatment effect heterogeneity during the estimation procedure. When the CRE method is accompanied with this estimation method, the CRE method discovers the underlying treatment effect structure with high probability and represents this structure in an easy-to-interpret form. Indeed, a few simple rules are utterly important for public policy implications. However, when it comes to precision medicine, discovering a possibly lengthy rule that is specific to a patient could be of interest. The proposed CRE method requires a researcher to specify some of the so-called tuning parameters. In particular, one should choose a number of trees that are generated for extracting decision rules, and the cut-off threshold in stability selection during the discovery step. Previous studies show that the performance is not much affected by specification of the parameters. Also, the studies provide a general guidance of how to specify the parameters. However, the optimal choice of the splitting ratio between the discovery and inference samples is not known yet. Even though the ratio (25\%, 75\%) is shown to have the best performance through simulation studies, we do not know whether this ratio works best for all real-world datasets. It may be possible to require a larger proportion of the discovery sample if data is sparse. On the contrary, a smaller proportion is needed when the underlying effect structure is simple. Regardless of the splitting ratio, it is more important to choose a proper number of decision rules during the discovery step. The choice may depend on the questions that practitioners want to answer. For example, public policy makers generally want to discover a short list of risk factors. A few important subgroups defined by the risk factors are usually easy-to-understand, and further foster focused discussions about the assessments of potential risks and benefits of policy actions. Also, due to the restriction of resources, public health can be promoted efficiently when prioritized subgroups are available. Instead, a comparatively larger set of decision rules can be chosen, for instance, in precision medicine. An important goal is to identify patient subgroups that respond to treatment at a much higher (or lower) rate than the average \citep{loh2019subgroup}. Also, identifying a subgroup that must avoid the treatment due to its excessive side effects can be valuable information. However, discovering only a few subgroups is likely to miss this extreme subgroup. A number of extensions of the CRE method can be possible. First, the CRE method maintains the benefits that existing methods have, i.e., asymptotic normality and unbiasedness. If an existing method can produce unbiased point estimates for $\tau(x)$ with valid confidence intervals, the CRE method can also produce unbiased estimates for $\bm{\beta}$ with valid confidence intervals. Bayesian methods such as BART or BCF can be also used, and it is empirically shown that they perform really well. However, the validity of Bayesian inference such as constructing credible intervals remains as a future research question. Second, the discovery step of the CRE method can be considered as a dimension reduction procedure. We used a set of decision rules as a basis, but it may be possible to use other forms to characterize the treatment effect heterogeneity. Finally, we proposed an approach for sensitivity analysis of unmeasured confounding bias based on the inverse probability of treatment weighting estimator. A general approach for sensitivity analysis that can be compatible with a larger class of estimation methods would be helpful. Future research is needed for developing such sensitivity analysis. \bibliographystyle{apalike}
{'timestamp': '2020-09-22T02:02:10', 'yymm': '2009', 'arxiv_id': '2009.09036', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09036'}
arxiv
\section{Introduction} \label{introduction} Traditional community consultation methods, such as town halls, public forums, and workshops, are the \textit{modus operandi} for public engagement~\cite{mahyar2019deluge, ehsaei2015successful}. For fair and impartial civic decision-making, the inclusivity of community members' feedback is paramount~\cite{gordon2016civic, mahyar2019deluge, torres2007citizen}. However, traditional methods rarely provide opportunities for inclusive public participation~\cite{Mansbridge2006NormsStudy, Levine2005FutureDeliberation, bryson2013designing}. For instance, reticent meeting attendees struggle to speak up and articulate their viewpoints due to fear of confronting outspoken and dominant individuals~\cite{tracy2007contentious, brabham2009crowdsourcing}. This lack of inclusivity in traditional face-to-face meetings results in an uneven representation of community members and often fails to capture broader perspectives of attendees~\cite{innes2004reframing}. As a result, these methods often fall short in achieving the desired exchange of perspectives between government officials and the community~\cite{salgado2014so, Karpowitz2005DisagreementDeliberation, sanders1997against}. Furthermore, meeting organizers grapple with simultaneously facilitating often contentious discussions and taking meeting notes to capture attendees' broader perspectives~\cite{innes2004reframing, Mansbridge2006NormsStudy}. These bottlenecks further obstruct inclusivity and may lead to biased decisions that can significantly impact people's lives~\cite{Mansbridge2006NormsStudy, mahyar2019deluge}. Advancements in computer-mediated technology can address this predicament by creating a communication channel between these entities. Bryan~\cite{bryan2010real} and Gastil~\cite{gastil2008political} investigated the state of town halls\footnote{In this work, we use the term \emph{Town Hall} to refer to various community consultation approaches where community members convene to meet and discuss civic issues with government officials or decision-makers. Town Halls can take many forms, but the main goal is to establish a communication channel between the officials and the community, to inform the community about civic issues, and often to receive community's feedback~\cite{bryan2010real}.} and demonstrated a steady decline in civic participation due to the growing disconnect between local government and the community. To reengage disconnected, reticent, or disenfranchised community members, researchers in HCI and digital civics\footnote{Digital Civics is an emerging interdisciplinary area that explores novel ways to utilize technology for promoting broader public engagement and participation in the design and delivery of civic services~\cite{kennethdd, Vlachokyriakos, Olivier}.} have offered novel strategies and technological interventions to increase engagement~\cite{mahyar2019deluge, kennethdd, Olivier, Vlachokyriakos, gordon2016civic}. Researchers in this field have proposed several online technologies that made wider participation possible for community members (e.g.,~\cite{mahyar2018communitycrit, decidim:2019, polis:2017, democracyos:2019}). Despite the introduction of such online platforms, government officials and decision-makers predominantly favor traditional face-to-face meetings to create relationships, foster discourse, and conduct follow-up conversations with community members~\cite{mahyar2019deluge, asad2017creating, corbett2018going} to understand their views and aspirations~\cite{ehsaei2015successful, von2005democratizing, innes1999consensus}. However, employing technology to capture attendees' feedback---in particular, silent attendees' feedback---in face-to-face meetings remains largely unexplored. Commonly, feedback in meetings is gathered using voting or polling attendees~\cite{murphy2009promotion, boulianne2018citizen, lukensmeyer21} or taking notes during the meeting~\cite{lukensmeyer2002taking, manuel2017participatory, bryan2010real}. However, voting often restricts attendees to only agreeing or disagreeing, which often does more harm to the richness of the captured feedback from attendees rather than promoting inclusivity~\cite{mahyar2019deluge, bergstrom2009vote}. To help alleviate this problem, prior work mostly focused on automatic speech recognition~\cite{voicea, tur2010calo} and interactive annotations~\cite{banerjee2006smartnotes, kalnikaite2012markup} to help organizers take notes for creating reports. However, these methods rarely preserve the discussion context or improve the inclusivity of attendees' feedback. To better understand the needs of attendees and organizers in community consultations and explore how technology can help to address these issues, we conducted a formative study by attending three town halls in a college town in the United States. We surveyed a total of 66 attendees to inquire about their ability to voice their opinions during town halls. 17\% of the attendees (11 responses) expressed that despite being physically present, they could not voice their opinions. They attributed this to factors such as intimidation from other participants, lack of confidence, and fear of interruption. Moreover, we surveyed 20 organizers to identify what could help them to make better use of the town halls to ensure that the public feedback is prioritized in the reports they authored. We found that the organizers often relied on their memories or the notes taken during the meeting to generate reports. However, they struggled to accurately capture or remember the attendees' feedback and important details after the meeting. In effect, these incomplete memories and meeting notes could potentially result in incomprehensive reports. These findings indicated a requirement for better capturing attendees' feedback and preserving meeting discussion details to support organizers in authoring more comprehensive reports. Based on our formative study, we designed and developed CommunityClick, a system for town halls that captures more inclusive feedback from attendees during the meeting and enables organizers to author more comprehensive meeting reports. We modified iClickers~\cite{iclicker} to allow attendees to silently and anonymously provide feedback and enable organizers to tag the meeting discussion at any time during the meeting. We chose to use iClickers due to their familiarity and ease of use~\cite{morse2010clicker, herreid2006clicker, whitehead2010usingiClicker} as an audience response system (ARS)~\cite{nickerson1993real}. Furthermore, we augmented the automatically-generated meeting transcript by synchronizing it with attendees' feedback and organizers' tags. We also provided an interactive interface where organizers can explore, analyze, and utilize the augmented meeting transcript in a data-driven way and a novel feedback-weighted summary of the meeting discussion to author meeting reports at their convenience. To evaluate the efficacy of our approach, we conducted a field experiment in the wild, followed by eight semi-structured interviews with experienced organizers. Our results demonstrate the efficacy of CommunityClick to give voice to reticent participants to increase their involvement in town halls, capture attendees' feedback, and enable organizers to compile more inclusive, comprehensive, and accurate meeting reports in a way that lends credibility to the report creation process. Our key contributions in this work are as follows: 1) using a communitysourcing technology to enable attendees to share their feedback at any time during the meeting by modifying iClickers as a real-time response mechanism, 2) augmenting meeting transcripts by combining organizers' tags and attendees' feedback to preserve discussion context and feedback from a broader range of attendees, 3) applying a novel feedback-weighted summarization method to generate meeting summaries that prioritize community's feedback, 4) developing an interface for organizers to explore and utilize the augmented meeting transcript to author more comprehensive reports, and 5) insights from a field experiment in the wild that demonstrates how technology can be effective in capturing attendees' voices, authoring more inclusive reports, and future directions to enhance our approach. \section{Background} \label{background} In this section, we describe the current challenges that inhibit inclusivity in town hall meetings. We also discuss existing technologies designed to promote engagement in various meeting scenarios and to help analyze and utilize meeting data. \subsection{Current Challenges in Town Halls} Prior investigations by Bryan~\cite{bryan2010real} and Gastil~\cite{gastil2008political} showed a steady decline in civic participation in town halls due to the growing disconnect between local government and community members and the decline in social capital~\cite{putnam2000bowling, costa2003understanding, rahn1998social}. Despite the introduction of online methods to increase public engagement in the last decade~\cite{coleman2001bowling, mahyar2018communitycrit, decidim:2019, polis:2017, democracyos:2019, kim2016budgetmap}, government officials continue to prefer face-to-face meetings to engage the community in the decision-making process~\cite{mahyar2019deluge, button1999deliberative, ehsaei2015successful}. They believe face-to-face meetings facilitate two-way communications between decision-makers and community members that can foster discourse and help them understand the views and aspirations of the community members~\cite{button1999deliberative, ehsaei2015successful, von2005democratizing, mahyar2019deluge, innes1999consensus}. However, constraints such as fixed physical locations for co-located meetings and scarcity of time and resources, limit the efficacy of face-to-face processes and inhibit the ability of officials to make proper use of town halls~\cite{Levine2005FutureDeliberation, Mansbridge2006NormsStudy, innes2004reframing, seltzer2013citizen, baker2007achieving}. Such constraints might repel or alienate citizens for whom traveling or dedicating time for town halls may not be a viable option from the perspective of physical, economical, or intrinsic interest~\cite{misra2014crowdsourcing, irvin2004citizen, seltzer2013citizen, convertino2015large}. While predictors such as education, income, and intrinsic interest help gauge civic engagement~\cite{davies2014civic}, social dynamics, such as shyness and tendency to avoid confrontation with dominant personalities can also hinder opinion sharing in town halls by favoring privileged individuals who are comfortable or trained to take part in contentious public discussions~\cite{brabham2009crowdsourcing, tracy2007contentious}. Specifically, people with training in analytical and rhetorical reasoning often find themselves at an advantage when discussing complex and critical civic issues~\cite{sanders1997against}. As a result, town halls inadvertently cater to a small number of privileged individuals, and silent participants often become disengaged despite physically attending the meetings~\cite{gordon2011immersive}. Due to the lack of inclusivity, the outcome of such meetings often tends to feel unjust and opaque for the general public~\cite{fung2006varieties, corbette2019trust}. \subsection{Technological Interventions to Increase Engagements in Town Halls} To increase broader civic participation, researchers in HCI have proposed both online~\cite{democracyos:2019, mahyar2018communitycrit, decidim:2019, polis:2017, kim2016budgetmap} and face-to-face~\cite{bergstrom2007conversation, keske2010consulting, lukensmeyer2002taking, taylor2012empowering} technological interventions that use the communitysourcing\footnote{Communitysourcing leverages the specific knowledge of a targeted community. It follows the crowdsourcing model, but takes a more direct approach in harnessing collective ideas, input, and feedback from targeted community members to find solutions to complex problems such as civic decision-making.~\cite{brabham2010crowdsourcing, heimerl2012communitysourcing}} approach. For instance, to increase engagement in town halls, some researchers have experimented with audience response systems (ARS)~\cite{kay2009examining, keske2010consulting, murphy2009promotion, boulianne2018citizen}. Murphy used such systems to promote democracy and community partnerships~\cite{murphy2009promotion}. Similarly, Boulianne et al. deployed clicker devices in contentious public discussions about climate change to gauge public opinions~\cite{boulianne2018citizen}. Bergstrom et al. used a single button device where the attendees anonymously voted (agree/disagree) on issues during the meeting. They showed that back-channel voting helped underrepresented users get more involved in the meeting~\cite{bergstrom2009vote}. The America\textit{Speaks}' public engagement platform, 21 Century Town Meeting\textregistered, also used audience response systems to collect feedback and perform straw polls and votes during town halls~\cite{lukensmeyer21}. However, in these works, the audience response systems were used either for binary voting or polling~\cite{bergstrom2009vote, lukensmeyer21}, or to receive feedback on specific questions that expected attendees' feedback on a Likert scale-like spectrum~\cite{likert1932technique}. These restrictions limit when and how meeting attendees can share their feedback. Audience response systems have seen widespread success as a lightweight tool to engage participants, promote discussions, and invoke critical thinking in the education domain~\cite{morse2010clicker, herreid2006clicker, addison2009usingiclicker, keller2007researchclicker, whitehead2010usingiClicker, mollborn2010meetingclicker}. As such, these devices have the potential to provide a communication channel for silent participants to express their opinions without the obligation to verbalize and risk confrontation. We build upon their success in the education domain by appropriating iClickers for the civic domain. We modify and utilize iClickers for town halls to create a mechanism that supports silent and real-time community feedback. HCI researchers have proposed research solutions to increase participation in face-to-face meetings such as design charrettes, or group-meetings in general, by using various tools and methods~\cite{mahyar2016udcospace, hunter2011memtable, bergstrom2007conversation, bergstrom2009vote, Shi2017IdeaWallStimuli}. Some researchers used interactive tabletop and large screen surfaces to engage attendees~\cite{mahyar2016udcospace, hunter2011memtable, Shi2017IdeaWallStimuli}. For example, UD Co-Spaces~\cite{mahyar2016udcospace} used a tabletop-centered multi-display environment for engaging the public in complex urban design processes. Memtable~\cite{hunter2011memtable} used a tabletop display to increase attendees' engagement by integrating annotations using a multi-user text editor on top of multimedia artifacts. IdeaWall visualized thematically grouped discussion contents in real-time on a large screen during the meeting to encourage attendees to discuss such topics~\cite{Shi2017IdeaWallStimuli}. However, large displays along with real-time visualizations might distract attendees from concentrating on meeting discussions~\cite{appleton2005gis}, which might lead to less contribution from the participants irrespective of how vocal they are~\cite{gordon2011immersive}. Furthermore, these innovative approaches might be overwhelming for meeting attendees, especially in the civic domain, due to the heterogeneity of participants with a wide spectrum of expertise and familiarity with technology~\cite{costa2003civic, tracy2007contentious, adams2004publicandemocratic}. It might also be impractical and financially infeasible to use expensive tabletops and large interactive displays for town halls organized in a majority of cities. \subsection{Technologies to Analyze and Utilize Meeting Data} Prior works showed that decision-makers often relied on meeting reports generated by organizers to inform public policies that had potential long-term impacts on the community~\cite{lukensmeyer2002taking}. Commonly, organizers generate these reports based on the outcome of voting or polling attendees~\cite{murphy2009promotion, boulianne2018citizen, lukensmeyer21}, and taking notes during the meeting~\cite{lukensmeyer2002taking, manuel2017participatory, bryan2010real}. They often use manual note-taking techniques such as pen-and-paper or text editors~\cite{di1972listening}. However, simultaneously taking notes from the meetings to capture attendees' feedback and facilitating the meeting to guide and encourage discussions is overwhelming and often lead to losing critical information and ideas~\cite{rowe2005typology, piolat2005cognitive}. Sometimes the meetings are audio-recorded and transcribed for reviewing before writing the report. However, such reviewing processes require significant manpower and labor~\cite{lukensmeyer21, lukensmeyer2002taking}. Furthermore, the audio recording themselves do not capture the feedback of reticent participants who did not speak up. In general meeting scenarios, researchers proposed improvements to manual note-taking for capturing meeting discussions~\cite{chiu2001liteminutes, kam2005livenotes, meetingKing, davis1998notepals}. For example, LiteMinutes used a web interface that allowed creating and distributing meeting contents~\cite{chiu2001liteminutes}. MeetingKing provided meeting agenda templates to help organizers create reports~\cite{meetingKing}. Similarly, LiveNotes facilitated note-taking using a shared whiteboard where users could write notes using a digital pen or a keyboard~\cite{kam2005livenotes, bennett1991optical}. Another group of researchers experimented with various tools and techniques to provide support for facilitating online synchronous group discussion. For example, SolutionChat provides moderation support to group discussion facilitators by visualizing group discussion stages and featured opinions from participants and suggesting appropriate moderator responses~\cite{lee2020solutionchat}. Bot in the Bunch takes a different approach and propose a chatbot agent that aims to enhance goal-oriented online group discussions by managing time, encouraging participants to contribute to the discussion, and summarizing the discussion~\cite{kim2020bot}. Similarly, Tilda synthesizes online chat conversation using structured summaries and enable annotation of chat conversation to improve recall~\cite{zhang2018tilda}. Closer to our approach, some researchers proposed different techniques for automatically capturing meeting discussions without significant manual intervention~\cite{tur2010calo, voicea, banerjee2006smartnotes, iCompassTech}. For example, CALO and Voicea are automated systems for annotating, transcribing, and analyzing multiparty meetings~\cite{tur2010calo, voicea}. These systems use automatic speech recognition~\cite{rabiner1993fundamentals} to transcribe the meeting audio and extract topics, question-answer pairs, and action items using natural language processing~\cite{hirschberg2015advances}. However, automatic approaches are often error-prone and susceptible to miscategorization of important discussion topics~\cite{mcgregor2017moretomeeting, chuang:2012}. To address this problem, some researchers suggested incorporating human intervention to control and compile reports without completely depending on automatically generated results~\cite{banerjee2006smartnotes, kalnikaite2012markup, iCompassTech}. SmartNotes~\cite{banerjee2006smartnotes} and commercial applications such as ICompassTech~\cite{iCompassTech} use this approach where the users can add and revise notes and topics. Although these methods used a combination of automatic and interactive techniques, they enabled the utilization of meeting discussions without capturing sufficient circumstantial input. The automatically generated transcript might record discussions but it may not contain feedback shared by all attendees, especially silent ones. Furthermore, these tools are designed for small-scale group meetings and may not be practical in town halls in the civic domain where attendee numbers and requirements can vary significantly~\cite{bryan2010real, lukensmeyer2002taking}. The heterogeneity of attendees in town halls~\cite{costa2003civic, adams2004publicandemocratic}, the lack of inclusivity in sharing their opinions~\cite{Karpowitz2005DisagreementDeliberation, sanders1997against}, the deficient methods to record meeting discussions~\cite{lukensmeyer21}, and limited financial and design pragmatism in existing technologies~\cite{mahyar2016udcospace, Shi2017IdeaWallStimuli} necessitate a closer investigation and innovation in designing technology to address both meeting attendees' and organizers' challenges regarding inclusivity in town halls. \section{Formative Study: School Building Town Halls} \label{formative_study} To inform our work, we wanted to understand the perspectives and needs of organizers and attendees who participate in community consultations. To this end, we attended several town halls, including multiple public engagement sessions in a college town in the United States (U.S.). The agenda for these town halls included discussions regarding new public school buildings where the town authorities wanted the community's feedback on two new proposals that involved millions of dollars worth of renovation or reconstruction. The town authorities made careful considerations to ensure that the public has access to all the information about the proposals by arranging six community-wide engagement sessions organized by professional facilitators. We joined three out of six of these sessions in a span of three months. We decided to investigate this particular case due to the unique characteristics of the town, where there is relatively high citizen engagement on discussions around education and public schools. We also wanted to investigate how people discuss potentially contentious proposals in the town halls that pitted two contrasting ideas for future public school buildings. \subsection{Participants and Procedures} We approached both the meeting attendees, who were community members, and the meeting organizers, who included facilitators and town officials. The town halls began with the organizers presenting their proposal to attendees. Afterward, attendees engaged in discussions and shared their ideas, opinions, and concerns about the proposals. The facilitators were responsible for guiding the discussion and collecting the attendees' feedback.They played a neutral role in the discussion and did not influence the attendees' opinions in any way. To understand the attendees' perspectives, we conducted surveys after each town hall. The attendees were all residents of the town and attended the meeting of their own volition. We surveyed a total of 66 attendees. We refer to the attendees from our formative study as \textbf{FA} and organizers from our formative study as \textbf{FO}. In the survey, we asked them open-ended questions regarding their motivation to join the town hall meetings, their experiences in these meetings, and their thoughts around what makes these face-to-face meetings successful. We also asked about their ability to voice their opinions in town halls and about their familiarity with audience response technologies. Furthermore, to gain an understanding of what type of semantic tags they wanted to provide during a town hall, we compiled a list of tags based on prior work on meeting discussions or public engagements that focused on characterizing effective participation during synchronous communication between organizers and meeting attendees in both online and face-to-face settings~\cite{zhang2018tilda, nathan2012incase, derek2010collaborative, zhang2017characterizing, im2018deliberation, murray2006incorporating}. The list of tags is presented in Fig.~\ref{fig:survey}(B). We provided this list to the attendees and asked them to rate which of these tags would help them to express their thoughts in town halls. They rated each tag on a 5-point Likert scale~\cite{likert1932technique}. During these town halls, we made contact with the organizers and explained our project goals. From these initial contacts, we used the snowball method~\cite{goodman1961snowball} to reach other organizers working across the U.S. to learn more about their practices regarding town hall meeting organization, facilitation, and report creation. We conducted surveys with a total of 20 organizers with an average experience of 10.5 years (min 1 year, max 35 years) in conducting town halls across the U.S. Our survey participants consisted of town administrators, town clerks, senior planners, directors, professional facilitators, and chairs of different town committees. We asked them open-ended questions around their meeting data recording practices including what data do they prioritize when recording, the challenges they face while organizing the meeting simultaneously and recording meeting notes, and their post-meeting data analysis and meeting report generation processes. We also asked about their choice of tools and technologies for recording meeting notes and for creating reports, and what they think are the elements that constitute a good report. To identify representative tags that could help organizers track and categorize meeting discussion, we compiled another list of tags based on prior works~\cite{zhang2018tilda, nathan2012incase, derek2010collaborative, im2018deliberation, murray2006incorporating}. We used a different list from the one we provided to attendees (Fig.~\ref{fig:survey}(A)) because prior work suggest that organizers and attendees need different tags to categorize meeting discussion based on their perspectives. We asked organizers to rate the tags in the order of importance on a five-point Likert scale~\cite{likert1932technique}. The survey questions and list of tags are provided as supplementary materials. \subsection{Findings} \begin{figure} \includegraphics[width=1\textwidth]{Figures/surveyresults.pdf} \caption{This figure presents attendees' and organizers' perceived importance of two sets of tags that we compiled based on prior research: (A) shows the ratings of 20 organizers on a list of 10 tags for organizers; (B) shows the ratings of 66 Community members on a list of 9 tags for attendees' feedback. } \label{fig:survey} \end{figure} Here, we report the findings from our surveys with both attendees and organizers. The 66 attendees we surveyed were highly motivated to attend town halls and the majority of them (64\%, 42 responses) considered attending such meetings to provide their feedback on civic issues as their \emph{civic duty}. Most of the attendees (88\%, 58 responses) attended two or more town halls every year. Regarding their familiarity with technology, every meeting attendee (100\%, 66 responses) mentioned having a computer, smartphone, and internet access, but 61\% of them (40 responses) never used an audience response system before. We also found that 17\% (11 responses) of meeting attendees felt they were not able to share their feedback during these meetings, and 23\% (15 responses) were not satisfied with the way town halls were organized to discuss critical issues. It was surprising for us to find that 17\% of people from a homogeneous, relatively wealthy, and educated community in a college town believed that they could not voice their opinions during town halls. Despite their unfamiliarity with audience response systems, the majority of the meeting attendees (87\%, 57 responses) mentioned that they were willing to use such devices in town halls to share their feedback. In response to the question regarding what makes face-to-face town hall meeting successful, a group of attendees mentioned that the success of town hall meetings hinges upon the attendees' ability to openly communicate their opinions and hear others' opinions. One attendee (FA-17) mentioned, \blockquote{\emph{Town halls need to provide opportunities for all people to be heard, having diversity of voices and opinions, and be present in the discussion.}} Another attendee (FA-36) mentioned, \blockquote{\emph{Being face-to-face means asking questions, listening to others' questions and ideas, and to be able to see their emotions, nuances and expressions.}} Several attendees' mentioned facing challenges around sharing their opinions due to being dominated in the discussion. One such attendees' mentioned (FA-23), \blockquote{\emph{Town halls give us the chance to talk things out, but often this doesn't happen and people get shut down.}} Another attendee (FA-11) mentioned, \blockquote{\emph{You need to have ground rules so that we stay on track and no one dominates the discussion.}} Some attendees considered that facilitators play an important role in the success of town halls and skilled and well-equipped facilitators can make a difference. One attendee (FA-57) emphasized the importance of skilled facilitator saying, \blockquote{\emph{Professional facilitators understand the context of our community, and the history of tension regarding the issues. They move it along and listen with open minds.}} Another attendee (FA-47) mentioned, \blockquote{\emph{Skilled facilitators make sure all voices are heard, organize the discussion around goals and keep everyone focused on tasks.}} When rating the tags for sharing opinions during meetings (Fig.~\ref{fig:survey} (A)), the majority (90\%) of the attendees considered \emph{Agree} and \emph{Disagree} to be the most important tags. 75\% or more attendees thought \emph{Unsure}, \emph{Important}, \emph{Confused}, and \emph{Neutral} to be important. The majority of the organizers (17 responses) mentioned that often manpower and budget constraints forced them to forego the appointment of designated note-takers and thus, they must shuffle between organizing and note-taking during the meetings. Some organizers also mentioned how context-switching between organizing the meeting and taking notes often led to missing critical evidence or information (8 responses). They employed a variety of methods for recording meeting data depending on their convenience and their operational abilities and experiences to utilize such methods, including pen-and-paper (5 responses), text editors (6 responses), audio or video recorders (3 responses), or a combination of these methods. To generate reports from the notes taken during the meetings, organizers usually used text editors (17 responses) with preferences towards Microsoft Word and Notepad (12 responses). However, when asked about the time required to compile a report from meeting notes, their responses varied from 15 minutes to a few days. The variation, in part, can be attributed to the amount of notes and the format in which notes were captured. All organizers (20 responses) mentioned that the report generation process involves some form of summarization process of meeting records to retain the most important discussion components. One organizer (FO-7) explained, \blockquote{\emph{If I'm responsible for the report, I listen to the recording, review the notes, and translate them into coherent accounts of meeting attendees, topics, discussion, and decisions/outcomes.}}. Another organizer (FO-1) mentioned, \blockquote{\emph{I start with the agenda, review the audio, then edit and summarize the meeting notes into report content.}} Organizers also described high-level properties of what would constitute a \textit{good report}. One organizer (FO-1) mentioned that, good meeting reports should be \blockquote{\emph{accurate, comprehensive, clear, and concise}}. Another organizer (FO-4) emphasized that several components constitue a good report including, \blockquote{\textit{[the] main agenda items, relevant comments, consensus, action plans, and feedback}}. One organizer (FO-17) thought meeting reports should be \blockquote{\textit{balanced, fair, and pertinent}} towards multiple perspectives, however, it is often challenging because they only \blockquote{listen to a few, while others stay silent}. When rating tags that would help them to take better notes to create good reports (Fig.~\ref{fig:survey} (B)), the meeting organizers unanimously (100\%) endorsed the tag \emph{Decision}. The tags \emph{Topic}, \emph{Action Items}, \emph{Main Issue}, and \emph{Date} were preferred by more than 70\% organizers. However, all other tags except for \emph{Q\&A} were favored by more than 50\% of organizers. These survey responses suggest that preferences for tagging meeting discussion varies among organizers, and different sets of tags might be required to be useful for generating reports from different meetings with diverse agendas. \subsection{Design Goals} Based on prior work and our formative study, we identified four design goals to guide our system design that address the requirements and challenges of both meeting attendees and organizers. First, we found that some attendees lacked a way to respond to ongoing discussions. Furthermore, many organizers struggled to keep track of the discussion and take notes simultaneously. Thus, we needed to provide communication channel between attendees and organizers for sharing opinions and capturing feedback (G1). Second, the organizers often refer to several sources of meeting data including meeting notes and audio/video recording to compile meeting reports. Hence, the meeting discussion audio, organizers' tags, and attendees' feedback should be captured and combined together to provide organizers with a holistic view of the meeting data (G2). Third, the organizers perform some form of summarization to generate meeting reports. However, many organizers also struggled to account for attendees' feedback while summarizing meeting data. This challenge motivated a third goal to introduce summarization techniques that incorporate attendees' feedback to help organizers to get the gist of meeting discussions (G3). Finally, organizers needed to examine the meeting-generated data to capture more inclusive attendees' feedback so that they could write more comprehensive reports. To that end, our final design goal was to provide exploration and report authoring functionalities to help them investigate the meeting data and identify evidence to generate reports that included and reflected attendees' feedback (G4). \begin{figure} \includegraphics[width=1\textwidth]{Figures/cc_fig.pdf} \caption{A snapshot of CommunityClick's workflow. During the meeting, attendees and organizers can use iClickers to share feedback and tag the meeting respectively. The meeting is also audio-recorded for transcription. The audio recordings are transcribed automatically and then augmented with the organizer's tags and attendees' feedback. Furthermore, we generated the feedback-weighted discussion summary and extracted the most relevant topics. The interactive interface enables the exploration and utilization of augmented meeting discussions, which is available online for organizers to examine and author meeting reports.} \label{fig:cc_block} \end{figure} \section{CommunityClick} \label{sysdesign} Guided by the design goals, we designed and developed CommunityClick, a system where we modified iClickers as a real-time response mechanism and augmented meeting transcripts to capture more inclusive feedback. We also introduced a novel feedback-weighted summarization to prioritize attendees' feedback and enabled exploration and utilization of the augmented transcript through an interactive interface for organizers to author meeting reports. Here, we provide a scenario where CommunityClick can be employed (Fig.~\ref{fig:cc_block}), followed by the system description. \subsection{User Scenario} Michelle is an organizer who has been appointed by the local government officials to organize an important town hall. Given the importance of the meeting, she decides to deploy CommunityClick to focus on facilitating the meeting while using iClickers to capture the community's feedback. Adam is a community member who is attending the town hall. He cares about the community and wants to share his opinions on the agenda. He prefers to avoid confrontations, especially in town halls, as he is worried about speaking up and running into arguments. In the meeting, he is given an iClicker and instructions for using it to share his opinions using five options. Adam engages in discussion with other attendees in the meeting but whenever he feels hesitant to speak up, he uses the iClicker to provide feedback. A week later, Michelle finally gets around to writing the report of the town hall. By now, she has forgotten a significant portion of the meeting discussion. She logs in to CommunityClick and selects the town hall. She uses the timeline and feedback-weighted summary to get an overview of the meeting discussion and jog her memory by exploring the meeting discussion. She uses her own tags, timeline, and the interactive summary to investigate the augmented meeting transcript that contained attendees' feedback alongside the discussion segments. Finally, she authors the report by importing information into the text editor from the transcript. \begin{figure}[h] \centering \includegraphics[width=0.5\textwidth]{Figures/apts.pdf} \caption{The apparatus used to capture organizers' tags and attendees' feedback. (A) The iClicker for organizers to tag the meeting. (B) The iClicker for attendees to add their feedback. We used different sets of tags for organizers and attendees based on our formative study. Each iClicker was labeled with the respective set of tags to reduce the cognitive load of mapping options to the iClicker buttons. (C) The iClicker recorder. We used an Adafruit Feather M0 with the 900 MHz RFM69W/RFM69HW transceiver to capture iClicker clicks with timestamps in real-time to synchronize tags and feedback with meeting audio.} \label{fig:apa} \end{figure} \subsection{System Description} In the following, we describe how we addressed the design goals by using iClickers, augmenting meeting transcripts, performing text analysis, and developing an interactive interface. \subsubsection{Modifying iClickers to enable attendees and organizers to provide real-time responses (G1)} We used iClickers for both organizers and attendees to enable them to respond to meeting discussions any time during the meeting without the need to manually take notes or speak up to share opinions. iClicker is a communication device that uses radio frequency to allow users to anonymously respond using its five buttons (Fig.~\ref{fig:apa}). Despite the widespread usage of smartphones, we chose iClickers as an audience response system due to recent statistics that show 20\% of U.S. citizens do not yet have access to smartphones~\cite{pewresearch}. Furthermore, they are often a major cause of distraction and hindrance to participation in meetings~\cite{bajko2016prevalence, kushlev2016silence}. There are also technical overheads involved including installation of application, maintenance, and issues regarding version compatibility based on operating systems which might disengage the participants. In contrast, iClickers have proven to be successful in town halls due to its familiarity and affordance of anonymity in sharing opinions in town halls and to receive attendees' feedback on specific questions~\cite{bergstrom2009vote, murphy2009promotion, boulianne2018citizen}. The anonymous use of iClickers could ensure that silent participants can also share their opinions to the organizer about the ongoing discussion without engaging with a potentially heated debate. Moreover, we modified the iClickers to go beyond previous approaches by allowing meeting organizers and attendees to respond to the ongoing discussion using all five different options instead of only binary agree or disagree. The tag options are customizable and depending on their meeting agendas, the organizers can set up an appropriate list of tags and feedback before the meeting. We used different types of iClickers for organizers and attendees. The organizers used instructor iClickers and attendees used regular ones (Fig.~\ref{fig:apa}). It helped us to effectively separate organizers' and attendees' responses. To reduce the cognitive load of iClicker users to map and remember the options, we labeled each iClicker with organizers' tags and attendees' feedback. \subsubsection{Combining automatically generated transcripts with tags and feedback to capture more inclusive feedback (G2)} We recorded and synchronized three different sets of data generated simultaneously in the meeting---the discussion audio, the organizers' tags, and the attendees' feedback via iClickers. We recorded the meeting audio using a regular and commonly used omnidirectional microphone. To remove the noise from the audio recording, we used an open-source freeware named Audacity\textregistered. However, capturing organizers' tags and attendees' feedback from iClickers was non-trivial due to the limitations in hardware access and the API provided by the iClicker manufacturer. The original software and hardware in factory settings did not provide timestamped data on each click. As a result, we customized the hardware and API to record organizers' tags and attendees' feedback (Fig.~\ref{fig:apa}). We used an Adafruit Feather M0 with the 900 MHz RFM69W/RFM69HW transceiver to collect an iClicker's clicks and timestamps that were transmitted through radio frequency on the same bandwidth. This allowed us to accurately and precisely capture and synchronize iClicker interactions to match the time of discussion. To transcribe the meeting audio, we used automatic speech recognition techniques from Assembly AI~\cite{assemblyai}. We assessed the quality of this method by comparing them to human-generated reference transcripts. We found our approach to be on-par with human-generated transcripts. The results of these analyses are presented in full in the \hyperref[appendix]{Appendix} section. We combined the transcript with the timestamped tags and feedback to transform the recorded meeting audio into timestamped text. Furthermore, we used the organizers' tags to divide the meeting transcript into manageable and consumable segments. Previous work showed that there is a gap (2 seconds on average) between hearing something, registering it, and taking actions upon it, such as clicking a button for annotation~\cite{risko2013collaborative}. Based on prior work and our early pilot experiments, for each organizer's tag, we created a 30 second time window around the tag (2 seconds before the tag and 28 seconds after the tag). The complete meeting transcript is divided into similar 30-second segments. For each segment, we collected the attendees' feedback provided within that time-window. Consequently, the meeting audio is transformed into timestamped segments, each containing transcribed conversation, organizers' tags, and a set of attendees' feedback (Fig.~\ref{fig:interface}(E)). We also extracted the main discussion points from the transcript segments using Topic Rank~\cite{bougouin2013topicrank} (Fig.~\ref{fig:interface}(B)). We chose this topic modeling method to have better multi-word topics which are useful for better topic representation~\cite{blei2009visualizing}. \subsubsection{Applying text summarization method to incorporate attendee's feedback into meeting discussion summaries (G3)} To summarize the meeting transcript, we used the graph-based TextRank algorithm~\cite{mihalcea2004textrank}, which is based on a variation of the PageRank~\cite{page1999pagerank} algorithm. TextRank is known to deliver reasonable results in summarizing meeting transcripts~\cite{garg2009clusterrank} in unsupervised settings. However, it treats all input text the same without any domain-specific consideration. Our goal was to incorporate attendees' feedback in the summarization process so that the resultant summary was weighted by attendees' feedback. To that end, we added two critical modifications to the original methodology: 1) by incorporating attendees' feedback while computing relative importance of sentences, and 2) replacing the vanilla similarity function used in TextRank with a bag-of-words ranking function called BM25, which is proven to work well in information extraction tasks~\cite{robertson1995okapi}. Each individual transcript is treated as a set of sentences ($s_1, s_2...s_n$). Each sentence is considered as an independent node. We used a function to compute the similarity between these sentences to construct edges between them. The higher the similarity between the sentences, the more important the edge between them will be in the graph. The original TextRank algorithm considers the relation between two sentences based on the content (tokens) they share. This relationship is between two sentences $S_i, S_j$, for every $w_k$ common token, is given by equation~\ref{tr_sim}. \begin{equation} \centering sim(S_i, S_j) = \frac{\vert \{w_k \vert w_k \in S_i \& w_{k} \in S_j\}\vert}{\log(\vert S_j \vert) + \log(\vert S_i \vert)} \label{tr_sim} \end{equation} We replaced the above similarity function by a BM25 ranking function utility defined by equation \ref{bm_sim}. \begin{equation} \centering sim(S_i, S_j) = \sum_{k=1}^n IDF(w_k \in S_i) \frac{f(w_k \in S_i, S_j). (a + 1)}{f(w_k \in S_i, S_j) + a.(1-b+b.\frac{\vert P \vert}{\mu_{DL}})} \label{bm_sim} \end{equation} \noindent where $a, b$ are function parameters ($a=1.2, b=0.75$), $f(w_k, S_j)$ is $w_k$'s term frequency in $S_j$, $IDF$ is the inverse document frequency, and $\mu_{DL}$ is the average length of the sentences in our collection. More importantly, since we timestamped and tagged our transcripts, we knew which instances were potentially more important in terms of garnering attendees' feedback. To incorporate those, we augmented every edge weight $w_{i,j}$ by a factor of $\epsilon$ determined experimentally (set to $1.10$ if either of the sentences being compared prompted feedback, or $0.90$ otherwise). From the constructed graph of sentences, we computed the final relative importance of every vertex (sentence), and selected the top-n sentences corresponding to about $30\%$ of the total length of the transcript which were then presented, in their original order, as the summary of the meeting discussion. We performed a series of ablation tests to evaluate the robustness of our summarization approach. The results of these tests are presented in full in the \hyperref[appendix]{Appendix} section. For three different meeting transcripts that we had generated using CommunityClick, we quantitatively evaluated the auto-generated summaries against human-annotated reference summaries using the widely used ROUGE~\cite{lin-2004-rouge} metrics. Across different meeting transcripts, we observed similar ROUGE scores, indicating that we produced summaries of consistent quality of summaries across different meetings. Additionally, we evaluated our algorithmic approach on the popular AMI meeting corpus~\cite{carletta2005ami}. Our results were found to be comparable to the current state-of-the-art methods~\cite{zhong2019searching, shang2018unsupervised} employed on the AMI dataset under unsupervised settings. \begin{figure} \centering \includegraphics[width=1\textwidth]{Figures/interface.pdf} \caption{A snapshot of CommunityClick's interface. A) The title provides useful metadata about the meeting such as date and location. B) The main topics extracted from the meeting transcript. C) The timeline visualizes organizers' tags in chronological order. Each circle represents a tag. Clicking on a circle brings organizers to the corresponding transcript segment. D) The interactive feedback-weighted summary. E) Transcript view displays the transcript text alongside organizers' assigned tag, the main topic, and aggregated attendees' feedback in that time interval for each segment. F) Filters for attendee's feedback (based on what was provided on iClicker). G) The bar chart displays attendees' feedback. H) Filters for organizer's tags. I) Rich text editor for organizers to author the report. J) Options to view or collapse the summary or the transcript view.} \label{fig:interface} \end{figure} \subsubsection{Enabling exploration of an augmented meeting transcript through an interactive interface to help organizers author meeting reports (G4)} We developed CommunityClick's interface as a web application. It allows multi-faceted exploration and analysis of meeting data by providing components including the title, filters, discussion topics, timeline, summary, text editor, and finally the augmented meeting transcript segments (Fig.~\ref{fig:interface}). The title contains the metadata about the meeting, including the meeting title, date, and location (Fig.~\ref{fig:interface}(A)). The filters allow organizers to explore the transcript segments according to the selected feedback or tags of interest (Fig.~\ref{fig:interface}(F, H)). These options are customizable, and organizers may customize the tags to suit their purpose before the meeting. We chose to visually collapse transcript segments that are filtered as opposed to completely removing them from the view to communicate to the users that there are additional conversations that transpired between the segments currently visible. In the topic and timeline component, we provide the list of most relevant topics and the timeline of the meeting discussion (Fig.~\ref{fig:interface}(B, C)). The organizers can filter the transcript segments based on any topic. The timeline displays the organizers' tags using circles in a chronological manner, where each circle represents a tag, and the color corresponds to organizers' tags (Fig.~\ref{fig:interface}(C)). This provides the organizers with a temporal distribution of tags that demonstrates how the conversation progressed during the meeting. When a circle is selected, the transcript is scrolled to the corresponding segment and highlights the background to distinguish it from other segments. The feedback-weighted extractive summary is presented in a textbox (Fig.~\ref{fig:interface}(D)). Each of these sentences is interactive, and upon selection, they navigate to the transcript segment it was extracted from. This can enable organizers to explore the transcript and get a better understanding of why the sentence was added to the summary. Below the summary, we added a rich text editor for authoring the meeting report with rich formatting options (Fig.~\ref{fig:interface}(I)). We also added options for attaching additional files or images. Once the report is created, it can be printed in PDF format directly, without switching to other external printing applications. Finally, we present the augmented transcript divided into transcript segments (Fig.~\ref{fig:interface}(E)). The segments are ordered chronologically. Each transcript segment contains the transcript text, associated organizer's tag, the most relevant extracted topic, time of the segment, option to import the summary of the selected transcript to the text editor, and aggregated attendees' feedback in the form of a bar chart. For easy tracking, we highlight the transcript text that are added to the summary. Organizers can edit the segments to assign or change tags and topics. However, they do not have control over attendees' feedback to mitigate bias injection. To reduce clutter on the screen, we added two additional filters to collapse the summary or augmented transcript (Fig.~\ref{fig:interface}(J)). \subsection{Pilot Study} To explore whether CommunityClick could be effectively deployed in a real-world town hall meeting, we performed a pilot study where we simulated a town hall with nine participants. We recruited eight participant as meeting attendees and one participant as the organizer, who had previous experience with organizing meetings. We refer to the attendees who participated in our pilot study as \textbf{PA} We recruited all participants using word of mouth from a public university in the U.S. For the discussion topic, we selected two contentious issues regarding the university that were popular at the time of our pilot study. The topics included discussions around building a new common room for graduate students and the rise of racist activities across the campus. All participants were graduate students (6 males and 2 females with a average age of 27.25). The goal of the pilot study was to assess the system workflow for potential deployment and whether the attendees could share their feedback silently using iClickers without interrupting others. Furthermore, we used the augmented transcript from the meetings to enable the pilot study organizer we recruited to explore the meeting discussions to identify potential interface issues. The meeting took 60 minutes which is similar to a traditional town hall. We collected 292 items of feedback from attendees (avg 36.5 per attendee $\pm$ 8.23) and 56 tags from the organizer. After the meeting, we asked attendees to share their experiences of using iClickers to voice their opinions using open-ended questions. The findings suggested that attendees found iClickers easy to get used to. They were able to share their feedback silently using iClickers, managed to avoid potential confrontations, and thought they could contribute more compared to their experiences in other meetings. However, one attendee mentioned about difficulties around remembering which iClicker button mapped to which attendees' tag. Another attendee mentioned that while expressing strong agreement or disagreement with the ongoing discussion, some attendees might spam the iClicker button which might \blockquote{\emph{dilute the opinion values}} (PA-4). The organizer mentioned using iClickers enabled him to focus more on the discussion and the interface allowed him to better capture attendees' feedback. He recalled that some attendees were silent, but the bar charts showed feedback from all eight participants, meaning they were participating silently. He also identified the flow of the discussion, and important discussion points. This pilot study helped us to better understand and solidify operational procedures to perform real-world deployment of our system. Based on the feedback we received, we modified the system and user interface. For instance, we added a spamming prevention technique~\cite{sun2013synthetic} by calibrating the system to capture one click from each attendees' iClicker in a 30-second window to negate the possibility of diluting the values of specific feedback options. Furthermore, we added an option to collapse the summary or transcript to reduce interface clutter. Finally, we used written labels on iClickers to reduce attendees' cognitive load in remembering the mapping of response options. \section{Evaluation} \label{evaluation} We evaluated the application of iClickers as a real-time response system, particularly for the ability of silent attendees to share feedback, and the efficacy of our approach in enabling organizers to explore, capture, and incorporate attendees' feedback to author more comprehensive reports. To that end, we conducted a field experiment to examine if the attendees could effectively use iClickers to voice their feedback. In addition, we followed up by conducting semi-structured interviews with 8 expert organizers to evaluate if CommunityClick could enable them to capture attendees' feedback and generate more comprehensive reports. \subsection{Field Experiment: Parking Town Hall} We deployed CommunityClick at a town hall in a college town in the U.S. The meeting focused on a new set of proposals to improve the parking condition of the town. We reached out to the town officials a month before the meeting took place. They allowed us to deploy our system, record the discussion, and use the data. They also introduced us to the organizer who facilitated the meeting. We explained the procedure to them and discussed the tags to be used for both the organizer and attendees. The town hall took place on a Thursday evening and was open for all to attend. \subsubsection{Meeting Participants} There were 31 attendees and 1 organizer present in the meeting. We provided attendees' iClickers with Agree, Disagree, Unsure, Important, and Confused tags to 31 attendees. For the organizers, we provided them iClickers labeled with Main Issue, Concern, Supportive, New Idea, and Good Point tags as per our pre-meeting discussion. \subsubsection{Procedure} At the beginning of the town hall, we provided a brief tutorial for five minutes on how to use the iClickers to the meeting attendees. We also received consent from the attendees about recording their discussions. The meeting began with an organizer presenting the meeting agenda and the new parking proposals to the meeting attendees. The attendees and the organizer used iClickers to tag the conversations throughout the meeting. After the presentation, the attendees engaged in discussing the proposals. The meeting lasted for 76 minutes. At the end of the meeting, we provided post-study questionnaires to attendees that asked various questions, such as their reasons behind attending the meeting, their usual experience during town halls, whether they could share their opinions by speaking up, and how did using iClickers compare to such experiences. They responded on a five-point Likert scale. We also asked them open-ended questions around their experience of working with iClickers, whether they faced any issues or challenges, and suggestions to improve their experiences and our approach. The post-study questionnaire is provided as a supplementary material. \subsubsection{Data Collection and Analysis} We were given permission to collect and use the data from the town hall by government officials. We collected 61 minutes of meeting audio for transcription. We also collected organizer's tags and attendees' feedback from the meeting. In total, we captured 56 tags from the organizer. Out of 31 meeting attendees, 22 used the iClickers we provided to share their feedback. Out of these 22 attendees, 20 of them filled up the post-study questionnaire. We report the statistics based only on these 20 attendees' responses. We captured a total of 492 attendees' feedback with an average of 24.6 feedback items per attendee with a standard deviation of 6.44. This data was later used to populate CommunityClick's interface for demonstrating its various functionalities to meeting organizers, which we describe in~\ref{sub:interview}. We also collected the post-study questionnaire responses and entered them into spreadsheets for creating charts (Fig.~\ref{fig:field_exp}) and statistics for analysis. \subsubsection{Findings} From the analysis of the attendees' iClicker usage patterns, we found that the attendees' used the tag \textit{Agree} the most 187 clicks (38\%), followed by \textit{Important} with 103 clicks (21\%), \textit{Disagree} with 93 clicks (19\%), \textit{Confused} with 79 clicks (16\%), and finally \textit{Unsure} with the least amount of 30 clicks (6\%) only. Initially, we were surprise to see the large gap between agreement and disagreement. However, upon closer inspection, we found that on several occasions, the attendees who were using iClickers was clicking \textit{Agree} when other vocal attendee were verbally expressing their disagreement to a discussion topic. This behavior pattern indicates that the silent attendees used iClickers to provide their support for an ongoing argument alongside sharing their own opinions. We also found that the attendees did not press any iClicker options during the introduction when the organizers were setting up the discussion and conclusion of the meeting when the organizers expressed gratitude for attending the meeting and other social conversation. This suggests that the attendees took their opinion sharing using iClickers seriously and did not randomly clicked different options during the meeting. \begin{figure} \centering \includegraphics[width=1\textwidth]{Figures/field_exp_data.pdf} \caption{The results from the field experiment. A) Attendees' responses show that the majority of meeting attendees were not satisfied with the status quo of town halls but found iClickers easy to get used to. It also displays the number of attendees who thought they could share their voices by speaking up or using iClickers. B) A deeper comparison between speaking up and using iClickers to share attendees' feedback. The diamonds (\textcolor{gray}{\ding{117}}) and stars (\textcolor{gray}{\ding{86}}) represent 20 attendees' (A1-A20) responses to questions that asked them to rate their experiences of sharing opinions by speaking up and using iClickers respectively during town halls. The arrows show the difference and increase or decrease in their ratings. The arrows demonstrate that the majority of the participants who were not satisfied with the current methods of sharing opinions (A1-A3, A5) during town halls found iClickers to be a better alternative. They also show the participants who were comfortable with speaking up during meetings, did not endorse iClickers as strongly to share their voices.} \label{fig:field_exp} \end{figure} From the analysis of the post-study questionnaires, we found that all of the 20 attendees either lived or worked in the town of Amherst, where the town hall was organized. 95\% of these attendees (19 responses) were well-accustomed with such meetings and they mentioned attending similar town halls twice a year, while 50\% (10 responses) attended these meetings more than five times per year. When asked about their exposure to technology, all meeting attendees responded to owning at least one computer and one smartphone with an internet connection, which they were comfortable using. However, their responses to the experiences in town halls varied as presented in Fig.~\ref{fig:field_exp}(A). 25\% of attendees (5 responses) mentioned that they did not feel that they are able to voice their thoughts in town halls. Only 35\% (7 responses) were pleased with the way such town halls are organized while 50\% of the attendees (10 responses) were neutral in their responses. 75\% attendees (15 responses) responded that they got used to iClickers quickly. 85\% mentioned (17 responses) they were able to share their thoughts using iClickers compared to only 65\% (13 responses) attendees who are comfortable with speaking up to share opinions. The majority of the attendees (90\%) were positive about their experiences of using iClickers to share their opinions (18 responses). One attendee (A9) mentioned, \blockquote{\emph{I feel like I could contribute more than usual and I would definitely like use it in future meetings.}} We further compared the attendees' responses on their ability to share their thoughts in town halls by voicing their opinions against using iClickers (Fig.~\ref{fig:field_exp}(B)). The data shows that almost all of the attendees who did not think they could share their thoughts by speaking up, except for one (A4) thought they could voice their opinions using iClickers. One such attendee (A2) mentioned, \blockquote{\textit{I didn't like what others were saying. But instead of interrupting, I just used the clicker to say that I didn't agree with them.}} We also found that, while agreeing that iClickers' could provide a way to voice opinions in town halls, the attendees who strongly preferred speaking up did not rate their experience of using iClickers to share opinions as high. One of these attendees (A17) mentioned, \blockquote{\textit{I was distracted, so I didn't use it that much.}} We identified two important insights from this field experiment (Fig.~\ref{fig:field_exp}). Firstly, it demonstrated that the silent attendees' who could not speak their minds found a way to voice their opinions without apprehension of confrontation in town halls using iClickers (Fig.~\ref{fig:field_exp}(A) and (B), attendees A1-A3, A5). However, we also found that some attendees who strongly agreed that they were satisfied with the current method of sharing opinions by speaking up, did not as strongly endorse iClickers as a way to share their opinions (Fig.~\ref{fig:field_exp}(B), attendees A13-A15, A17, A18). We speculate two reasons for such reduced ratings for iClickers. First, for the attendees who are already comfortable with speaking up, iClickers might seem like an additional step to share opinions which might lead to distractions, as mentioned by one of the attendees (A17). The second reason might be a reluctance to deviate from the norm and use technology in an established albeit impaired town hall proceedings and customs. Nevertheless, our results suggest that the addition of iClickers could be an acceptable trade-off between providing the silent attendees a way to communicate their opinions and mildly inconveniencing the adept and vocal meeting attendees. \subsection{Semi-structured Interviews with Meeting Organizers} \label{sub:interview} We conducted semi-structured interviews with 8 expert meeting organizers, who were experienced with organizing or facilitating town halls to gather data on community's needs, issues, and ideas. They were also adept at compiling meeting reports that play a pivotal role in informing civic decision-making. Our objective was to examine if CommunityClick's interactive interface could help the organizers to better capture the attendees' feedback to author more comprehensive reports that preserve the equity and inclusivity of voiced opinions in town halls. \subsubsection{Participants} We reached out to a total of 29 expert organizers from across the U.S. 8 of them responded by agreeing to help us with evaluating CommunityClick. Our interviewees were experts in their fields with intimate knowledge of town hall organization and decision-making. We refer to our semi-structured interview participants as \textbf{P}. On average, they had over 20 years of experience. One interviewee (P1) was the organizer from our field experiment---the town hall on parking. We made connections with the others (P3-P8) during our formative study. All of our interviewees were based in the U.S. \subsubsection{Procedure} Several experts we engaged with to evaluate CommunityClick were excited about its potential and agreed to deploy the system in their then upcoming town halls. Our original evaluation plan involved several deployments in the wild, then providing organizers with the meeting audio from these deployments and ask them to write two reports, one using their current method of writing reports, and the other using CommunityClick's augmented meeting transcript and interactive interface. We wanted to study the differences between these reports to investigate the efficacy of our system. However, the recent COVID-19 pandemic forced the organizers to cancel all town halls until further notice, and we were compelled to cut our evaluation short. Due to this setback, we revised and modified our evaluation procedure as follows. We deployed the CommunityClick interface on a public domain and shared it with our interviewees via emails at least two weeks before our interviews. To maintain privacy of usage, we provided each organizer with their own user account and login credentials. We also provided detailed instructions on how to use CommunityClick's various features and encouraged the interviewees to explore the interface at their own convenience. We populated the interface with the data collected from the simulated meetings from our pilot study as well as the meeting from our field experiment for the interviewees to explore. During the interview sessions, we asked them open-ended questions focusing around their current practices towards town hall organization, how using CommunityClick differed from these practices, how useful could CommunityClick be to capture silent attendees' feedback and marginalized perspectives, could the interface allow them to author better reports, and finally, suggestions to improve CommunityClick. We also allowed them to ask any questions they might have about CommunityClick. The interview questions are provided as a supplementary material. We conducted the meetings over video conferencing via Zoom~\cite{zoom}. The interviews lasted between 45-60 minutes. All participation was voluntary. Each interview was conducted by an interviewer and a dedicated note-taker from our research team. \subsubsection{Data Collection and Analysis} We transcribed over 400 minutes of audio recording from our interviews with organizers. We also took extensive notes throughout the meeting. Finally, we thematically analyzed the interview transcripts and notes taken using the open-coding method~\cite{burnard1991method}. Two members of our research team independently coded the data at the sentence level using a spreadsheet application. The inter-coder reliability was 0.89 which was measured using Krippendorff's alpha~\cite{krippendorff2011computing}. We had several iterations of discussions among the research team to condense the codes into the themes presented in Table~\ref{tab:theme_table}. \begin{table*} \caption{This table shows themes that emerged from analyzing the interviews with the organizers. The codes associated with the themes and their description is also presented in the table.} \scriptsize \setlength\tabcolsep{6pt} \ra{1.5} \centering \begin{tabular}[t]{p{2.6cm} p{6cm} p{4cm}} \toprule \textbf{Themes} & \textbf{Codes} & \textbf{Descriptions}\\ \midrule Enabling inclusivity & Equitable platform, problem speaking up, opinion sharing, understanding others, inclusive opinions & CommunityClick's impact on inclusivity in town halls\\ Diverse perspectives & Shared narrative, honest reflections, attendee's reactions, identifying conversation flow & Different perspectives and opinion shared in town halls\\ Report quality & meeting summarization, missing information, credible process, comprehensiveness, accurate representation & CommunityClick's utility in creating reports\\ Meeting organization & Unstructured discussions, real-time attendee's response, tracking response, customized tags, measuring consensus & Organizing meeting-generated data\\ Interface learnability & Intuitiveness, easy-to-use, formatting, data exploration & Users' ability to learn and use interface features\\ Concerns and caveats & Technology as a barrier, tech-savvy, distraction factors, young generation & Concerns regarding CommunityClick's usage in town halls\\ Improvement suggestions & Real-time feedback, opinion statistics, organizers' input & Suggestions to improve our approach\\ \bottomrule \end{tabular} \label{tab:theme_table} \end{table*} \subsubsection{Findings} Our analysis of interview transcripts and notes surfaced critical insights on how CommunityClick could enable attendees to share opinions and help organizers to capture inclusive feedback to author more comprehensive reports. We elaborate on these insights in the following and discuss possible room for improvement. \\\\ \noindent\textbf{CommunityClick can create a more inclusive platform to share opinions.} Our interviewees were unanimous (8 out of 8) in acknowledging CommunityClick's potential to create an inclusive platform for community to share their opinions. They shared with us several example scenarios they experienced where CommunityClick could have provided silent attendees a way to speak their minds. P1 mentioned, \blockquote{\textit{People want to share their opinions, but sometimes they just can't express themselves because they're not comfortable talking, or they're nervous about how they'll appear to or who is around the table. Often they are intimidated. Here, }"intimidated" \textit{is a strong word. But I don't think it's the wrong word.}} P2 mentioned, \blockquote{\textit{There was an individual who attended several meetings, it was clear that their presence had an impact on people's willingness to speak at all, or the opposite effect, where people escalated in reaction to that person. Giving them the ability to click help both ways. They can avoid confrontation or avoid escalation by just clicking.}} Similarly, P3 drew examples from his experiences, saying, \blockquote{\textit{Even if the attendees are from the U.S., [people with] different upbringings or cultural backgrounds have a disadvantage to those who are quite familiar with the moors of group dynamics. In our town halls, we only take votes on questions or get agreements, but in a conversation, there are so many euphemisms, colloquialisms, and metaphors that make it difficult for someone unfamiliar with them to understand others' reactions. There is real value in using options like ``confused'' and ``unsure'' to allow them to record that they didn't understand the conversation instead of forcing them to agree or disagree.}} P6 found further value in separating the attendees' tags and the organizers' tags to establish organizers' credibility. She mentioned, \blockquote{\textit{The organizers cannot unintentionally skew the attendees' feedback because [their tags] are separate. That way, we know the recorded feedback is unbiased.}} \\\\ \noindent\textbf{The augmented transcripts provide evidence of attendees' reflections.} One of our primary goals was to enable organizers to have access to attendees' perspectives to form a shared narrative of the meeting discussions. After exploring CommunityClick's interface, the majority of interviewees (7 out of 8) mentioned how it enabled them to capture meeting attendees' reflections on the meeting agenda. P6 mentioned, \blockquote{\textit{It provides a way of ensuring that voices and reactions are reflected as people speak and click. It is a huge step towards having a more honest reflection of what really went on in the meeting.}} P3 further emphasized how CommunityClick not only captured the attendees' feedback but also allowed navigation of the conversation flow using the Timeline, \blockquote{\textit{This tool allows me to see both how many ideas have traction or agreement and how many don't, but just as importantly, how the flow went. The facilitators are concerned with the way topics are discussed in town halls. These topics are influenced by the surrounding conversations. It [Timeline] allows me to see reactions that might or might not be intended because of the sequence of conversations. Having a way to track that has a huge value.}} Regarding the interactive augmented transcript, P4 specifically preferred the way it enabled her to track attendees' responses. She drew a comparison with her usual methods for note-taking during town halls saying, \blockquote{\textit{We usually have a table facilitator and then a table observer. The table observer takes detailed notes, but it adds to the number of staff we have to have. So that creates an additional challenge, but the speech to text transcription makes a big difference in recording people's reactions. With [CommunityClick], maybe we won't need a table observer.}} P5 also mentioned how CommunityClick gave credence to attendees' reactions during the meeting discussions through the feedback bar charts. She said, \blockquote{\textit{It makes a lot of sense to see where people are aligned, where the challenges are, and giving information from their reactions. When changing policies, we hear from only a few voices who are either for or against something, and they tend to dominate the conversation. Having a visual and data-driven way to show what was the actual participation is gold. Sometimes people feel that a proposal is not aligned with their ideas. With the bar chart, you can show them that maybe you are the outlier and others agree with the proposal.}} \vspace{0.3cm} \noindent\textbf{CommunityClick can help create more comprehensive and accurate reports.} All of our interviewees had prior experiences of writing reports by summarizing the meeting discussions and identifying key discussion points. They found various aspects of CommunityClick useful to not only author more comprehensive reports but also more accurate ones that lend credibility to the report creation process. P1 drew parallels with his experience of working in scenarios where designated note-takers took notes and his team generated the reports from those notes. He mentioned, \blockquote{\textit{People who take notes have varying abilities and the notes vary in quality. Instead, as you are writing reports, you have [CommunityClick], where you can see and add the reactions to what [attendees] discussed right away, it builds credibility for the process.}} P3 echoed similar sentiments, saying, \blockquote{\textit{You are usually distracted by the conversation while taking notes, which means you might miss every third word at a particular moment, which could be the difference between agreement and disagreement. Having it transcribed and summarized will remind a facilitator of some things that he or she may not have remembered or make it more accurate, because they may have remembered it differently. I love the fact that the [text analysis methods] can capture that objectively for us.}} P4 also emphasized the usefulness of importing a summary to the text editor. She mentioned, \blockquote{\textit{Having the text editor where you can start writing the report and pull in pieces from the transcript could be really helpful, because then as you read through the transcript and you're writing about some themes, you can pull characteristic quotes that would really help bring in more evidence for claims for those themes.}} Furthermore, we found that the report creation process can take a few hours to a few days depending on variables such as the way notes were taken, the length of the meeting, report creators' skills, etc. P7 highlighted the reduced workload and efficiency that CommunityClick could provide, saying, \blockquote{\textit{There is a physical component of getting into it, typing it up, theming, organizing, and editing which always takes longer than anticipated, I can see some of those issues can be fixed with this.}} \\\\ \noindent\textbf{CommunityClick preserves the flow of meeting discussions by establishing an implicit structure.} The majority of our interviewees (6 out of 8) thought CommunityClick could be best utilized to organize unstructured meeting discussions. They emphasized that contrary to asking meeting attendees to respond to specific questions in town halls, CommunityClick allowed attendees to respond whenever they wanted, creating an implicit structure to the meeting while preserving the flow of discussion. One interviewee (P1) mentioned, \blockquote{\textit{[CommunityClick] would provide the biggest benefit in more unstructured kind of discussions. If you have a town hall, where people are less likely to speak up, [tags] would be helpful to understand their reactions and help with the theming.}} Another interviewee (P5) mentioned, \blockquote{\textit{It's hard to keep track of many ideas, but the visual organization of information helps to gauge reactions and figuring out if we reached consensus. But most importantly, it helps me to see if there are any social or racial injustice components into the proposals where there can be negative reactions.}} They also found the option to customize the attendees' feedback and organizers' tags useful to adapt to different meeting scenarios. One interviewee (P3) mentioned, \blockquote{\textit{Words may mean different things in different meetings. Having the ability to label and customize [tags] individually would be a way for different organizations to adjust to that. Sometimes we want to know [attendees'] hopes and concerns, but other times, we just want to know if they agree or disagree.}} However, P7 raised a concern about larger meetings, saying, \blockquote{\textit{I think [CommunityClick] will be useful for smaller meetings, but if there are hundreds of people, and everyone is speaking over each other, I'm not sure if you will be able to cope with that.}} \\\\ \noindent\textbf{The simplicity and learnability of the interface affords intuitive exploration.} From a usability standpoint, all of our interviewees (8 out of 8) found CommunityClick's interface to be simple and straightforward to work with. P3 extolled the interface saying, \blockquote{\textit{It's very intuitive, simple, easy to use, and navigate after the fact, edit, and update. All user interface features look well-thought-out to me considering the inner workings are extremely delicate and complicated.}} P4 valued the rich editing options of the text editor. She said, \blockquote{\textit{The automatic summaries can be used as a starting point of the report, as an initial cut, and then I can delete the things that might not be very useful and build up the report by adding more to it and formatting it. I can clearly see a lot of thought was put into designing the interface.}} P5 thought that the interactivity of the timeline was useful for navigating the augmented transcript. She mentioned, \blockquote{\textit{When I started clicking on the buttons on the circles at the top [timeline], it was very intuitive, like, it just automatically brings you to the places where that correlates with the statements, so you understand what it's connected to.}} P6 further emphasized CommunityClick's potential as a record-keeping and meeting exploration system, saying, \blockquote{\textit{Everything is linked together. So in that sense, it makes intuitive and logical sense when I'm looking at the data. It will be a total game-changer for policymakers and community organizers.}} \\\\ \noindent\textbf{Concerns around technology in town halls.} Although our interviewees praised CommunityClick, some of them raised a few important concerns. P8 mentioned how technology usage could be troublesome in town halls, saying, \blockquote{\textit{It feels like the technology itself could be seen as a barrier, because a lot of people might not feel quite as comfortable, clicking on things and reacting to.}} On a different note, P4 raised concerns about the sense of urgency such technology might impose on the meeting attendees. She said, \blockquote{\textit{[Attendees'] reactions, they are decisions that are being made in the spur of the moment as they're hearing information. And it's such a complex, sociological, and psychological response to information.}} Her concern was whether the urge to immediately respond to someone's perspectives could inhibit the ability to contemplate and deliver a measured response. Further concerns arose from P5, who mentioned how younger meeting attendees might have an advantage in the town halls if the technology is heavily used, saying, \blockquote{\textit{Younger generations tend to use technology so much more easily. And they turn to it so much more easily than older generations.}} \\\\ \noindent\textbf{Possible room for improvements.} We received some feedback from our interviewees on how to improve CommunityClick. Some of these suggestions focused on adding more real-time components to CommunityClick that can further augment the ongoing discussions. For example, P3 mentioned, \blockquote{\textit{Right now, [CommunityClick] helps me to understand attendees' reactions after the fact. I think if the facilitators could see them in real-time as the attendees are clicking away, they might be able to steer the conversation better to be more fruitful and fair.}} Other suggestions involved adding functionalities to add the organizers' own topics on top of the automatically extracted topics. In that regard, P4 mentioned, \blockquote{\textit{I guess it depends on who is using the system, but we look to dive a little bit more and would want to maybe customize the topics and themes}}. \section{Discussion} \label{discussions} From our field experiment and interviews with experts, we found that CommunityClick could be used to create an equitable platform to share more inclusive feedback in town halls. Compared to prior approaches to utilize technology in town halls~\cite{murphy2009promotion, boulianne2018citizen}, CommunityClick enabled attendees to utilize iClickers to silently and anonymously voice their opinions any time during the meeting without interrupting the discussion or the apprehension of being shut out by dominant personalities. We extended the use of audience response systems in prior works by adding five customizable options that go beyond binary agreement or disagreement and modifying iClickers as a real-time response system~\cite{boulianne2018citizen, bergstrom2009vote}. The experts we interviewed valued options such as \textit{confused}, or \textit{unsure} to identify if attendees were disengaged or did not understand the conversation without forcing them to agree or disagree~\cite{Karpowitz2005DisagreementDeliberation, sanders1997against}. The customizability of both organizers' tags and attendees' feedback further added to the flexibility of our approach that could potentially increase adaptability in meetings with diverse agendas in both civic and other domains. Moreover, the automation and augmentation of speech-to-text transcription, extraction of most relevant discussion topics, and feedback-weighted summarization of meeting discussion could potentially eliminate the need for separate note-takers. According to the organizers we interviewed, it could reduce the manpower requirement significantly compared to established approaches~\cite{lukensmeyer21, lukensmeyer2002taking}. From organizers' perspectives, CommunityClick could help create more comprehensive and accurate reports that could provide evidence of attendees' reflections. Prior work experimented with annotations during face-to-face meetings~\cite{kalnikaite2012markup, kelkar2010livetagging} for memory recall. In our work, we empowered organizers to go beyond recollection of events during meetings by integrating their own customized tags and enabled them to capture a more comprehensive picture of the meeting discussion. Furthermore, our interactive summary and attendees' feedback visualization provided a visual and data-driven way to highlight attendees' viewpoints, and outliers on critical points of discussions. This could enable organizers to receive a more clear reflection of what occurred in the meeting and author more accurate reports based on tangible evidence rather than incomprehensive interpretation~\cite{mahyar2019deluge}, that could further lend credibility to the report creation process. Prior work highlighted concerns about accuracy in computational approaches to analyze meeting data~\cite{mcgregor2017moretomeeting}. However, from our interviews with experts, we found that the accuracy and comprehensiveness of meeting reports often depends on meeting length, method of taking notes during the meetings, and note-takes' skills. We posit that synchronization of meeting data and addition of inclusive attendees' feedback into the summary and interface will enable organizers to author more accurate reports with the added benefit of reduced manpower requirement. Although during our interviews with meeting organizers, some of them highlighted that the augmented transcripts, discussion topics, and summaries could only be accessed after the meeting is finished, we argue that the latency is an acceptable tradeoff for increased comprehensiveness, credibility, and accuracy in generating reports. Furthermore, enabling access to the variety of meeting generated data could also help to reduce both organizers' and attendees' distraction during the meeting~\cite{gordon2011immersive, appleton2005gis} and allow them to engage with the ongoing discussion. In particular, the separation of attendees' feedback and organizers' tags along with the evidence of attendees' feedback in meeting reports could pave the way to instill trust between the decision-makers in the local government and the community members, which is considered to be a wicked problem in the civic domain~\cite{corbette2019trust, corbett2018problem, harding2015, mahyar2019deluge}. \subsection{Marginalization in Civic Participation and the Role of Technology} Marginalization can be broadly defined as the exclusion of a population from mainstream social, economic, cultural, or political life~\cite{given2008sage}, which still stands as a barrier to inclusive participation in the civic domain~\cite{mahyar2019deluge, dickinson2019cavalry}. Researchers in HCI and CSCW have explored various communitysourcing approaches to include marginalized populations in community activities, proceedings, and designs~\cite{dickinson2019cavalry, erete2017empowered, walsh2019ai+, mahyar2018communitycrit, kim2016budgetmap}. In this work, we added to this body of work by designing technology that included silent voices in civic participation to increase the visibility of marginalized opinions. Our field experiment and interviews with experts demonstrated the efficacy of our approach to enable, capture, and include silent attendees' participation in town halls, regardless of their reasons behind keeping silent (social dynamics, fear of confrontation, cultural background, etc.). Our work also answers the call for more inclusive data analysis processes and practices to augment computational approaches~\cite{rhody2016dig, d2020data} by proposing a text summarization method that included and prioritized attendees' feedback when generating meeting discussion summaries. Such inclusive data analysis techniques could reflect the community's opinions, identify social and injustice, and support accountability in the outcome of civic engagements~\cite{erete2017empowered}. However, designing communitysourcing technologies to include marginalized opinions and amplify participation alone may not be enough to solve inequality of sharing opinions in the civic domain~\cite{torres2007citizen, bovaird2007beyond}. Despite the success of previous works~\cite{erete2017empowered, lukensmeyer21, boulianne2018citizen}, technology is rarely integrated with existing manual practices and follow-ups of engagements between government officials and community members are seldom propagated to the community. This lack of communication might lead to the uncertainty of attendees on whether actions will be taken to reflect their opinions. As a result, the power dynamics between the government officials and the community remain unbalanced, especially for the marginalized populations~\cite{dickinson2019cavalry, erete2017empowered, dickinson2018inclusion, taylor2012empowering}. One way to establish the practicality of using technology to include marginalized opinions is to integrate them into existing processes to convince the officials of its efficacy. Our work provides first steps towards integration of marginalized perspectives, however, long-term studies are required to assess the possibility and feasibility of integrating public perspectives into the actual civic decisions. \subsection{Integrating CommunityClick in Today's Town Halls} Our formative study with 66 attendees and field experiment with 20 attendees bore a striking resemblance regarding the attendees' ability to share their opinions in town halls. We found that 17\% (11 out of 66) of attendees from the formative study and 25\% (5 out of 20) of attendees from the field experiment were not comfortable to speak up in town halls and needed a way to share their opinions. However, similar to previous works~\cite{lukensmeyer21, gastil2008political}, some of the meeting organizers we interviewed were apprehensive towards depending solely on technology due to concerns around logistics involved with the procurement and maintenance of electronic devices such as iClickers, reliability concerns of using technology that require proper management, and unfair advantage towards newer generation who are more receptive to novel technologies. We argue that renewed motivation, careful design choices, and detailed instructions could help overcome the novelty barrier of technology even for people from older generations~\cite{vaportzis2017older, d2014three}. Based on our experiences from this study, we advocate for integrating technology with current face-to-face methods. We do not suggest complete replacement of traditional methods with technology, rather we suggest augmenting them with technology to address some of their limitations. CommunityClick could be gradually integrated as a fail-safe or an auxiliary method to complement the current process. All the functionality of CommunityClick would remain operational while the organizers could take personal notes in parallel alongside their iClicker interactions. This would allow organizers to retain their current practices while taking advantage of augmented meeting transcripts, discussion topics, and summaries from CommunityClick to better capture and understand attendees' perspectives when compiling reports. Another way to integrate CommunityClick into current processes would be to provide statistics of attendees' feedback so that the organizers could track the discussion dynamics and facilitate the conversation accordingly to keep attendees engaged. However, prior works suggested that real-time visualization or displays can add to attendees' distraction, causing them to disengage from the ongoing discussion~\cite{gordon2011immersive, appleton2005gis}. To circumvent this issue, optional companion mobile applications could be introduced only for organizers to receive real-time feedback on attendees' iClicker responses so that they can make course corrections accordingly without distracting the attendees or influencing their opinions. \subsection{Expanding CommunityClick to other Domains} From our field experiment and interviews with the experts, we demonstrated CommunityClick's potential in elevating traditional town halls. We argue that our proposed data pipeline can be expanded to other domains where opinion sharing is important for successful operation. For example, in education, whether in classroom settings or in massive open online courses~\cite{kizilcec2013deconstructing, d2007mind, jones2013classroom}, it could enable students to share their feedback anytime without interrupting the class on whether they could understand a certain concept, or if they were confused and needed more elaboration, especially when the class size is large. For educators, it could allow them to track the effectiveness of their content delivery, class progress, and student motivation, which might help them to adjust the course curriculum more effectively and efficiently, instead of receiving feedback from students once every semester. More importantly, familiarity with iClickers in education eliminates the entry point barrier for technology making the system readily adoptable~\cite{whitehead2010usingiClicker, addison2009usingiclicker}. Similarly, CommunityClick could be used as a possible alternative to expensive commercial applications in meeting domains within the business and other corporate organizations~\cite{meetingKing, iCompassTech}. Similar to town halls, in a corporate setting, CommunityClick could provide text summary and direct evidence of attendees' feedback from the meeting transcripts for better decision-making. Automatic text summarization remains a challenging problem~\cite{tas2007survey}, especially when it comes to automatically summarize meeting discussions~\cite{gillick2009global}. Our summarization approach emphasized the importance of meeting attendees' feedback instead of purely text-based summarization approach that treated all sorts of text documents similarly~\cite{tas2007survey, mihalcea2004textrank}. We argue that this \textit{feedback-weighted} summary could be valuable in generating domain-specific contextual text summarization in other meeting genres. Furthermore, there are potential applications of CommunityClick as a record-keeping tool which might be particularly applicable in journalism where the journalists can utilize the iClickers to annotate the interview conversation with important tags and later review the augmented interview conversation using CommunityClick's interface to better organize and write news articles or interview reports. \section{Limitations and Future Work} Our evaluations suggested the efficacy of CommunityClick in providing a voice to reticent participants and enabling organizers to better capture the community's perspectives. However, we had only one real-world deployment of CommunnityClick at a town hall due to the pandemic. We will continue to engage with meeting organizers and deploy CommunityClick in town halls to study the long-term impact of CommunityClick and attempt to gradually integrate our approach in the predominantly manual town hall ecosystem. Also, we found that iClickers might be distracting as a new technology for some attendees in town halls as the findings from our field experiment suggested. Furthermore, the logistical issues associated with both hardware procurement and the unavailability of software APIs might be a hindrance to some communities. To circumvent these issues, low-cost alternatives to iClickers or fully software-based substitute audience response system applications could be utilized~\cite{voxvote, slido}. A fully software based solution could also enable attendees to provide open-ended textual feedback which CommunityClick does not allow in its current state. However, further comparative studies are required to assess the cost, efficacy, and applicability of such alternatives to replace iClickers that would provide the same benefit without incurring additional financial, computational, or cognitive overhead. There are several avenues to improve CommunityClick in the future. For example, it could be augmented with more real-time components including a companion application to deliver dynamic feedback statistics for organizers to access and utilize during the meeting. We will also explore novel methodologies to speed up the automatic speech to text transcription process to further reduce the time required for data processing. One approach could be to utilize parallel pipeline processing~\cite{chaiken2008scope} where audio signals from the meeting will be processed concurrently, which might reduce processing time significantly. To further provide evidence from attendees' feedback to help organizers when authoring reports, the audio of discussions could be added and synchronized with the transcript segments. It could enable the organizers to identify vocal cues and impressions from the attendees who spoke during the town hall to further contextualize the discussion segment ~\cite{mehrabian2017nonverbal}. In addition, we will investigate the possibility of tracking individual iClickers IDs without risking the privacy of attendees to anonymously identify potentially contentious individuals who might be pushing specific agendas or marginalize minority viewpoints in a discussion. However, further studies are required to understand the potential computational challenges that might arise with such extensions. To further improve the report generation, we will explore novel technologies in natural language generation~\cite{wen2015semantically} to automatically write meeting reports that could further reduce meeting organizers' workload. In addition to exporting the created reports, we will further enable exporting various statistics around attendees' feedback, organizers' tags, discussion topics, etc. to be added to the report or used separately in presenting the outcome of the town halls to decision-makers. \section{Conclusion} In this study, we investigated the practices and issues around the inequality of opportunity in providing feedback in town halls, especially for reticent participants. To inform our work, we attended several town halls and surveyed 66 attendees and 20 organizers. Based on our findings, we designed and developed CommunityClick, where we modified iClickers as a real-time response mechanism to give voice to silent meeting attendees and reflect on their feedback by augmenting automatically generated meeting transcripts with organizers' tags and attendees' feedback. We proposed a novel feedback-weighted text summarization method along with extracting the most relevant discussion topics to better capture community's perspectives. We also designed an interactive interface to enable multi-faceted exploration of the summary, main discussion topics, and augmented meeting-generated data to enable organizers to author more inclusive reports. We deployed CommunityClick in-the-wild to conduct a field experiment and interviewed 8 expert organizers to evaluate our system. Our evaluation demonstrated CommunityClick's efficacy in creating a more inclusive communication channel to capture attendees' opinions from town halls and provide evidence of attendees' feedback that could help organizers to author more comprehensive and accurate reports to inform critical civic decision-making. We discussed how CommunityClick could be integrated into the current town hall ecosystem and possibly expanded to other domains. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-09-22T02:02:39', 'yymm': '2009', 'arxiv_id': '2009.09053', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09053'}
arxiv
\section{Introduction} Historically, metrics for evaluating the quality of machine translation (MT) have relied on assessing the similarity between an MT-generated hypothesis and a human-generated reference translation in the target language. Traditional metrics have focused on basic, lexical-level features such as counting the number of matching n-grams between the MT hypothesis and the reference translation. Metrics such as {\sc Bleu} \cite{papineni-etal-2002-bleu} and {\sc Meteor} \cite{banerjee-lavie-meteor2009} remain popular as a means of evaluating MT systems due to their light-weight and fast computation. Modern neural approaches to MT result in much higher quality of translation that often deviates from monotonic lexical transfer between languages. For this reason, it has become increasingly evident that we can no longer rely on metrics such as {\sc Bleu} to provide an accurate estimate of the quality of MT \cite{barrault-etal-2019-findings}. While an increased research interest in neural methods for training MT models and systems has resulted in a recent, dramatic improvement in MT quality, MT evaluation has fallen behind. The MT research community still relies largely on outdated metrics and no new, widely-adopted standard has emerged. In 2019, the WMT News Translation Shared Task received a total of 153 MT system submissions \cite{barrault-etal-2019-findings}. The Metrics Shared Task of the same year saw only 24 submissions, almost half of which were entrants to the Quality Estimation Shared Task, adapted as metrics \cite{ma-etal-2019-results}. The findings of the above-mentioned task highlight two major challenges to MT evaluation which we seek to address herein \cite{ma-etal-2019-results}. Namely, that current metrics \textbf{struggle to accurately correlate with human judgement at segment level} and \textbf{fail to adequately differentiate the highest performing MT systems}. In this paper, we present {\sc Comet}, a PyTorch-based framework for training highly multilingual and adaptable MT evaluation models that can function as metrics. Our framework takes advantage of recent breakthroughs in cross-lingual language modeling \cite{laser2019-Artetxe, devlin-etal-2019-bert, NIPS2019_8928, conneau2019unsupervised} to generate prediction estimates of human judgments such as \textit{Direct Assessments} (DA) \cite{graham-etal-2013-continuous}, \textit{Human-mediated Translation Edit Rate} (HTER) \cite{Snover06astudy} and metrics compliant with the \textit{Multidimensional Quality Metric} framework \cite{mqm}. Inspired by recent work on Quality Estimation (QE) that demonstrated that it is possible to achieve high levels of correlation with human judgements even without a reference translation \cite{fonseca-etal-2019-findings}, we propose a novel approach for incorporating the source-language input into our MT evaluation models. Traditionally only QE models have made use of the source input, whereas MT evaluation metrics rely instead on the reference translation. We show that using a multilingual embedding space allows us to leverage information from all three inputs and demonstrate the value added by the source as input to our MT evaluation models. To illustrate the effectiveness and flexibility of the {\sc Comet} framework, we train three models that estimate different types of human judgements and show promising progress towards both better correlation at segment level and robustness to high-quality MT. We will release both the {\sc Comet} framework and the trained MT evaluation models described in this paper to the research community upon publication. \section{Model Architectures} \label{sec:model} Human judgements of MT quality usually come in the form of segment-level scores, such as DA, MQM and HTER. For DA, it is common practice to convert scores into relative rankings ({\small DA}RR) when the number of annotations per segment is limited \cite{bojar-etal-2017-results, ma-etal-2018-results, ma-etal-2019-results}. This means that, for two MT hypotheses $h_i$ and $h_j$ of the same source $s$, if the DA score assigned to $h_i$ is higher than the score assigned to $h_j$, $h_i$ is regarded as a ``better'' hypothesis.\footnote{In the WMT Metrics Shared Task, if the difference between the DA scores is not higher than 25 points, those segments are excluded from the {\scriptsize DA}RR data.} To encompass these differences, our framework supports two distinct architectures: The {\bf Estimator model} and the {\bf Translation Ranking model}. The fundamental difference between them is the training objective. While the Estimator is trained to regress directly on a quality score, the Translation Ranking model is trained to minimize the distance between a ``better'' hypothesis and both its corresponding reference and its original source. Both models are composed of a cross-lingual encoder and a pooling layer. \subsection{Cross-lingual Encoder} \label{ssec:encoder} The primary building block of all the models in our framework is a pretrained, cross-lingual model such as multilingual BERT \cite{devlin-etal-2019-bert}, XLM \cite{NIPS2019_8928} or XLM-RoBERTa \cite{conneau2019unsupervised}. These models contain several transformer encoder layers that are trained to reconstruct masked tokens by uncovering the relationship between those tokens and the surrounding ones. When trained with data from multiple languages this pretrained objective has been found to be highly effective in cross-lingual tasks such as document classification and natural language inference \cite{conneau2019unsupervised}, generalizing well to unseen languages and scripts \citep{pires-etal-2019-multilingual}. For the experiments in this paper, we rely on XLM-RoBERTa (base) as our encoder model. Given an input sequence $x = \left[x_0, x_1, ..., x_n\right]$, the encoder produces an embedding $\bm{e}_{j}^{(\ell)}$ for each token $x_j$ and each layer $\ell \in \{0,1,...,k\}$. In our framework, we apply this process to the source, MT hypothesis, and reference in order to map them into a shared feature space. \subsection{Pooling Layer} \label{ssec:pooling} The embeddings generated by the last layer of the pretrained encoders are usually used for fine-tuning models to new tasks. However, \citep{tenney-etal-2019-bert} showed that different layers within the network can capture linguistic information that is relevant for different downstream tasks. In the case of MT evaluation, \citep{ZhangBERTScore} showed that different layers can achieve different levels of correlation and that utilizing only the last layer often results in inferior performance. In this work, we used the approach described in \citet{peters-etal-2018-deep} and pool information from the most important encoder layers into a single embedding for each token, $\bm{e}_{j}$, by using a layer-wise attention mechanism. This embedding is then computed as: \vspace{-5pt} \begin{equation} \label{eq:attention} \bm{e}_{x_j} = \mu {E}_{x_j}^\top \bm{\alpha} \end{equation} where $\mu$ is a trainable weight coefficient, $\bm{E}_{j} = [\bm{e}_{j}^{(0)}, \bm{e}_{j}^{(1)}, \dots\, \bm{e}_{j}^{(k)}]$ corresponds to the vector of layer embeddings for token $x_j$, and $\bm{\alpha} = \textrm{softmax} ([\alpha^{(1)}, \alpha^{(2)}, \dots, \alpha^{(k)}])$ is a vector corresponding to the layer-wise trainable weights. In order to avoid overfitting to the information contained in any single layer, we used layer dropout \cite{kondratyuk-straka-2019-75}, in which with a probability $p$ the weight $\alpha^{(i)}$ is set to $-\infty$. Finally, as in \cite{reimers-gurevych-2019-sentence}, we apply average pooling to the resulting word embeddings to derive a sentence embedding for each segment. \subsection{Estimator Model} \label{ssec:estimator} \begin{figure*} \centering \begin{minipage}{.48\textwidth} \centering \includegraphics[width=1.0\linewidth]{images/small_estimator.jpg} \caption{Estimator model architecture. The source, hypothesis and reference are independently encoded using a pretrained cross-lingual encoder. The resulting word embeddings are then passed through a pooling layer to create a sentence embedding for each segment. Finally, the resulting sentence embeddings are combined and concatenated into one single vector that is passed to a feed-forward regressor. The entire model is trained by minimizing the Mean Squared Error (MSE). } \label{fig:estimator} \end{minipage}% \hfill \begin{minipage}{.48\textwidth} \centering \vspace{25pt} \includegraphics[width=1.0\linewidth]{images/small_ranker.jpg} \caption{Translation Ranking model architecture. This architecture receives 4 segments: the source, the reference, a ``better'' hypothesis, and a ``worse'' one. These segments are independently encoded using a pretrained cross-lingual encoder and a pooling layer on top. Finally, using the triplet margin loss \cite{SchroffKP15} we optimize the resulting embedding space to minimize the distance between the ``better'' hypothesis and the ``anchors'' (source and reference).} \label{fig:ranking_model} \end{minipage} \end{figure*} Given a $d$-dimensional sentence embedding for the source, the hypothesis, and the reference, we adopt the approach proposed in RUSE \cite{shimanaka-etal-2018-ruse} and extract the following combined features: \begin{itemize} \item Element-wise source product: $\bm{h} \odot \bm{s}$ \item Element-wise reference product: $\bm{h} \odot \bm{r}$ \item Absolute element-wise source difference: $|\bm{h} - \bm{s}|$ \item Absolute element-wise reference difference: $|\bm{h} - \bm{r}|$ \end{itemize} These combined features are then concatenated to the reference embedding $\bm{r}$ and hypothesis embedding $\bm{h}$ into a single vector $\bm{x} = [\bm{h}; \bm{r}; \bm{h} \odot \bm{s}; \bm{h} \odot \bm{r}; |\bm{h} - \bm{s}|; |\bm{h} - \bm{r}|]$ that serves as input to a feed-forward regressor. The strength of these features is in highlighting the differences between embeddings in the semantic feature space. The model is then trained to minimize the mean squared error between the predicted scores and quality assessments (DA, HTER or MQM). Figure~\ref{fig:estimator} illustrates the proposed architecture. Note that we chose not to include the raw source embedding ($\bm{s}$) in our concatenated input. Early experimentation revealed that the value added by the source embedding as extra input features to our regressor was negligible at best. A variation on our HTER estimator model trained with the vector $\bm{x} = [\bm{h}; \bm{s}; \bm{r}; \bm{h} \odot \bm{s}; \bm{h} \odot \bm{r}; |\bm{h} - \bm{s}|; |\bm{h} - \bm{r}|]$ as input to the feed-forward only succeed in boosting segment-level performance in 8 of the 18 language pairs outlined in section \ref{sec:results} below and the average improvement in Kendall's Tau in those settings was +0.0009. As noted in \citet{zhao2020limitations}, while cross-lingual pretrained models are adaptive to multiple languages, the feature space between languages is poorly aligned. On this basis we decided in favor of excluding the source embedding on the intuition that the most important information comes from the reference embedding and reducing the feature space would allow the model to focus more on relevant information. This does not however negate the general value of the source to our model; where we include combination features such as $\bm{h} \odot \bm{s}$ and $|\bm{h} - \bm{s}|$ we do note gains in correlation as explored further in section \ref{sect:source-value} below. \subsection{Translation Ranking Model} \label{ssec:ranking} Our Translation Ranking model (Figure \ref{fig:ranking_model}) receives as input a tuple $\chi = (s, h^{+}, h^{-}, r)$ where $h^{+}$ denotes an hypothesis that was ranked higher than another hypothesis $h^{-}$. We then pass $\chi$ through our cross-lingual encoder and pooling layer to obtain a sentence embedding for each segment in the $\chi$. Finally, using the embeddings $\{\bm{s}, \bm{h^{+}}, \bm{h^{-}}, \bm{r}\}$, we compute the triplet margin loss \cite{SchroffKP15} in relation to the source and reference: \vspace{-10pt} \begin{equation} \label{eq:tloss} \begin{split} L(\chi) &= L(\bm{s}, \bm{h^{+}}, \bm{h^{-}}) + L(\bm{r}, \bm{h^{+}}, \bm{h^{-}}) \end{split} \end{equation} where: \begin{equation} \label{eq:tloss1} \begin{split} L(\bm{s}, \bm{h^{+}}, \bm{h^{-}}) = \\ \max\{0, d(&\bm{s}, \bm{h^{+}})\ - d(\bm{s}, \bm{h^{-}}) + \epsilon\} \end{split} \end{equation} \begin{equation} \label{eq:tloss2} \begin{split} L(\bm{r}, \bm{h^{+}}, \bm{h^{-}}) = \\ \max\{0, d(&\bm{r}, \bm{h^{+}})\ - d(\bm{r}, \bm{h^{-}}) + \epsilon\} \end{split} \end{equation} $d(\bm{u}, \bm{v})$ denotes the euclidean distance between $\bm{u}$ and $\bm{v}$ and $\epsilon$ is a margin. Thus, during training the model optimizes the embedding space so the distance between the anchors ($\bm{s}$ and $\bm{r}$) and the ``worse'' hypothesis $\bm{h^{-}}$ is greater by at least $\epsilon$ than the distance between the anchors and ``better'' hypothesis $\bm{h^{+}}$. During inference, the described model receives a triplet $(s, \hat{h}, r)$ with only one hypothesis. The quality score assigned to $\hat{h}$ is the harmonic mean between the distance to the source $d(\bm{s}, \bm{\hat{h}})$ and the distance to the reference $d(\bm{r}, \bm{\hat{h}})$: \begin{equation} \label{eq:ranking_inference} \begin{split} f(s, \hat{h}, r) = \frac{2 \times d(\bm{r}, \bm{\hat{h}}) \times d(\bm{s}, \bm{\hat{h}})}{d(\bm{r}, \bm{\hat{h}}) + d(\bm{s}, \bm{\hat{h}})} \end{split} \end{equation} Finally, we convert the resulting distance into a similarity score bounded between 0 and 1 as follows: \begin{equation} \label{eq:ranking_similarity} \begin{split} \hat{f}(s, \hat{h}, r) = \frac{1}{1+f(s, \hat{h}, r)} \end{split} \end{equation} \section{Corpora} \label{sec:Corpora} To demonstrate the effectiveness of our described model architectures (section \ref{sec:model}), we train three MT evaluation models where each model targets a different type of human judgment. To train these models, we use data from three different corpora: the QT21 corpus, the {\small DA}RR from the WMT Metrics shared task (2017 to 2019) and a proprietary MQM annotated corpus. \subsection{The QT21 corpus} \label{sec:qt21} The QT21 corpus is a publicly available\footnote{QT21 data: \url{https://lindat.mff.cuni.cz/repository/xmlui/handle/11372/LRT-2390}} dataset containing industry generated sentences from either an information technology or life sciences domains \cite{specia-etal_MTSummit:2017}. This corpus contains a total of 173K tuples with source sentence, respective human-generated reference, MT hypothesis (either from a phrase-based statistical MT or from a neural MT), and post-edited MT (PE). The language pairs represented in this corpus are: English to German (en-de), Latvian (en-lt) and Czech (en-cs), and German to English (de-en). The HTER score is obtained by computing the translation edit rate (TER) \cite{Snover06astudy} between the MT hypothesis and the corresponding PE. Finally, after computing the HTER for each MT, we built a training dataset $D = \{s_i, h_i, r_i, y_i\}_{n=1}^N$, where $s_i$ denotes the source text, $h_i$ denotes the MT hypothesis, $r_i$ the reference translation, and $y_i$ the HTER score for the hypothesis $h_i$. In this manner we seek to learn a regression $f(s, h, r) \rightarrow y $ that predicts the human-effort required to correct the hypothesis by looking at the source, hypothesis, and reference (but not the post-edited hypothesis). \subsection{The WMT {\small DA}RR corpus} \label{sec:daRR} Since 2017, the organizers of the WMT News Translation Shared Task \cite{barrault-etal-2019-findings} have collected human judgements in the form of adequacy DAs \cite{graham-etal-2013-continuous, graham-etal-2014-machine, graham_baldwin_moffat_zobel_2017}. These DAs are then mapped into relative rankings ({\small DA}RR) \cite{ma-etal-2019-results}. The resulting data for each year (2017-19) form a dataset $D = \{s_i, h_i^+, h_i^-, r_i\}_{n=1}^N$ where $h_i^+$ denotes a ``better'' hypothesis and $h_i^-$ denotes a ``worse'' one. Here we seek to learn a function $r(s, h, r)$ such that the score assigned to $h_i^+$ is strictly higher than the score assigned to $h_i^-$ ($r(s_i, h_i^+, r_i) > r(s_i, h_i^-, r_i)$). This data\footnote{The raw data for each year of the WMT Metrics shared task is publicly available in the results page (2019 example: \url{http://www.statmt.org/wmt19/results.html}). Note, however, that in the \texttt{README} files it is highlighted that this data is not well documented and the scripts occasionally require custom utilities that are not available.} contains a total of 24 high and low-resource language pairs such as Chinese to English (zh-en) and English to Gujarati (en-gu). \subsection{The MQM corpus} \label{sec:mqm} The MQM corpus is a proprietary internal database of MT-generated translations of customer support chat messages that were annotated according to the guidelines set out in \citet{mqm_guidelines}. This data contains a total of 12K tuples, covering 12 language pairs from English to: German (en-de), Spanish (en-es), Latin-American Spanish (en-es-latam), French (en-fr), Italian (en-it), Japanese (en-ja), Dutch (en-nl), Portuguese (en-pt), Brazilian Portuguese (en-pt-br), Russian (en-ru), Swedish (en-sv), and Turkish (en-tr). Note that in this corpus English is always seen as the source language, but never as the target language. Each tuple consists of a source sentence, a human-generated reference, a MT hypothesis, and its MQM score annotated by one (or more) professional editors. The MQM metric referred to throughout this paper is an internal metric defined in accordance with the MQM framework \citep{mqm} (MQM). Errors are annotated under an internal typology defined under three main error types; `Style', `Fluency' and `Accuracy'. Our MQM scores range from $-\infty$ to 100 and are defined as: \begin{equation} \label{eq:mqm} \begin{split} \text{\footnotesize MQM} = 100 - \frac{{I}_{\text{\scriptsize Minor}} + 5 \times {I}_{\text{\scriptsize Major}} + 10 \times {I}_{\text{\scriptsize Crit.}}}{\text{\footnotesize Sentence Length} \times 100} \end{split} \end{equation} where ${I}_{\text{\scriptsize Minor}}$ denotes the number of minor errors, ${I}_{\text{\scriptsize Major}}$ the number of major errors and ${I}_{\text{\scriptsize Crit.}}$ the number of critical errors. Our MQM metric takes into account the severity of the errors identified in the MT hypothesis, leading to a more fine-grained metric than HTER or DA. When used in our experiments, these values were divided by 100 and truncated at 0. As in section~\ref{sec:qt21}, we constructed a training dataset $D = \{s_i, h_i, r_i, y_i\}_{n=1}^N$, where $s_i$ denotes the source text, $h_i$ denotes the MT hypothesis, $r_i$ the reference translation, and $y_i$ the MQM score for the hypothesis $h_i$. \begin{table*}[!ht] \centering \caption{Kendall's Tau ($\tau$) correlations on language pairs with English as source for the WMT19 Metrics {\footnotesize DA}RR corpus. For {\sc Bertscore} we report results with the default encoder model for a complete comparison, but also with XLM-RoBERTa (base) for fairness with our models. The values reported for YiSi-1 are taken directly from the shared task paper \cite{ma-etal-2019-results}.} \label{tab:english-to-x2019} \begin{tabular}{lcccccccc} \hline \textbf{Metric} & \textbf{en-cs} & \textbf{en-de} & \textbf{en-fi} & \textbf{en-gu} & \textbf{en-kk} & \textbf{en-lt} & \textbf{en-ru} & \textbf{en-zh} \\ \specialrule{1.5pt}{1pt}{1pt} {\sc Bleu} & 0.364 & 0.248 & 0.395 & 0.463 & 0.363 & 0.333 & 0.469 & 0.235 \\ {\sc chrF} & 0.444 & 0.321 & 0.518 & 0.548 & 0.510 & 0.438 & 0.548 & 0.241 \\ {\sc YiSi-1} & 0.475 & 0.351 & 0.537 & 0.551 & 0.546 & 0.470 & 0.585 & 0.355 \\ {\sc Bertscore} {\footnotesize ({default})} & 0.500 & 0.363 & 0.527 & 0.568 & 0.540 & 0.464 & 0.585 & 0.356 \\ {\sc Bertscore} {\footnotesize ({xlmr-base})} & 0.503 & 0.369 & 0.553 & 0.584 & 0.536 & 0.514 & 0.599 & 0.317 \\ \hline {\sc Comet-hter} & 0.524 & 0.383 & 0.560 & 0.552 & 0.508 & 0.577 & 0.539 & 0.380 \\ {\sc Comet-mqm} & 0.537 & 0.398 & 0.567 & 0.564 & 0.534 & 0.574 & \textbf{0.615} & 0.378 \\ {\sc Comet-rank} & \textbf{0.603} & \textbf{0.427} & \textbf{0.664} & \textbf{0.611} & \textbf{0.693} & \textbf{0.665} & 0.580 & \textbf{0.449} \\ \hline \end{tabular} \end{table*} \section{Experiments} \label{sec:experiments} We train two versions of the Estimator model described in section \ref{ssec:estimator}: one that regresses on HTER (\textbf{{\sc Comet-hter}}) trained with the QT21 corpus, and another that regresses on our proprietary implementation of MQM (\textbf{{\sc Comet-mqm}}) trained with our internal MQM corpus. For the Translation Ranking model, described in section \ref{ssec:ranking}, we train with the WMT {\small DA}RR corpus from 2017 and 2018 (\textbf{{\sc Comet-rank}}). In this section, we introduce the training setup for these models and corresponding evaluation setup. \subsection{Training Setup} \label{ssec:estimator_setup} The two versions of the Estimators (\textbf{{\sc Comet-HTER/MQM}}) share the same training setup and hyper-parameters (details are included in the Appendices). For training, we load the pretrained encoder and initialize both the pooling layer and the feed-forward regressor. Whereas the layer-wise scalars $\bm{\alpha}$ from the pooling layer are initially set to zero, the weights from the feed-forward are initialized randomly. During training, we divide the model parameters into two groups: the encoder parameters, that include the encoder model and the scalars from $\bm{\alpha}$; and the regressor parameters, that include the parameters from the top feed-forward network. We apply gradual unfreezing and discriminative learning rates \cite{howard-ruder-2018-universal}, meaning that the encoder model is frozen for one epoch while the feed-forward is optimized with a learning rate of $3\mathrm{e}{-5}$. After the first epoch, the entire model is fine-tuned but the learning rate for the encoder parameters is set to $1\mathrm{e}{-5}$ in order to avoid catastrophic forgetting. In contrast with the two Estimators, for the \textbf{{\sc Comet-rank}} model we fine-tune from the outset. Furthermore, since this model does not add any new parameters on top of XLM-RoBERTa (base) other than the layer scalars $\bm{\alpha}$, we use one single learning rate of $1\mathrm{e}{-5}$ for the entire model. \subsection{Evaluation Setup} \label{ssec:metrics} We use the test data and setup of the WMT 2019 Metrics Shared Task \cite{ma-etal-2019-results} in order to compare the {\sc Comet} models with the top performing submissions of the shared task and other recent state-of-the-art metrics such as {\sc Bertscore} and {\sc Bleurt}.\footnote{To ease future research we will also provide, within our framework, detailed instructions and scripts to run other metrics such as {\sc chrF}, {\sc Bleu}, {\sc Bertscore}, and {\sc Bleurt}} The evaluation method used is the official Kendall's Tau-like formulation, $\tau$, from the WMT 2019 Metrics Shared Task \cite{ma-etal-2019-results} defined as: \begin{equation} \label{eq:kendall} \tau = \frac{\textit{Concordant} - \textit{Discordant}}{\textit{Concordant} + \textit{Discordant}} \end{equation} where \textit{Concordant} is the number of times a metric assigns a higher score to the ``better'' hypothesis $h^+$ and \textit{Discordant} is the number of times a metric assigns a higher score to the ``worse'' hypothesis $h^-$ or the scores assigned to both hypotheses is the same. As mentioned in the findings of \cite{ma-etal-2019-results}, segment-level correlations of all submitted metrics were frustratingly low. Furthermore, all submitted metrics exhibited a dramatic lack of ability to correctly rank strong MT systems. To evaluate whether our new MT evaluation models better address this issue, we followed the described evaluation setup used in the analysis presented in \cite{ma-etal-2019-results}, where correlation levels are examined for portions of the {\small DA}RR data that include only the top 10, 8, 6 and 4 MT systems. \begin{table*}[!ht] \centering \caption{Kendall's Tau ($\tau$) correlations on language pairs with English as a target for the WMT19 Metrics {\footnotesize DA}RR corpus. As for {\sc Bertscore}, for {\sc Bleurt} we report results for two models: the base model, which is comparable in size with the encoder we used and the large model that is twice the size.} \label{tab:x-to-english2019} \begin{tabular}{llllllll} \hline \textbf{Metric} & \textbf{de-en} & \textbf{fi-en} & \textbf{gu-en} & \textbf{kk-en} & \textbf{lt-en} & \textbf{ru-en} & \textbf{zh-en} \\ \specialrule{1.5pt}{1pt}{1pt} {\sc Bleu} & 0.053 & 0.236 & 0.194 & 0.276 & 0.249 & 0.177 & 0.321 \\ {\sc chrF} & 0.123 & 0.292 & 0.240 & 0.323 & 0.304 & 0.115 & 0.371 \\ {\sc YiSi-1} & 0.164 & 0.347 & 0.312 & \textbf{0.440} & 0.376 & 0.217 & 0.426 \\ {\sc Bertscore} {\footnotesize ({default})} & 0.190 & 0.354 & 0.292 & 0.351 & 0.381 & 0.221 & 0.432 \\ {\sc Bertscore} {\footnotesize ({xlmr-base})} & 0.171 & 0.335 & 0.295 & 0.354 & 0.356 & 0.202 & 0.412 \\ {\sc Bleurt} {\footnotesize ({base-128})} & 0.171 & 0.372 & 0.302 & 0.383 & 0.387 & 0.218 & 0.417 \\ {\sc Bleurt} {\footnotesize ({large-512})} & 0.174 & 0.374 & 0.313 & 0.372 & 0.388 & \textbf{0.220} & 0.436 \\ \hline {\sc Comet-hter} & 0.185 & 0.333 & 0.274 & 0.297 & 0.364 & 0.163 & 0.391 \\ {\sc Comet-mqm} & \textbf{0.207} & 0.343 & 0.282 & 0.339 & 0.368 & 0.187 & 0.422 \\ {\sc Comet-rank} & 0.202 & \textbf{0.399} & \textbf{0.341} & 0.358 & \textbf{0.407} & 0.180 & \textbf{0.445} \\ \hline \end{tabular} \end{table*} \section{Results} \label{sec:results} \subsection{From English into X} \label{ssec:from-English} Table \ref{tab:english-to-x2019} shows results for all eight language pairs with English as source. We contrast our three {\sc Comet} models against baseline metrics such as {\sc Bleu} and {\sc chrF}, the 2019 task winning metric {\sc YiSi-1}, as well as the more recent {\sc Bertscore}. We observe that across the board our three models trained with the {\sc Comet} framework outperform, often by significant margins, all other metrics. Our {\small DA}RR Ranker model outperforms the two Estimators in seven out of eight language pairs. Also, even though the MQM Estimator is trained on only 12K annotated segments, it performs roughly on par with the HTER Estimator for most language-pairs, and outperforms all the other metrics in en-ru. \subsection{From X into English} \label{sect:into-english} Table \ref{tab:x-to-english2019} shows results for the seven to-English language pairs. Again, we contrast our three {\sc Comet} models against baseline metrics such as {\sc Bleu} and {\sc chrF}, the 2019 task winning metric {\sc YiSi-1}, as well as the recently published metrics {\sc Bertscore} and {\sc Bleurt}. As in Table \ref{tab:english-to-x2019} the {\small DA}RR model shows strong correlations with human judgements outperforming the recently proposed English-specific {\sc Bleurt} metric in five out of seven language pairs. Again, the MQM Estimator shows surprising strong results despite the fact that this model was trained with data that did not include English as a target. Although the encoder used in our trained models is highly multilingual, we hypothesise that this powerful ``zero-shot'' result is due to the inclusion of the source in our models. \subsection{Language pairs not involving English} \label{sect:no-english} \begin{table}[!ht] \centering \caption{Kendall's Tau ($\tau$) correlations on language pairs not involving English for the WMT19 Metrics {\small DA}RR corpus.} \label{tab:not-english2019} \begin{tabular}{llll} \hline \textbf{Metric} & \textbf{de-cs} & \textbf{de-fr} & \textbf{fr-de} \\ \specialrule{1.5pt}{1pt}{1pt} {\sc Bleu} & 0.222 & 0.226 & 0.173 \\ {\sc chrF} & 0.341 & 0.287 & 0.274 \\ {\sc YiSi-1} & 0.376 & 0.349 & 0.310 \\ {\sc Bertscore} {\footnotesize ({default})} & 0.358 & 0.329 & 0.300 \\ {\sc Bertscore} {\footnotesize ({xlmr-base})} & 0.386 & 0.336 & 0.309 \\ \hline {\sc Comet-hter} & 0.358 & 0.397 & 0.315 \\ {\sc Comet-mqm} & 0.386 & 0.367 & 0.296 \\ {\sc Comet-rank} & \textbf{0.389} & \textbf{0.444} & \textbf{0.331} \\ \hline \end{tabular} \end{table} All three of our {\sc Comet} models were trained on data involving English (either as a source or as a target). Nevertheless, to demonstrate that our metrics generalize well we test them on the three WMT 2019 language pairs that do not include English in either source or target. As can be seen in Table \ref{tab:not-english2019}, our results are consistent with observations in Tables \ref{tab:english-to-x2019} and \ref{tab:x-to-english2019}. \subsection{Robustness to High-Quality MT} \label{sect:top-systems} For analysis, we use the {\small DA}RR corpus from the 2019 Shared Task and evaluate on the subset of the data from the top performing MT systems for each language pair. We included language pairs for which we could retrieve data for at least ten different MT systems (i.e. all but kk-en and gu-en). We contrast against the strong recently proposed {\sc Bertscore} and {\sc Bleurt}, with {\sc Bleu} as a baseline. Results are presented in Figure \ref{fig:Top models}. For language pairs where English is the target, our three models are either better or competitive with all others; where English is the source we note that in general our metrics exceed the performance of others. Even the MQM Estimator, trained with only 12K segments, is competitive, which highlights the power of our proposed framework. \begin{figure}[ht!] \centering \begin{tikzpicture}[scale=0.8, transform shape] \pgfplotsset{every axis legend/.append style={ at={(0.5,1.03)}, anchor=south}} \begin{axis}[ xlabel=Top models from X to English, ylabel=Kendall Tau ($\tau$), xticklabels={ , , All, 10 , 8, 6, 4}, legend columns=2] \addplot[color=Unbabel7,mark=x] coordinates { (1, 0.327) (2, 0.240) (3, 0.198) (4, 0.165) (5 , 0.134) }; \addplot[color=red,mark=x] coordinates { (1, 0.207) (2, 0.115) (3, 0.07) (4, 0.062) (5 , 0.026) }; \addplot[color=Unbabel2,mark=x] coordinates { (1, 0.305) (2, 0.227) (3, 0.192) (4, 0.174) (5 , 0.150) }; \addplot[color=Unbabel5,mark=x] coordinates { (1, 0.316) (2, 0.230) (3, 0.192) (4, 0.167) (5 , 0.126) }; \addplot[color=Unbabel1,mark=x] coordinates { (1, 0.287) (2, 0.215) (3, 0.175) (4, 0.159) (5 , 0.143) }; \addplot[color=Unbabel4,mark=x] coordinates { (1, 0.318) (2, 0.227) (3, 0.175) (4, 0.151) (5 , 0.104]) }; \legend{{\sc Comet-rank},{\sc Bleu},{\sc Comet-mqm},{\sc Bertscore},{\sc Comet-hter}, {\sc Bleurt}} \end{axis} \end{tikzpicture} \begin{tikzpicture}[scale=0.8, transform shape] \begin{axis}[ xlabel=Top models from English to X, ylabel=Kendall Tau ($\tau$), xticklabels={ , , All, 10 , 8, 6, 4}, ] \addplot[color=red,mark=x] coordinates { (1, 0.363) (2, 0.170) (3, 0.106) (4, 0.068) (5 , 0.045) }; \addplot[color=Unbabel5,mark=x] coordinates { (1, 0.488) (2, 0.370) (3, 0.296) (4, 0.256) (5 , 0.226) }; \addplot[color=Unbabel7,mark=x] coordinates { (1, 0.587) (2, 0.442) (3, 0.355) (4, 0.326) (5 , 0.302) }; \addplot[color=Unbabel2,mark=x] coordinates { (1, 0.521) (2, 0.405) (3, 0.334) (4, 0.294) (5 , 0.260) }; \addplot[color=Unbabel1,mark=x] coordinates { (1, 0.503) (2, 0.393) (3, 0.318) (4, 0.271) (5 , 0.239) }; \end{axis} \end{tikzpicture} \caption{Metrics performance over all and the top (10, 8, 6, and 4) MT systems.} \label{fig:Top models} \end{figure} \subsection{The Importance of the Source} \begin{table*}[!ht] \centering \caption{Comparison between {\sc Comet-rank} (section \ref{ssec:ranking}) and a reference-only version thereof on WMT18 data. Both models were trained with WMT17 which means that the reference-only model is never exposed to English during training.} \label{tab:value-src} \begin{tabular}{lllllllll} \hline \textbf{Metric} & \textbf{en-cs} & \textbf{en-de} & \textbf{en-fi} & \textbf{en-tr} & \textbf{cs-en} & \textbf{de-en} & \textbf{fi-en} & \textbf{tr-en} \\ \specialrule{1.5pt}{1pt}{1pt} \multicolumn{1}{l|}{{\sc Comet-rank} \footnotesize ({ref. only})} & 0.660 & 0.764 & 0.630 & \multicolumn{1}{l|}{0.539} & 0.249 & 0.390 & 0.159 & 0.128 \\ \multicolumn{1}{l|}{{\sc Comet-rank}} & 0.711 & 0.799 & 0.671 & \multicolumn{1}{l|}{0.563} & 0.356 & 0.542 & 0.278 & 0.260 \\ \hline \multicolumn{1}{l|}{$\Delta \tau$} & 0.051 & 0.035 & 0.041 & \multicolumn{1}{l|}{0.024} & \textbf{0.107} & \textbf{0.155} & \textbf{0.119} & \textbf{0.132} \\ \hline \end{tabular} \end{table*} \label{sect:source-value} To shed some light on the actual value and contribution of the source language input in our models' ability to learn accurate predictions, we trained two versions of our {\small DA}RR Ranker model: one that uses only the reference, and another that uses both reference and source. Both models were trained using the WMT 2017 corpus that only includes language pairs from English (en-de, en-cs, en-fi, en-tr). In other words, while English was never observed as a target language during training for both variants of the model, the training of the second variant includes English source embeddings. We then tested these two model variants on the WMT 2018 corpus for these language pairs and for the reversed directions (with the exception of en-cs because cs-en does not exist for WMT 2018). The results in Table \ref{tab:value-src} clearly show that for the translation ranking architecture, including the source improves the overall correlation with human judgments. Furthermore, the inclusion of the source exposed the second variant of the model to English embeddings which is reflected in a higher $\Delta \tau$ for the language pairs with English as a target. \section{Reproducibility} \label{sec:reproducibility} We will release both the code-base of the {\sc Comet} framework and the trained MT evaluation models described in this paper to the research community upon publication, along with the detailed scripts required in order to run all reported baselines.\footnote{These will be hosted at: \url{https://github.com/Unbabel/COMET}} All the models reported in this paper were trained on a single Tesla T4 (16GB) GPU. Moreover, our framework builds on top of PyTorch Lightning \cite{falcon2019pytorch}, a lightweight PyTorch wrapper, that was created for maximal flexibility and reproducibility. \section{Related Work} \label{sec:literature-review} Classic MT evaluation metrics are commonly characterized as \textbf{$n$-gram matching metrics} because, using hand-crafted features, they estimate MT quality by counting the number and fraction of $n$-grams that appear simultaneous in a candidate translation hypothesis and one or more human-references. Metrics such as {\sc Bleu} \cite{papineni-etal-2002-bleu}, {\sc Meteor} \cite{banerjee-lavie-meteor2009}, and {\sc chrF} \cite{popovic-2015-chrf} have been widely studied and improved \cite{koehn-etal-2007-moses, popovic-2017-chrf, denkowski-lavie-2011-meteor, guo-hu-2019-meteor}, but, by design, they usually fail to recognize and capture semantic similarity beyond the lexical level. In recent years, word embeddings \cite{NIPS2013_5021, pennington-etal-2014-glove, peters-etal-2018-deep, devlin-etal-2019-bert} have emerged as a commonly used alternative to $n$-gram matching for capturing word semantics similarity. \textbf{Embedding-based metrics} like {\sc YiSi-1} \cite{lo-2019-yisi}, {\sc MoverScore} \cite{zhao-etal-2019-moverscore} and {\sc Bertscore} \cite{ZhangBERTScore} create soft-alignments between reference and hypothesis in an embedding space and then compute a score that reflects the semantic similarity between those segments. However, human judgements such as DA and MQM, capture much more than just semantic similarity, resulting in a correlation upper-bound between human judgements and the scores produced by such metrics. \textbf{Learnable metrics} \cite{shimanaka-etal-2018-ruse, mathur-etal-2019-putting} attempt to directly optimize the correlation with human judgments, and have recently shown promising results. {\sc Bleurt} \cite{Sellam&das-bleurt}, a learnable metric based on BERT \cite{devlin-etal-2019-bert}, claims state-of-the-art performance for the last 3 years of the WMT Metrics Shared task. Because {\sc Bleurt} builds on top of English-BERT \cite{devlin-etal-2019-bert}, it can only be used when English is the target language which limits its applicability. Also, to the best of our knowledge, all the previously proposed learnable metrics have focused on optimizing DA which, due to a scarcity of annotators, can prove inherently noisy \cite{ma-etal-2019-results}. \textbf{Reference-less MT evaluation}, also known as Quality Estimation (QE), has historically often regressed on HTER for segment-level evaluation \cite{bojar-etal-2013-findings, bojar-etal-2014-findings, bojar-etal-2015-findings, bojar-etal-2016-findings, bojar-etal-2017-findings}. More recently, MQM has been used for document-level evaluation \cite{specia-etal-2018-findings, fonseca-etal-2019-findings}. By leveraging highly multilingual pretrained encoders such as multilingual BERT \cite{devlin-etal-2019-bert} and XLM \cite{NIPS2019_8928}, QE systems have been showing auspicious correlations with human judgements \cite{kepler-etal-2019-unbabels}. Concurrently, the OpenKiwi framework \cite{kepler-etal-2019-openkiwi} has made it easier for researchers to push the field forward and build stronger QE models. \section{Conclusions and Future Work} \label{sec:conclusions} In this paper we present {\sc Comet}, a novel neural framework for training MT evaluation models that can serve as automatic metrics and easily be adapted and optimized to different types of human judgements of MT quality. To showcase the effectiveness of our framework, we sought to address the challenges reported in the 2019 WMT Metrics Shared Task \cite{ma-etal-2019-results}. We trained three distinct models which achieve new state-of-the-art results for segment-level correlation with human judgments, and show promising ability to better differentiate high-performing systems. One of the challenges of leveraging the power of pretrained models is the burdensome weight of parameters and inference time. A primary avenue for future work on {\sc Comet} will look at the impact of more compact solutions such as DistilBERT \citep{sanh2019distilbert}. Additionally, whilst we outline the potential importance of the source text above, we note that our {\sc Comet-rank} model weighs source and reference differently during inference but equally in its training loss function. Future work will investigate the optimality of this formulation and further examine the interdependence of the different inputs. \section*{Acknowledgments} We are grateful to André Martins, Austin Matthews, Fabio Kepler, Daan Van Stigt, Miguel Vera, and the reviewers, for their valuable feedback and discussions. This work was supported in part by the P2020 Program through projects MAIA and Unbabel4EU, supervised by ANI under contract numbers 045909 and 042671, respectively.
{'timestamp': '2020-09-22T02:01:38', 'yymm': '2009', 'arxiv_id': '2009.09025', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09025'}
arxiv
\section{Introduction} \label{sec:1} Variabilities present among the different plant species (also called genotypes) are useful in their breeding programs. Here, the selection of diverse parent genotypes is important. More diverse the parents, the higher are the chances of developing new plant varieties having excellent qualities \citep{cite2}. A commonly used technique here is to study the genetic variability, which looks at the different genome sequences. However, this kind of analysis requires a large number of sequences, while very few are available \citep{Ingvarsson2011,reseq302} because genetic sequencing is computationally and monetarily expensive \citep{sequencing}. Variabilities in plant genotypes can also be studied using their phenotypic characteristics (physical characteristics). This kind of analysis can be relatively easily done because a sufficiently large amount of data is available from different geographical areas. In the phenotypic context, which is our first focus, a few characteristics that play an important role are Days to 50\% Flowering, Days to Maturity, Plant Height, 100 Seed Weight, Seed Yield Per Plant, Number of Branches Per Plant, etc. Cluster analysis is an important tool to describe and summarize the variation present between different plant genotypes \citep{cite2}. Thus, clustering can be used to obtain diverse parents which, as mentioned above, is of paramount importance. It is obvious that after clustering, the genotypes present in the same cluster would have similar characteristics, while those present in different clusters would be diverse. Phenotypic data for the genotypes of different plants (e.g., Soybean, Wheat, Rice, Maize, etc.) usually have enough variation for accurate clustering. However, if this data is obtained for the genotypes of the same plant, then clustering becomes challenging due to less variation in the data, which forms our second focus. Hierarchical Clustering (HC) is a traditional and standard method that is currently being used by plant biologists for grouping of phenotypic data \citep{cite2,wheat,cluster-analysis-1}. However, this method has a few disadvantages. First, it does not provide the level of accuracy required for clustering similar genotypes \citep{hc}. Second, HC is based on building a hierarchical cluster tree (also called dendrogram), which becomes cumbersome and impractical to visualize when the data is too large. To overcome the two disadvantages of HC, in this paper, we propose the use of the Spectral Clustering (SC) algorithm. SC is mathematically sound and is known to give one of the most accurate clustering results among the existing clustering algorithms \citep{sc}. For genome data, we have recently shown substantial accuracy improvements by using SC as well \cite{vqsc}. Furthermore, unlike HC, SC does not generate the intermediate hierarchical cluster tree. To the best of our knowledge, this algorithm has not been applied to phenotypic data in any of the previous works (see the Literature Review Section below). HC, as well as SC, both are computationally expensive. They require substantial computational time when clustering large amounts of data \citep{sc,hc_complexity}. Hence, we use sampling to reduce this complexity. Probability-based sampling techniques have recently gained a lot of attention because of their high accuracy at reduced cost \citep{sampling}. Among these, Pivotal Sampling is most commonly used, and hence, we apply it to phenotypic data \citep{pivotal}. Like for SC, using Pivotal Sampling for phenotypic data is also new. Recently, Vector Quantization (VQ) has given promising results for genetic data \citep{vqsc}. Hence, here we adapt VQ for phenotypic data as well. This also serves as a good standard against which we compare Pivotal Sampling. To summarize, in this paper, we develop a modified SC with Pivotal Sampling algorithm that is especially adapted for phenotypic data. The novelty of our work is in constructing the crucial similarity matrix for the clustering algorithm and defining the probabilities for the sampling technique. Although our algorithm can be applied to any plant genotypes, we test it on around 2400 Soybean genotypes obtained from Indian Institute of Soybean Research, Indore, India \citep{phenotypic-data}. In the experiments, we perform two sets of comparisons. {\it First}, our algorithm outperforms all the proposed competitive clustering algorithms with sampling in terms of the accuracy (i.e. modified SC with VQ, HC with Pivotal Sampling, and HC with VQ). The computational complexities of all these algorithms are similar because of the involved sampling. {\it Second}, our modified SC with Pivotal Sampling doubly outperforms HC, which as earlier, is a standard in the plant studies domain. In terms of the accuracy, we are up to 45\% more accurate. In terms of complexity, our algorithm is more than a magnitude cheaper than HC. The rest of this paper is organized as follows. Section \ref{sec:2} provides a brief summary of the previous works on HC for phenotypic data.\footnote{Since none of the previous works have used sampling for phenotypic data, we could not review this aspect.} The standard algorithms for Pivotal Sampling and SC are discussed in Section \ref{sec:3}. Section \ref{sec4} describes the crucial adaptations done in Pivotal Sampling and SC for phenotypic data. The validation metric, the experimental set-up, and the results are presented in Section \ref{sec:5}. Finally, Section \ref{sec:6} gives conclusions and future work. \section{Literature Review} \label{sec:2} In this section, we present some relevant previous studies on phenotypic data and the novelty of our approach. Broadly, these studies can be classified into two categories. The first category consists of the works that identify the correlation between the different phenotypic characteristics (for example, less plant height may indicate less plant yield). The second category consists of the studies that identify the genotypes having dissimilar properties for the breeding program. Initially, we present few works belonging to the first category. Immanuel et al. \citep{rice1} in 2011 measured nine traits of 21 Rice genotypes. Grain Yield was kept as the primary characteristic, and its correlations with all others were obtained. It was observed that several traits like Plant Height, Days to 50\% Flowering, Number of Tillers per Plant, Filled Grains per Panicle and Panicle Length were positively correlated with Grain Yield. Divya et al. \citep{rice2} in 2015 investigated the association between Infected Leaf Area, Blast Disease Susceptibility, Number of Tillers and Grain Yield traits of two Rice genotypes. The authors concluded that Infected Leaf Area had a significant positive correlation with leaf's Blast Susceptibility. Also, Number of Tillers exhibited the highest association with Grain Yield. Huang et al. \citep{leaf} in 2018 exploited leaf shapes and clustered 206 Soybean genotypes into three clusters using the $k$-means clustering algorithm. These clusters contained genotypes having elliptical leaves, lanceolate leaves and round leaves. Then, the authors studied variation present among the different phenotypic characteristics of these categories. They deduced that the cluster containing lanceolate leaves had maximum average Plant Height, Number of Pods per Plant, Number of Branches per Plant, and 100-Seed Weight, while the other two clusters had less values for these traits. Carpentieri-Pipolo et al. \citep{endobacteria} in 2019 investigated the effects of endophytic bacteria on $45$ phenotypic characteristics of a Soybean genotype. The authors clustered these bacteria into three clusters using Unweighted Pair Group Method using Arithmetic Mean (UPGMA) and studied whether the bacteria had positive or negative activity on the phenotypic traits. It was found that five bacteria in one cluster had positive activities on almost $40$ characteristics, while fifteen bacteria in the remaining two clusters had positive activities on around 25 characteristics only. Next, we present works that belong to the second category. Sharma et al. \citep{wheat} in 2014 performed clustering of $24$ synthetic Wheat genotypes (lines) to identify High Heat Tolerant (HHT) lines among them. Cluster analysis was performed using HC, and the Wheat lines were grouped into three clusters. This study aimed to improve heat tolerance of Wheat lines in a breeding program by identifying the diverse Wheat breeders. A similar study for accessing the drought tolerance of spring and winter bread Wheat using phenotypic data was conducted by Dodig et al. in 2010 \citep{wheat2}. Painkra et al. \citep{cite2} in 2018 performed clustering of $273$ Soybean genotypes to determine the diversity among them. Here, the authors clustered them into seven groups using HC. Most diverse genotypes were obtained from the clusters having the highest inter-cluster distance values. According to the authors, choosing the genotypes belonging to the distant clusters maximized heterosis\footnote{Heterosis refers to the phenomenon in which a hybrid plant exhibits superiority over its parents in terms of Plant Yield or any other characteristic.} in cross-breeding. Kahraman et al. \citep{cluster-analysis-1} in 2014 analyzed the field performances of 35 promising Common Bean genotypes. These genotypes were clustered into three groups using HC. Again, the goal of this work was to provide information for selecting the most diverse genotypes for breeding programs. Finally, we present a few works that belong to both the categories. Stansluos et al. \citep{corn} in 2019 analyzed $22$ phenotypic traits for $11$ Sweet Corn genotypes (cultivars). The authors showed a positive and significant correlation of Yield of Marketable Ear (YME) with Ear Diameter (ED) and Number of Marketable Ear (NME), whereas YME was negatively correlated with Thousand Kernel Weight (TKW). Also, they grouped these cultivars into four clusters using HC to obtain variation among them. Fried et al. \citep{root} in 2018 determined whether the root traits were related to other phenotypic traits for 49 Soybean genotypes. In this work, Principal Component Analysis (PCA) biplot was used to separate the Soybean genotypes into different clusters. According to the authors, this research was critical for Soybean improvement programs since it helped select genotypes with the improved root characteristics. We have three contributions as below, which have not been catered in any of the above cited papers. \begin{enumerate}[noitemsep] \item With a focus on the second category, we perform grouping of several thousand genotypes as compared to a few hundred in the papers cited above. \item Clustering becomes computationally expensive when the size of the data is very large. Hence, sampling is required to make the underlying algorithm scalable. As mentioned in the previous section, we adapt Pivotal Sampling, a probability-based technique, for phenotypic data. \item HC, which is the most common clustering algorithm (and some other sporadically used algorithms like $k$-means and UPGMA), do not provide the level of accuracy needed. Again, as earlier, we develop a variant of the SC algorithm, which is considered highly accurate, especially for phenotypic data. \end{enumerate} \section{Sampling and Clustering Algorithms} \label{sec:3} In this section, we briefly discuss the standard algorithms for Pivotal Sampling and SC in the two subsections below. \subsection{Pivotal Sampling} \label{sec:3.1} This is a well-developed sampling theory that handles complex data with unequal probabilities. The method is attractive because it can be easily implemented by a sequential procedure, i.e. by a single scan of the data \citep{pivotal2}. Thus, the complexity of this method is $\mathcal{O}(n)$, where $n$ is the population size. It is important to emphasize that the method is independent of the density of the data. Consider a finite population $U$ of size $n$ with its each unit identified by a label $i = 1, 2, ..., n$. A sample $S$ is a subset of $U$ with its size, either being random ($N(S)$) or fixed ($N$). Obtaining the inclusion probabilities of all the units in the population, denoted by $\pi_i$ with $i=1, 2, ..., n$, forms an important aspect of this unequal probability sampling technique. The pivotal method is based on a principle of contests between units \citep{sampling}. At each step of the method, two units compete to get selected (or rejected). Consider unit $i$ with probability $\pi_i$ and unit $j$ with probability $\pi_j$, then we have the two cases as below. \begin{enumerate} \item \textbf{Selection step ($\pi_i+\pi_j\geq1$):} Here, one of the units is selected, while the other one gets the residual probability $\pi_i+\pi_j-1$ and competes with another unit at the next step. More precisely, if $(\pi_i,\pi_j)$ denotes the selection probabilities of the two units, then \begin{equation*} (\pi_i,\pi_j)=\left\{\begin{matrix} (1,\pi_i+\pi_j-1) \textnormal{ with probability } \frac{1-\pi_j}{2-\pi_i-\pi_j}\\ (\pi_i+\pi_j-1,1) \textnormal{ with probability } \frac{1-\pi_i}{2-\pi_i-\pi_j} \end{matrix}\right. \end{equation*} \item \textbf{Rejection step ($\pi_i+\pi_j<1$):} Here, one of the units is definitely rejected (i.e. not selected in the sample), while the other one gets the sum of the inclusion probabilities of both the units and competes with another unit at the next step. More precisely, \begin{equation*} (\pi_i,\pi_j)=\left\{\begin{matrix} (0,\pi_i+\pi_j) & \textnormal{with probability } \frac{\pi_j}{\pi_i+\pi_j}\\ (\pi_i+\pi_j, 0) & \textnormal{with probability } \frac{\pi_i}{\pi_i+\pi_j} \end{matrix}\right. \end{equation*} \end{enumerate} This step is repeated for all the units present in the population until we get the sample of size $N(S)$ or $N$. The worst-case occurs when we obtain the last sample (i.e. $N^{th}$ sample) in the last iteration. \subsection{Spectral Clustering} \label{sec:3.2} Clustering is one of the most widely used techniques for exploratory data analysis with applications ranging from statistics, computer science, and biology to social sciences and psychology etc. It is used to get a first impression of data by trying to identify groups having ``similar behavior" among them. Compared to the traditional algorithms such as $k$-means, SC has many fundamental advantages. Results obtained by SC are often more accurate than the traditional approaches. It is simple to execute and can be efficiently implemented by using the standard linear algebra methods. The algorithm consists of four steps as below \citep{sc}. \begin{enumerate} \item The first step in the SC algorithm is the construction of a matrix called the similarity matrix. Building this matrix is the most important aspect of this algorithm; better its quality, better the clustering accuracy \citep{sc}. This matrix captures the local neighborhood relationships between the data points via similarity graphs and is usually built in three ways. The first such graph is a $\epsilon$-neighborhood graph, where all the vertices whose pairwise distances are smaller than $\epsilon$ are connected. The second is a $k$-nearest neighborhood graph, where the goal is to connect vertex $v_i$ with vertex $v_j$ if $v_j$ is among the $k$-nearest neighbors of $v_i$. The third and the final is the fully connected graph, where each vertex is connected with all the other vertices. Similarities are obtained only between the connected vertices. Thus, similarity matrices obtained by the first two graphs are usually sparse, while the fully connected graph yields a dense matrix. Let the $n$ vertices of a similarity graph be represented numerically by vectors $a_1, a_2, ..., a_n$, respectively. Here, each $a_i$ $\in \mathbb{R}^m$ is a column vector for $i=1, ..., n$. Also, let $a_i^l$ and $a_j^l$ denote the $l^{th}$ elements of vectors $a_i$ and $a_j$, respectively, with $l=1, ..., m$. There exist many distance measures to build the similarity matrix \citep{distance}. We describe some common ones below using the above introduced terminologies. \begin{enumerate}[noitemsep] \item \textbf{City block distance:} \citep{distance} It is the special case of the Minkowski distance \begin{equation*} d_{ij}=\sqrt[p]{\sum_{l=1}^{m}|a_i^l-a_j^l|^p} \end{equation*} with $p=1$. \item \textbf{Euclidean distance:} \citep{distance} It is the ordinary straight line distance between two points in the Euclidean space. It is again the special case of the Minkowski distance, where the value of $p$ is taken as $2$. Thus, it is given by \begin{equation*} d_{ij}=\sqrt{\sum_{l=1}^{m}(a_i^l-a_j^l)^2}. \end{equation*} \item \textbf{Squared Euclidean distance:} \citep{distance} It is the square of the Euclidean distance, and is given by \begin{equation*} d_{ij}=\sum_{l=1}^{m}(a_i^l-a_j^l)^2. \end{equation*} \item \textbf{Cosine distance:} \citep{distance} It measures the cosine of the angle between two non-zero vectors, and is given by \begin{equation*} d_{ij}=1-{a_i \cdot a_j \over \|a_i\| \|a_j\|}, \end{equation*} where, $\|\cdot \|$ denotes the Euclidean norm of a vector. \item \textbf{Correlation distance:} \citep{correlation} It captures the correlation between two non-zero vectors, and is given by \begin{equation*} d_{ij}=1-{(a_i-\bar{a}_i)^t(a_j-\bar{a}_j) \over \sqrt{(a_i-\bar{a}_i)^t(a_i-\bar{a}_i)}\sqrt{(a_j-\bar{a}_j)^t(a_j-\bar{a}_j)}}, \end{equation*} where, $\bar{a}_i$ and $\bar{a}_j$ are the means of $a_i$ and $a_j$ multiplied with a vector of ones, respectively, and $t$ signifies the transpose operation. \item \textbf{Hamming distance:} \citep{hamming} It measures the number of positions at which the corresponding values of two vectors are different, and is given by \begin{equation*} d_{ij}={\#(a_i^l \neq a_j^l) \over n}, \end{equation*} \item \textbf{Jaccard distance:} \cite{jaccard} It again measures the number of positions at which the corresponding values of two vectors are different excluding the positions where both the vectors have zero values, and is given by \begin{equation*} d_{ij}={\#[(a_i^l \neq a_j^l)\cap ((a_i^l\neq 0)\cup (a_j^l\neq 0))] \over \#[(a_i^l\neq 0)\cup (a_j^l\neq 0)]}. \end{equation*} \end{enumerate} \item Next, a matrix called the Laplacian matrix is constructed. This matrix is either non-normalized or normalized. The non-normalized Laplacian matrix is defined as \begin{equation*} L=D-W, \end{equation*} where $W$ is the similarity matrix and $D$ is a diagonal matrix whose elements are obtained by adding together the elements of all the columns for every row of $W$. Normalized Laplacian matrix is again of two types: the symmetric Laplacian ($L_{sym}$) and the random walk Laplacian ($L_{rw}$). Both these matrices are closely related to each other and are defined as \begin{equation*} L_{sym}=D^{-1/2}LD^{-1/2}=I-D^{-1/2}WD^{-1/2}. \end{equation*} \begin{equation*} L_{rw}=D^{-1}L=I-D^{-1}W. \end{equation*} Henceforth, the non-normalized Laplacian matrix is referred to as the Type-1 Laplacian, $L_{sym}$ as the Type-2 Laplacian, and $L_{rw}$ as the Type-3 Laplacian. In the literature, it is suggested to use the normalized Laplacian matrix instead of the non-normalized one, and specifically the Type-3 Laplacian \citep{sc}. \item Once we have the Laplacian matrix, we obtain the first $k$ eigenvectors $u_1, ..., u_k$ of this matrix, where $k$ is the number of clusters. \item Finally, these eigenvectors are clustered using the $k$-means clustering algorithm. \end{enumerate} \section{Implementing Pivotal Sampling and Modified Spectral Clustering for Phenotypic Data} \label{sec4} Here, we first present the application of Pivotal Sampling to obtain the samples from phenotypic data. Subsequently, we implement our modified SC algorithm on the same data. Consider that the phenotypic data of a plant consist of $n$ genotypes with each genotype evaluated for $m$ different characteristics/ traits. As discussed in Section \ref{sec:3.1}, Pivotal Sampling requires that the inclusion probabilities (i.e. $\pi_i$ for $i=1, ..., n$), of all the genotypes in the population $U$, be computed before a unit is considered for a contest. The set of characteristics associated with a genotype can be exploited in computing these probabilities. To select a sample of size $N$, where $N \ll n$, we obtain these probabilities as \citep{pivotal2} \begin{equation} \pi_i=N\frac{\varkappa_i}{\sum_{i\in U}\varkappa_i}, \label{eq:1} \end{equation} where $\varkappa_i$ can be a property associated with any one characteristic (or a combination of them) of the $i^{th}$ genotype. Obtaining $\pi_i$ in such a way also ensures that $\sum_{i=1}^{n}\pi_i=N$, i.e. we get exactly $N$ selection steps, and in-turn, exactly $N$ samples. In our implementation, we use the deviation property of the genotypes, which is discussed next. Since different characteristics have values in different ranges, we start by normalizing them as below \citep{normalize,normalize1}. \begin{equation*} (\mathcal{X}_j)_i={(x_j)_i-\textnormal{min}(x_j) \over \textnormal{max}(x_j)-\textnormal{min}(x_j)}. \end{equation*} Here, $(\mathcal{X}_j)_i$ and $(x_j)_i$ are the normalized value and the actual value of the $j^{th}$ characteristic for the $i^{th}$ genotype, respectively with $j=1, ..., m$ and $i=1, ..., n$. Furthermore, max($x_j$) and min($x_j$) are the maximum and the minimum values of the $j^{th}$ characteristic among all the genotypes. Now, the deviation for the $i^{th}$ genotype is calculated using the above normalized values as \begin{equation*} dev_i=\sum_{j=1}^{m}\textnormal{max}(\mathcal{X}_j)-(\mathcal{X}_j)_i. \end{equation*} Here, $\textnormal{max}(\mathcal{X}_j)$ denotes the maximum normalized value of the $j^{th}$ characteristic among all the genotypes. Practically, a relatively large value of $dev_i$ indicates that the $i^{th}$ genotype is less important, and hence, its probability should be small. Thus, the inclusion probability of a genotype is calculated by taking $\varkappa_i = \frac{1}{dev_i}$ in Eq. (\ref{eq:1}) or \begin{equation*} \pi_i=N\frac{\frac{1}{dev_i}}{\sum_{i\in U}\frac{1}{dev_i}}. \end{equation*} Once these probabilities are obtained, we follow the two steps (selection and rejection) as discussed in Section \ref{sec:3.1}. Next, we discuss the clustering of these $N$ genotypes into $k$ clusters. Similar to the standard SC algorithm discussed in Section \ref{sec:3.2}, the first step in our modified SC is to obtain the similarity matrix. As mentioned earlier, this is the most important aspect of this algorithm since better the quality of this matrix, better is the clustering accuracy. For this, we consider these $N$ genotypes as the vertices of a graph. Let vector $a_i$ contain the normalized values of all the characteristics ($m$) for the $i^{th}$ genotype. Thus, we have $N$ such vectors corresponding to the $N$ genotypes selected using Pivotal Sampling, and each vector is of size $m$. In our implementation, we use a fully connected graph to build the similarity matrix, i.e. we obtain similarities among all the $N$ genotypes. We define the similarity between the vectors $a_i$ and $a_j$ (representing the genotypes $i$ and $j$, respectively) as the inverse of the distance between these vectors obtained by using the distance measures mentioned in Section \ref{sec:3.2}. This is intuitive because smaller the distance between any two genotypes, larger the similarity between them and vice versa. We denote this distance by $d_{ij}$. We build this matrix of size $N \times N$ by obtaining the similarities among all the $N$ genotypes. The next step is to compute the Laplacian matrix, which when obtained from the above-discussed similarity matrix, generates poor eigenvalues,\footnote{Zero/ close to zero and distinct eigenvalues are considered to be a good indicator of the connected components in a similarity matrix. Thus, eigenvalues are considered poor when they are not zero/ not close to zero or indistinct \citep{sc}.} and in-turn poor corresponding eigenvectors that are required for clustering\footnote{For some distance matrices (like Euclidean distance), the eigenvalues don't even converge.}. Thus, instead of taking only the inverse of $d_{ij}$, we also take its exponent, i.e. we define the similarity between the $i^{th}$ and the $j^{th}$ genotypes as $e^{-d_{ij}}$ \citep{NgSC,spsc}. This, besides fixing the poor eigenvalues/ eigenvectors problem, also helps perform better clustering of the given data. Further, we follow the remaining steps as discussed in Section \ref{sec:3.2}. Above, we discussed the clustering of $N$ sampled genotypes into $k$ clusters. However, our goal is to cluster all $n$ genotypes and not just $N$. Hence, there is a need to reverse-map the remaining $n-N$ genotypes to these $k$ clusters. For this, we define the notion of average similarity, which between the non-clustered genotype $p_i$ and the cluster $C_l$ is given as \begin{equation*} \mathcal{AS}(C_l, p_i)=\frac{1}{\#(C_l)}\sum_{q\in C_l} e^{-d_{p_iq}}. \end{equation*} Here, $\#(C_l)$ denotes the number of genotypes present in $C_l$ and $q$ is a genotype originally clustered in $C_l$ by our modified SC algorithm with Pivotal Sampling. We obtain the average similarity of $p_i$ with all the $k$ clusters (i.e. with $C_l$ for $l=1, ..., k$), and associate it with the cluster with which $p_i$ has the maximum similarity. Next, we perform the complexity analysis of our algorithm. Since Pivotal Sampling and SC form the bases of our algorithm, we discuss the complexities of these algorithms before ours. \begin{enumerate}[noitemsep] \item Pivotal Sampling ($n$: number of genotypes, $N$: sample size) \begin{enumerate}[noitemsep] \item Obtaining Probabilities: $\mathcal{O}(n)$ \item Obtaining Samples: $\mathcal{O}(n)$ \end{enumerate} \item SC ($n$, $m$: number of characteristics) \begin{enumerate}[noitemsep] \item Constructing Similarity Matrix: $\mathcal{O}(n^2m)$ \item Obtaining Laplacian Matrix: $\mathcal{O}(n^3)$ \end{enumerate} \item Our Algorithm ($n$, $N$, $m$) \begin{enumerate}[noitemsep] \item Obtaining Samples: $\mathcal{O}(n)$ \item Constructing Similarity Matrix: $\mathcal{O}(N^2m)$ \item Obtaining Laplacian Matrix: $\mathcal{O}(N^3)$ \item Reverse Mapping: $\mathcal{O}\big((n-N)N\big)$ \end{enumerate} Thus, the overall complexity of our algorithm is $\mathcal{O}(nN+N^3+Nm^2)$. Here, we have kept three terms because any of these can dominate (here, $n \gg N, m$). \end{enumerate} When we compare complexity of our algorithm with that of HC, which is $\mathcal{O}(n^3)$, it is evident that we are more than a magnitude faster than HC. \section{Results} \label{sec:5} In this section, we first briefly discuss the data used for our experiments. Next, we check the goodness of our sampling technique by estimating a measure called the population total. Subsequently, we describe the clustering set-up, where the validation metric, the ideal number of clusters, the suitable distance measures for building similarity matrices, and the most useful Laplacian matrix are discussed. Finally, we present the results for our modified SC with Pivotal Sampling. Here, we compare our algorithm with (a) SC with VQ, HC with Pivotal Sampling, HC with VQ and (b) non-sampled HC. \subsection{Data Description} \label{sec:5.1} As mentioned in Introduction, our techniques can be applied to any plant data. However, here we experiment on phenotypic data of Soybean genotypes. This data is taken from Indian Institute of Soybean Research, Indore, India, and consists of $29$ different characteristics/ traits for $2376$ Soybean genotypes \citep{phenotypic-data}. Among these, we consider the following eight characteristics that are most important for higher yield: Early Plant Vigor (EPV), Plant Height (PH), Number of Primary Branches (NPB), Lodging Score (LS), Number of Pods Per Plant (NPPP), 100 Seed Weight (SW), Seed Yield Per Plant (SYPP) and Days to Pod Initiation (DPI). Table \ref{data} provides a snapshot of this data for a few genotypes. \begin{table}[ht] \centering \begin{tabular}{|c|c|c|c|c|c|c|c|c|} \hline \textbf{Genotypes} & \textbf{EPV} & \textbf{PH} & \textbf{NPB} & \textbf{LS} & \textbf{NPPP} & \textbf{SW} & \textbf{SYPP} & \textbf{DPI} \\ \hline 1&Poor &54 &6.8 &Moderate &59.8 &6.5 &2.5 &65 \\ 2&Poor &67 &3.4 &Severe &33 &6.2 &3.9 &64 \\ 3&Poor &38.4 &2.8 &Slight &68 &6.9 &4.4 &61 \\ 4&Good &60.8 &4 &Moderate &34.6 &6.1 &3 &65 \\ \vdots&\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots &\vdots \\ 2376&Very Good&89.6 &5 &Severe &32.6 &7.3 &3.4 &62 \\ \hline \end{tabular} \caption{\label{data}Description of Phenotypic Data.} \end{table} \subsection{Sampling Discussion} \label{sec:5.2} To inspect the quality of our sampling techniques, we estimate a measure called the population total, which is the addition of values of a particular characteristic for all the $n$ units (genotypes here) present in the population $U$. For example, if ``Plant Height (PH)" is the characteristic of interest, then the population total is the addition of PH values for all the $n$ genotypes. Mathematically, the exact (or actual) population total for a characteristic of interest $x_j$ is given as \begin{equation*} Y=\sum_{i\in U}(x_j)_i, \end{equation*} where, as earlier, $(x_j)_i$ is the value of the $j^{th}$ characteristic for the $i^{th}$ genotype and $U$ is the set of all genotypes. As evident by the above equation, this measure can be only applied to characteristics that contain numerical values.\footnote{Methods do exist to convert non-numeric data to numeric one for using this measure.} In this work, we use two different estimators to compute an approximation of the population total from the sampled data. Closer the value of an estimator to the actual value, better the sampling. First is the Horvitz-Thompson (HT)-estimator (also called $\pi$-estimator), which is defined as \citep{HT} \begin{equation*} Y_{HT}^{'} = Y_{\pi}^{'}=\sum_{i\in S}\frac{(x_j)_i}{\pi_i}, \end{equation*} where, $\pi_i$ is the inclusion probability of the $i^{th}$ genotype as evaluated in Section \ref{sec4} and $S$ is the set of sampled genotypes. Another estimator that we use is the H\'ajek-estimator. It is usually considered better than the HT-estimator and is given as \citep{hajek} \begin{equation*} Y_{H\acute{a}jek}^{'} =n\frac{\sum_{i\in S}\frac{(x_j)_i}{\pi_i}}{\sum_{i\in S}\frac{1}{\pi_i}}, \end{equation*} here, as earlier, $n$ is the total number of genotypes. The actual population total and the values of the above two estimators for six characteristics (that have numerical values) when using Pivotal Sampling and $500$ samples are given in Table \ref{estimator} (see columns 3, 4, and 6, respectively). From this table, it is evident that the approximate values of the population total are very close to the corresponding actual values. Thus, Pivotal Sampling works well in an absolute sense. Here, we also compute the values of the two estimators when using VQ (see columns 5 and 7). We can notice from these results that VQ also works reasonably well, but Pivotal Sampling is better. \begin{table}[ht] \centering \begin{tabular}{|c|c|c|c|c|c|c|} \hline \textbf{Sr.} & \textbf{Characteristics} & \textbf{Actual} & \textbf{Pivotal} & \textbf{VQ} & \textbf{Pivotal} & \textbf{VQ} \\ \textbf{No.} & & \textbf{Population} & \textbf{Sampling} & \textbf{(HT)} & \textbf{Sampling} &\textbf{(H\'ajek)} \\ & & \textbf{Total} & \textbf{(HT)} & & \textbf{(H\'ajek)} & \\ \hline 1& PH &121773.05 &122507.84 &123407.80 &123716.09 &113168.90 \\ 2 &NPB &8576.56 &8585.28 &9669.29 &8669.95 &8867.05 \\ 3 & NPPP &99712.72 &100193.53 &114465.66 &101181.70 &104968.67 \\ 4& SW &20073.32 &19907.10 &20966.86 &20103.44 &19227.28 \\ 5 &SYPP &10048.04 &10137.57 &10536.08 &10237.55 &9661.92 \\ 6& DPI &136810 &135309.78 &149242.17 &136644.29 &136859.84 \\ \hline \end{tabular} \caption{\label{estimator}HT and H\'ajek estimators values for Pivotal Sampling and VQ as compared to the actual population total with $N=500$ as the sample size.} \end{table} \subsection{Clustering Setup} \label{sec:5.3} Here, {\it first}, we describe the criteria used to check the goodness of generated clusters. There are various metrics available for the validation of clustering algorithms. These include Cluster Accuracy (CA), Normalized Mutual Information (NMI), Adjusted Rand Index (ARI), Compactness (CP), Separation (SP), Davis-Bouldin Index (DB), and Silhouette Value \citep{validation,silhouette}. For using the first three metrics, we should have a prior knowledge of the cluster labels. However, here we do not have this information. Hence, we cannot use these validation metrics. Rest of the techniques do not have this requirement, and hence, can be used for validation here. We use Silhouette Value because of its popularity \citep{silhouette}. Silhouette Value is a measure of how similar an object is to its own cluster (intra-cluster similarity) compared with other clusters (inter-cluster similarity). For any cluster $C_l$ ($l = 1, ..., k; \textnormal{ say } l = 1$), let $a(i)$ be the average distance between the $i^{th}$ data point and all other points in the cluster $C_1$, and let $b(i)$ be the average distance between this $i^{th}$ data point in the cluster $C_1$ and all other points in clusters $C_2, ..., C_k$. Silhouette Value for the $i^{th}$ data point is defined as \citep{silhouette} \begin{equation} s(i) = {b(i)-a(i) \over \text{max}\{a(i), b(i)\}}, \label{eq:2} \end{equation} where, $a(i)$ and $b(i)$ signify the intra-cluster and the inter-cluster similarities, respectively. Silhouette Value comes to be between $-1$ and $1$,\footnote{This is because the denominator of Eq. (\ref{eq:2}) is always greater than its numerator.} and average over all the data points is computed. A positive value (tending towards 1) indicates good clustering (compact and well-separated clusters), while a negative value (tending towards -1) indicates poor clustering. {\it Second}, we determine the ideal number of clusters by using the eigenvalue gap heuristic \citep{sc,eigenheuristic}. If $\lambda_1, \lambda_2, ..., \lambda_n$ are the eigenvalues of the matrix used for clustering (e.g., the Laplacian matrix), then often the initial set of eigenvalues, say $k$, have a considerable difference between the consecutive ones in this set. That is, $|\lambda_i - \lambda_{i+1}| \not \approx 0$ for $i=1, ..., k-1$. After the $k^{th}$ eigenvalue, this difference is usually approximately zero. According to this heuristic, this $k$ gives a good estimate of the ideal number of clusters. For this experiment, without loss of generality, we build the similarity matrix using the Euclidean distance measure on the above discussed phenotypic data. As mentioned earlier, it is recommended to use the Type-3 Laplacian matrix \citep{sc}. Hence, we use its eigenvalues for estimating $k$. Figure \ref{Fig1} represents the graph of the first fifty smallest eigenvalues (in absolute terms) of this Laplacian matrix. On the $x$-axis, we have the eigenvalue number, and on the $y$-axis its corresponding value. \begin{figure}[ht] \centering \includegraphics[width=\linewidth,height=6cm]{euclidean.eps} \caption{Fifty Smallest Eigenvalues of the Type-3 Laplacian Matrix Obtained from the Euclidean Similarity Matrix (for estimating the ideal number of clusters).} \label{Fig1} \end{figure} From this figure, we can see that there is a considerable difference between the first ten consecutive eigenvalues. After the tenth eigenvalue, this difference is very small (tending to zero). Hence, based upon the earlier argument and this plot, we take $k$ as ten. To corroborate this choice more, we experiment with $k$ as twenty and thirty as well. As expected, and discussed in detail later in this section, Silhouette Values for these numbers of clusters are substantially lesser than those for ten clusters. {\it Third}, and final, we perform experiments to identify the suitable similarity measures to build the similarity matrix, and also verify that, as recommended, the Type-3 Laplacian matrix is the best. Table \ref{suitable_similarity} below gives Silhouette Values of our modified SC for all seven similarity measures and three Laplacians when clustering the earlier presented phenotypic data into $10$, $20$, and $30$ clusters. \begin{table}[ht] \centering \begin{tabular}{|c|c|c|c|c|c|} \hline \textbf{Sr.} & \textbf{Similarity} & \textbf{Number of} & \textbf{Type-1} & \textbf{Type-2} & \textbf{Type-3} \\ \textbf{No.} & \textbf{Measure} & \textbf{Clusters $(k)$} & \textbf{Laplacian} & \textbf{Laplacian} & \textbf{Laplacian} \\ \hline 1. &Euclidean &10 &0.0828 &-0.0273& \textbf{0.2422} \\ & &20 &0.0455 &-0.1096& \textbf{0.2069} \\ & &30 &0.0887 &-0.1536& \textbf{0.1783} \\ \hline 2. &Squared &10 &0.0815 &-0.0555& \textbf{0.3836} \\ &Euclidean &20 &-0.0315&-0.1809& \textbf{0.2612} \\ & &30 &0.0354 &-0.2367& \textbf{0.1538} \\ \hline 3. &City-block &10 &0.0687 &0.2375 &\textbf{0.2647} \\ & &20 &-0.0356& 0.1347& \textbf{0.2082} \\ & &30 &-0.0870& 0.0866& \textbf{0.1887} \\ \hline 4. &Cosine &10 &0.1737 &-0.1408& 0.0694 \\ & &20 &0.0359 &-0.1973& 0.0277 \\ & &30 &0.0245 &-0.2456& -0.0316 \\ \hline 5. &Correlation &10 &0.1926&-0.1259 &\textbf{0.3426} \\ & &20 &0.0970 &-0.2198& \textbf{0.2313} \\ & &30 &0.2383 &-0.2604& \textbf{0.1556} \\ \hline 6. &Hamming &10 &0.0643 &0.0706&0.0775 \\ & &20 &0.0683 &0.0311 &0.0382 \\ & &30 &0.0715 &0.0283 &0.0229 \\ \hline 7. &Jaccard &10 &0.0716 &0.0303 &0.0458 \\ & &20 &0.0446 &0.0276 &0.0236 \\ & &30 &0.0279 &0.0298 &0.0318 \\ \hline \end{tabular} \caption{\label{suitable_similarity}Silhouette Values for modified SC with seven similarity measures and three Laplacian matrices for $k=10, 20$, and $30$. Silhouette Values in bold represent good clustering.} \end{table} From this table, it is evident that Silhouette Values for the Euclidean, Squared Euclidean, City-block and Correlation similarity measures and the Type-3 Laplacian matrix are the best. Hence, we use these four similarity measures and this Laplacian matrix. Also, as mentioned earlier, Silhouette Values decrease for twenty and thirty cluster sizes. \subsection{Results} \label{sec:5.4} Using the earlier presented dataset, and sampling-clustering setups, we compare our proposed algorithm (modified SC with Pivotal Sampling) with the existing variants in three ways. Initially, we compare with modified SC with VQ, HC\footnote{HC also requires building a similarity matrix.} with Pivotal Sampling and HC with VQ for a sample size of $500$. Since the results for modified SC with VQ come out to be closest to our algorithm, next, for broader appeal we compare these two algorithms for a sample size of $300$. Finally, we compare our algorithm with the current best in literature for this kind of data (i.e. HC without sampling) for both the sample sizes of $500$ and $300$. The results for the {\it initial} set of comparisons are given in Table \ref{sampling500}. Columns 2 and 3 give the similarity measures and the number of clusters chosen, respectively. Columns 4 and 5 give Silhouette Values of modified SC with Pivotal Sampling and VQ, respectively, while columns 6 and 7 give Silhouette Values of HC with Pivotal Sampling and VQ, respectively. \begin{table}[ht] \centering \begin{tabular}{|c|c|c|c|c|c|c|} \hline \textbf{Sr.}& \textbf{Similarity} &\textbf{\# of} & \multicolumn{2}{|c|}{\textbf{modified SC}} & \multicolumn{2}{|c|}{\textbf{HC}} \\ \cline{4-7} \textbf{No.} & \textbf{Measure} & \textbf{Clusters} & \textbf{Pivotal} & \textbf{VQ} & \textbf{Pivotal} & \textbf{VQ} \\ & & $(k)$ & \textbf{Sampling} & & \textbf{Sampling} & \\ \hline 1. &Euclidean &10 &{\bf 0.2152} &0.2061 &0.2105 &-0.1040\\ & &20 &{\bf 0.1905} &0.1448 &$0.2263^*$ &-0.1620\\ & &30 &{\bf 0.1741} &0.1021 &$0.1933^*$ &-0.2874\\ \hline 2. &Squared &10 &{\bf 0.3362} &0.2969 &0.2634 &-0.2096\\ &Euclidean &20 &{\bf 0.2469} &0.1522 &$0.3726^*$ &-0.5899\\ & &30 &{\bf 0.1658} &0.0440 &$0.2933^*$ &-0.6083\\ \hline 3. &City-block &10 &{\bf 0.2369} &0.2354 &0.1703 &-0.2278\\ & &20 &{\bf 0.2019} &0.1870 &0.1879 &-0.2398\\ & &30 &{\bf 0.1752} &0.1524 &$0.1988^*$ &-0.2868\\ \hline 4. &Correlation&10 &{\bf 0.3367} &0.2560 &0.2582 &-0.0060\\ & &20 &{\bf 0.2291} &0.0899 &0.0867 &-0.4120\\ & &30 &{\bf 0.1742} &-0.0349 &0.0998 &-0.7018\\ \hline \end{tabular} \caption{\label{sampling500}Silhouette Values for modified SC and HC with Pivotal Sampling and VQ for $N=500$. Silhouette Values in bold represent good clustering.} \end{table} When we compare our algorithm (values in the fourth column, and highlighted in bold) with other variants, it is evident that we are clearly better than modified SC with VQ and HC with VQ (values in the fifth and the seventh columns); our values are higher than those from these two algorithms. When we compare our algorithm with HC with Pivotal Sampling (values in the sixth column), we again perform better for many cases. However, for some cases, our algorithm performs worse than HC with Pivotal Sampling (highlighted with a *). Upon further analysis (discussed below), we realize that an inappropriate grouping of genotypes by HC with Pivotal Sampling results in these set of Silhouette Values getting wrongly inflated. To further assess the quality of our algorithm, we present the distribution of genotypes into different clusters (after reverse-mapping) for modified SC with Pivotal Sampling and HC with Pivotal Sampling. Without loss of generality, this comparison is done using the Squared Euclidean similarity measure and cluster size thirty. The results for our algorithm are given in Figure \ref{Fig2} and for HC with Pivotal Sampling are given in Figure \ref{Fig3}. On the $x$-axis, we have the cluster number and on the $y$-axis, the number of genotypes present in them. \begin{figure}[ht] \centering \includegraphics[width=\linewidth,height=6cm]{SqEu-SC-30.eps} \caption{Distribution of Genotypes (modified SC with Pivotal Sampling) for Squared Euclidean similarity measure and cluster size thirty.} \label{Fig2} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=\linewidth,height=6cm]{SqEu-HC-30.eps} \caption{Distribution of Genotypes (HC with Pivotal Sampling) for Squared Euclidean similarity measure and cluster size thirty.} \label{Fig3} \end{figure} From Figure \ref{Fig2}, we can see that our algorithm equally distributes all genotypes between the different clusters. This matches the real-life segregation as well since all genotypes belong to the same plant (Soybean in this case). This clustering has also been validated by the plant biologists at Indian Institute of Soybean Research, Indore, India. The equivalent clustering results obtained by using HC with Pivotal Sampling (as given in Figure \ref{Fig3}), however, depicts a very skewed distribution. Most genotypes are segregated in only a few clusters, while the remaining clusters contain only one or two genotypes. This is also the reason for the inflation of Silhouette Values of HC with Pivotal Sampling in Table \ref{sampling500} since the intra-cluster similarity for solitary genotype is zero leading to its respective Silhouette Value to become one (the maximum possible; see Eq. (\ref{eq:2})). Thus, our algorithm also outperforms HC with Pivotal Sampling, which from Table \ref{sampling500} was not very evident. {\it Next}, as mentioned earlier, to further demonstrate the applicability of our work, we also present the results with a sample size $300$. Since modified SC with VQ turns out to be our closest competitor, we compare our algorithm with this one only. This comparison is given in Table \ref{sampling300}, with its columns mapping the respective columns of Table \ref{sampling500}. As evident from Table \ref{sampling300}, our modified SC with Pivotal Sampling substantially outperforms modified SC with VQ (see values in columns 4 and 5). \begin{table}[ht] \centering \begin{tabular}{|c|c|c|c|c|} \hline \textbf{Sr.}& \textbf{Similarity} &\textbf{\# of} & \multicolumn{2}{|c|}{\textbf{modified SC}} \\ \cline{4-5} \textbf{No.} & \textbf{Measure} & \textbf{Clusters} & \textbf{Pivotal} & \textbf{VQ} \\ & & $(k)$ & \textbf{Sampling} & \\ \hline 1. &Euclidean &10 &{\bf }0.2104 &0.1833 \\ & &20 &{\bf }0.1968 &0.0955 \\ & &30 &{\bf }0.1743 &0.0722 \\ \hline 2. &Squared &10 &{\bf }0.3280 &0.2589 \\ &Euclidean &20 &{\bf }0.2424 &0.1322 \\ & &30 &{\bf }0.1613 &0.0044 \\ \hline 3. &City-block &10 &{\bf }0.2392 &0.2157 \\ & &20 &{\bf }0.1990 &0.1696 \\ & &30 &{\bf }0.1752 &0.1373 \\ \hline 4. &Correlation&10 &{\bf }0.3368 &0.2229 \\ & &20 &{\bf }0.2312 &0.0336 \\ & &30 &{\bf }0.1725 &-0.0788 \\ \hline \end{tabular} \caption{\label{sampling300}Silhouette Values for modified SC with Pivotal Sampling and VQ for $N=300$.} \end{table} As earlier, {\it finally}, we compare the results of our algorithm (modified SC with Pivotal Sampling) with the currently popular clustering algorithm in the plant studies domain (i.e. HC without sampling). For this set of experiments, without loss of generality, we use the cluster size of ten. The results of this comparison are given in Table \ref{percentage}, where the first four columns are self-explanatory (based upon the data given in Tables \ref{sampling500} and \ref{sampling300} earlier). In the last column of this table, we also evaluate the percentage improvement in our algorithm over HC. As evident from this table, our algorithm is up to 45\% more accurate than HC for both the sample sizes. As earlier, our algorithm also has the crucial added benefit of reduced computational complexity as compared to HC. \begin{table}[ht] \centering \begin{tabular}{|c|c|c|c|c|} \hline \textbf{Sample} & \textbf{Similarity} & \textbf{modified SC with} & \textbf{HC} & \textbf{Percentage} \\ \textbf{Size} & \textbf{Measure} & \textbf{Pivotal Sampling} & & \textbf{Improvement} \\ \hline & Euclidean & 0.2152 & 0.2173 & -0.97\% \\ $N=500$ &Squared Euclidean & 0.3362 &0.3257 & 3.22\% \\ &City-block & 0.2369 & 0.2135 & 10.96\% \\ &Correlation & 0.3367 & 0.2307 & 45.95\% \\ \hline & Euclidean & 0.2104 & 0.2173 & -3.28\% \\ $N=300$ &Squared Euclidean & 0.3280 &0.3257 & 0.71\% \\ &City-block & 0.2392 & 0.2135 & 12.04\% \\ &Correlation & 0.3368 & 0.2307 & 45.99\% \\ \hline \end{tabular} \caption{\label{percentage}Silhouette Values of modified SC with Pivotal Sampling and HC for cluster size ten.} \end{table} \section{Conclusions and Future Work} \label{sec:6} We present the modified Spectral Clustering (SC) with Pivotal Sampling algorithm for clustering plant genotypes using their phenotypic data. We use SC for its accurate clustering and Pivotal Sampling for its effective sample selection that in-turn makes our algorithm scalable for large data. Since building the similarity matrix is crucial for the SC algorithm, we exhaustively adapt seven similarity measures to build such a matrix. We also present a novel way of assigning probabilities to different genotypes for Pivotal Sampling. We perform two sets of experiments on about 2400 Soybean genotypes that demonstrate the superiority of our algorithm. \textit{First}, when compared with the competitive clustering algorithms with samplings (SC with Vector Quantization (VQ), Hierarchical Clustering (HC) with Pivotal Sampling, and HC with VQ), Silhouette Values obtained when using our algorithm are higher. \textit{Second}, our algorithm doubly outperforms the standard HC algorithm in terms of clustering accuracy and computational complexity. We are up to 45\% more accurate and an order of magnitude faster than HC. Since the choice of the similarity matrix has a significant impact on the quality of clusters, in the future, we intend to adapt other ways of constructing this matrix such as Pearson $\chi^2$, Squared $\chi^2$, Bhattacharyya, Kullback-Liebler etc. \citep{distance}. Furthermore, in-place of Pivotal Sampling, we also plan to adapt other probabilistic sampling techniques like Cube Sampling, which possess complementary data analysis properties \citep{sampling}. As mentioned earlier, our algorithm is developed to work well for phenotypic data of all plants. Hence, in the future, we aim to test our algorithm on other plant genotypes as well (e.g., Wheat, Rice, etc.) \citep{wheat,rice-future}. \section*{Acknowledgments} The authors would like to thank Mr. Mohit Mohata, Mr. Ankit Gaur and Mr. Suryaveer Singh (IIT Indore, India) for their help in preliminary experiments, which they did as part of their undergraduate degree project. We would also like to sincerely thank Dr. Vangala Rajesh and Dr. Sanjay Gupta (Indian Institute of Soybean Research, Indore, India) for their help in generating the experimental data.
{'timestamp': '2020-09-22T02:01:41', 'yymm': '2009', 'arxiv_id': '2009.09028', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09028'}
arxiv
\section{Introduction} \label{sec:intro} Epidemics greatly affect Homo sapiens \cite{McN,O,Benedict}, as well as all other animals. Epidemic modeling goes back at least to Bernoulli who modeled the spread of smallpox \cite{Ber,Ber-history}. The methods and concepts developed in this field have been applied to modeling recent human epidemics like HIV, H1N1 Swine Flu, Zika Virus, and COVID-19, and also to modeling non-biological processes like the spread of rumors or cultural fads, diffusion of innovations, computer viruses, etc. (see \cite{MT,Lud,CFL,Volovik} and references therein). One general lesson that we learn about epidemics is that they often operate close to a critical regime. Subcritical epidemics are actually the most numerous, but they quickly die out. Supercritical epidemics can kill a finite fraction of the population thereby destroying the environment that the virus needs to thrive and multiply. Epidemics close to the critical regime are kind of optimal in a view of never-ending competition between the hosts and the viruses. Furthermore, humans are now sufficiently advanced to devise and employ the containment measures to suppress supercritical epidemics to critical. Mathematical models of epidemics are over-simplified. In physics, for instance, we know that electrons are identical. In contrast, organisms are different, even twins are different. This heterogeneity is rarely taken into account, and it is far from clear how to model it in a reasonable way. In physics, we usually rely on binary and symmetric interactions. Both these features are questionable in the realm of epidemics. Other realistic features are also mostly ignored. However, the populations where the epidemics spread are usually very large and the lore from statistical physics tells us that in large systems qualitative behaviors can be predicted even if one greatly simplifies the model. This is especially true in critical regimes. The very concept of critical regimes comes from epidemic modeling. This concept clearly emerges from the well-known susceptible-infected-recovered (SIR) process \cite{McK,KMcK,May,Siam,Murray}, a toy model that mimics the spread of infection. According to the rules of the SIR process, infected individuals recover (become immune or die) with equal rates and every infected individual transmits a disease to every susceptible individual with the rate $R_0/N$, where $N$ is the population size. Thus each infected individual on average spreads the infection to $R_0$ individuals before recovery. Therefore the behavior of the SIR process greatly depends on whether the reproduction number $R_0$ is smaller or larger than the recovery rate which we set to unity. When $R_0<1$, i.e., for subcritical SIR processes, outbreaks quickly end, namely just a few individuals catch the disease. For supercritical SIR processes ($R_0>1$), the outbreak may affect only a few individuals, e.g. starting from a single infected individual the size of the outbreak is finite with probability $R_0^{-1}$. With complimentary probability, $rN+O(\sqrt{N})$ individuals catch the disease before the outbreaks dies out; the fraction $r=r(R_0)$ is implicitly determined by \begin{equation} \label{rR} r+e^{-R_0 r} = 1 \end{equation} Huge outbreaks killing finite fractions of the population continue to devastate animal species. They also used to decimate human societies \cite{McN,O,Benedict}, e.g., the Black Death killed about 50\% of the European population \cite{Benedict}. Preventive and containment measures such as quarantine, improved hygiene, etc. suppress supercritical infectious diseases and often drive them to a critical situation. This critical state is effectively self-organized. Indeed, suppressing the disease to the subcritical regime may be possible but costly and psychologically difficult to maintain when the number of newly infected starts to decrease exponentially. Therefore, if the outbreak is not quickly and completely eradicated, the containment measures are relaxed and the system may return to the supercritical stage, the disease gets again out of control, so the containment measures are tightened driving the system back to the subcritical state. It would be interesting to devise a self-organized process of the spread of infection with dynamics similar to the critical SIR process. In this paper, however, we merely consider the critical SIR process with many initially infected individuals. The SIR processes are often treated using a deterministic framework \cite{McK,KMcK,May,Siam,Murray}. This framework can be applied to the supercritical regime where it gives e.g. the simplest derivation of Eq.~\eqref{rR}. Stochastic effects are unavoidable, however, for the critical and subcritical SIR processes (see \cite{Bailey50,Bailey,AB,book}). When the population of susceptible is finite, finite-size corrections become important, particularly for the critical SIR process \cite{rr,ML,bk,KS,Gordillo,Hofstad,bk12}. In this paper, we study the critical SIR process and hence we employ stochastic methods. We consider finite populations. The population size is assumed to be large, $N\gg 1$. We focus on the situation when the initial number of infected individuals is also large: $k\gg 1$. Most epidemics start with a single infected individual. We want to describe the SIR process that has begun at the supercritical regime and exhibited an exponential growth regime. Preventive and containment measures subsequently suppressed the reproduction number to unity. Ignoring the earlier regime yields the critical SIR process with a certain large number $k$ of initially infected individuals. The same critical SIR process with a large number of initially infected individuals has been recently studied, using large-scale simulations and scaling arguments, by Radicchi and Bianconi \cite{Ginestra}. Our analysis relies on exact calculations and asymptotic methods. Our analytical and asymptotic predictions qualitatively agree with simulation results \cite{Ginestra}, explain the major features, and perhaps suggest slightly different scaling fits which are a little simpler than the fits used in Ref.~\cite{Ginestra}. The chief reason for subtle behaviors are algebraic tails, the average size and duration of outbreaks are especially sensitive to these tails. Considerable insight into the behavior of finite systems can be gained from the analysis of the infinite-population limit where the critical SIR process is equivalent to the critical branching process with continuous time. This is a classical subject, but we are studying an unusual setting with an arbitrary number $k$ of initially infected individuals. We derive several exact results in this infinite-population limit. Our analysis of finite systems employs asymptotic and scaling methods. The outline of this paper is as follows. In Sec.~\ref{sec:CBP}, we consider the infinite-population limit, present exact results for the outbreak size distribution and show that exact results approach a simple scaling form in the most interesting situation when $k\gg 1$. We then analyze the critical SIR process in a population with $N\gg 1$ individuals. The size of an outbreak is a random quantity, its average and variance are studied using scaling and heuristic arguments (Sec.~\ref{sec:SIR}) and asymptotically exact analysis (Sec.~\ref{sec:EA}). In Sec.~\ref{sec:SIR-time}, we investigate the duration of outbreaks. Several technical calculations are relegated to the Appendices~\ref{ap:det}--\ref{ap:time}. \section{infinite-population limit: Outbreak Size Distribution} \label{sec:CBP} In the infinite-population limit, the SIR process reduces to the branching process \cite{feller,teh,athreya04,branch,vatutin}. Branching processes involve duplication and death. Symbolically, \begin{displaymath} \xymatrix{P+P & \\ P \ar[u] \ar[r] & \emptyset} \end{displaymath} For the critical branching process, the rates of duplication and death are equal. Branching processes have numerous applications, e.g., they mimic cell division and death; for adult organisms, the critical branching process is appropriate as the number of cells remains (approximately) constant. We begin with a classical setting when one individual was initially infected. Let $A_n$ be the probability that exactly $n$ individuals catch the infection before the epidemic is over. With probability $\tfrac{1}{2}$, the initially infected individual joins the population of recovered before infecting anyone else, so $A_1=\tfrac{1}{2}$. Further, $A_2=\tfrac{1}{2}A_1^2$ since at the first step a new individual must get infected, and then both must recover without spreading infection. Proceeding along these lines we arrive at the recurrence \begin{equation} \label{An_rec} A_n = \frac{1}{2}\sum_{i+j=n}A_iA_j+\frac{1}{2}\,\delta_{n,1} \end{equation} reflecting that the first infection event creates two independent infection processes \cite{teh}. A solution to \eqref{An_rec} is found by introducing the generating function \begin{equation} \label{An_gen} \mathcal{A}(z) = \sum_{n\geq 1}A_n z^n \end{equation} converting the recurrence \eqref{An_rec} into a quadratic equation \begin{equation} \label{2A:eq} 2\mathcal{A} = \mathcal{A}^2 + z \end{equation} whose solution reads \begin{equation} \label{Az} \mathcal{A}(z) = 1 - \sqrt{1-z} \end{equation} Expanding $\mathcal{A}(z)$ in powers of $z$ we find \begin{equation} \label{An_sol} A_n = \frac{1}{\sqrt{4\pi}}\, \frac{\Gamma\left(n-\tfrac{1}{2}\right)}{\Gamma(n+1)} \simeq \frac{1}{\sqrt{4\pi}}\,n^{-3/2} \end{equation} In particular, the probabilities $A_n$ are given by \begin{equation*} \tfrac{1}{2},\tfrac{1}{8},\tfrac{1}{16},\tfrac{5}{128},\tfrac{7}{256},\tfrac{21}{1024},\tfrac{33}{2048},\tfrac{429}{32768},\tfrac{715}{65536},\tfrac{2431}{262144},\tfrac{4199}{524288} \end{equation*} for $n=1,\dots,11$. Generally when the critical branching process begins with $k$ initially infected individuals, infection processes originated with each individual are independent. Hence the probability $A_n^{(k)}$ that exactly $n$ individuals catch the infection before the epidemic is over can be expressed via the probabilities $A_m \equiv A_m^{(1)}$ corresponding to the classical situation with one initially infected individual: \begin{equation} \label{An-k} A_n^{(k)} = \sum_{i_1+\ldots+i_k=n}A_{i_1}\ldots A_{i_k} \end{equation} The generating function \begin{equation} \label{gen-k-def} \mathcal{A}^{(k)}(z) = \sum_{n\geq k}A_n^{(k)} z^n \end{equation} is therefore \begin{equation} \label{gen-k} \mathcal{A}^{(k)}(z) = [\mathcal{A}(z)]^k = \left\{1 - \sqrt{1-z}\right\}^k \end{equation} This generating function encapsulates all $A_n^{(k)}$, but it is desirable to obtain more explicit representation. Needless to say, $A_n^{(k)}=0$ when $n<k$. When $n\geq k$, one can express $A_n^{(k)}$ through the probabilities \eqref{An_sol}. Here are a first few explicit formulas: \begin{equation*} \begin{split} &A_n^{(2)} = 2A_n\\ &A_n^{(3)} = 4A_n - A_{n-1}\\ &A_n^{(4)} =8A_n - 4A_{n-1}\\ &A_n^{(5)} =16A_n - 12A_{n-1} + A_{n-2}\\ &A_n^{(6)} =32A_n - 32A_{n-1} + 6A_{n-2}\\ &A_n^{(7)} =64A_n - 80A_{n-1} + 24A_{n-2}-A_{n-3}\\ &A_n^{(8)} =128A_n - 192A_{n-1} + 80A_{n-2}-8A_{n-3}\\ &A_n^{(9)} =256A_n - 448A_{n-1} + 240A_{n-2}-40A_{n-3}+ A_{n-4} \end{split} \end{equation*} The general formula is \begin{equation} \label{Ank-sum} A_n^{(k)}=\sum_{p=0}^{\lfloor \frac{k-1}{2}\rfloor} (-1)^p \binom{k-1-p}{p} 2^{k-1-2p}A_{n-p} \end{equation} where $\lfloor x\rfloor$ denotes the largest integer $\leq x$. \begin{figure} \centering \includegraphics[width=7.89cm]{An-k-3} \caption{Top to bottom: $\sqrt{k}\,A_n^{(k)}$ versus $n/k$ for $k=1, 16, 30$. The asymptotic behavior is $(4\pi)^{-1/2} (n/k)^{-3/2}$ in agreement with Eq.~\eqref{An-k-asymp}. } \label{Fig:An-k} \end{figure} Plugging \eqref{An_sol} into the sum in Eq.~\eqref{Ank-sum}, one reduces the sum to a hypergeometric series \cite{Knuth}. Using identities involving hypergeometric series \cite{Knuth}, as well as identities involving the gamma function (particularly, the duplication formula), we have computed the sum in \eqref{Ank-sum} and arrived at a neat final formula \begin{equation} \label{Ank-gamma} A_n^{(k)}=\frac{k}{2^{2n-k}}\,\frac{\Gamma(2n-k)}{ \Gamma(n+1-k)\Gamma(n+1)} \end{equation} Note that substituting \eqref{An_sol} into the recurrence \eqref{An-k} one can directly compute \begin{equation} \label{Akk} \begin{split} &k\geq 1: \quad A_k^{(k)} =\frac{1}{2^k} \\ &k\geq 2: \quad A_{k+1}^{(k)}=\frac{k}{2^{k+2}} \\ &k\geq 3: \quad A_{k+2}^{(k)}=\frac{k}{2^{k+3}}+ \frac{k(k-1)}{2^{k+5}} \end{split} \end{equation} These results are recovered from the general solution \eqref{Ank-gamma} thereby providing a consistency check. As another consistency check we note that \eqref{Ank-gamma} agrees with normalization \begin{equation} \label{norm} \sum_{n\geq k} A_n^{(k)}=1 \end{equation} The sequence $A_n^{(k)}$ has a single peak located at $n=k$ when $k\leq 4$, while for $k\geq 5$ the peak is at $n=\nu(k)>k$, see Fig.~\ref{Fig:An-k}. The sequence $A_n^{(k)}$ grows from $A_k^{(k)}=2^{-k}$ to the maximum \begin{equation} \label{An-k-max} b(k):=\text{max}\{A_n^{(k)}|\, n\geq k\} \end{equation} at $n=\nu(k)$, then decays and eventually approaches \begin{equation} \label{An-k-asymp} A_n^{(k)}\simeq \frac{k}{\sqrt{4\pi}}\,n^{-3/2} \end{equation} This asymptotic behavior is straightforwardly deduced from \eqref{Ank-gamma}. Using the general solution \eqref{Ank-gamma} together with the Stirling formula one can establish the behaviors of $b(k)$ and $\nu(k)$ in the $k\to\infty$ limit. One gets \begin{equation} \label{nu-a} \nu(k)\simeq \tfrac{1}{6}k^2, \qquad b(k)\simeq B k^{-2} \end{equation} with \begin{equation} \label{C:def} B=3e^{-3/2}\sqrt{\frac{6}{\pi}}= 0.92508197882\ldots \end{equation} The general solution \eqref{Ank-gamma} approaches the scaling form \begin{equation} \label{Ank-scaling} A_n^{(k)}=\frac{4}{k^2}\,\Phi(\mu), \quad \Phi(\mu)=\pi^{-1/2} \mu^{-3/2}\,e^{-1/\mu} \end{equation} in the scaling limit \begin{equation} \label{mu-scaling} n\to\infty, \quad k\to \infty, \quad \mu=\frac{4n}{k^2}= \text{finite} \end{equation} \begin{figure} \centering \includegraphics[width=7.89cm]{Phi-mu} \caption{The scaled distribution $\Phi(\mu)$ versus the scaled outbreak size $\mu$ given by Eq.~\eqref{Ank-scaling}. } \label{Fig:Phi} \end{figure} The scaled distribution $\Phi(\mu)$ has a single peak (Fig.~\ref{Fig:Phi}) and it vanishes faster than any power of $\mu$ when $\mu\to 0$. We also note that from Eqs.~\eqref{Ank-scaling}--\eqref{mu-scaling} one easily recovers \eqref{nu-a}--\eqref{C:def}. Due to the algebraic tail \eqref{An-k-asymp}, the moments defined by $\langle n^a\rangle = \sum_{n\geq k} n^a A_n^{(k)}$ diverge when $a\geq \frac{1}{2}$. To perform the summation in the $a<\frac{1}{2}$ range where the moments converge it is convenient to consider modified moments with $n^a$ replaced by $\Gamma(n+1)/\Gamma(n+1-a)$. Such moments admit an analytical expression \begin{equation} \label{moments-a-k} \sum_{n\geq k} \frac{\Gamma(n+1)}{\Gamma(n+1-a)}\, A_n^{(k)}=\frac{\Gamma(1-2a)}{\Gamma(1-a)}\, \frac{\Gamma(1+k)}{\Gamma(1-2a+k)} \end{equation} Identities which we have used in computing the sum in \eqref{moments-a-k} are standard, they can be found e.g. in Ref.~\cite{Knuth}. When $k\gg 1$, the modified moments are asymptotically equal to the regular moments since $\frac{\Gamma(n+1)}{\Gamma(n+1-a)}\to n^a$ for $n\geq k\gg 1$, so Eq.~\eqref{moments-a-k} simplifies to \begin{equation} \label{mom-a-k} \langle n^a\rangle=\sum_{n\geq k} n^a A_n^{(k)}\simeq \frac{\Gamma(1-2a)}{\Gamma(1-a)}\, k^{2a} \end{equation} The moments $\langle n^a\rangle$ remain finite for finite populations, but diverge as $N\to\infty$ if $a\geq \frac{1}{2}$. This divergent leading behavior of the moments in finite populations is computed in the next section; in the simplest case of $k=1$, it is given by Eq.~\eqref{mom-a-k-N}. \section{Outbreak Size Distribution: Scaling Analysis} \label{sec:SIR} Consider the critical SIR process with $k$ initially infected individuals, but in a finite population. Denote by $N$ the size of the population and by $A_n(k; N)$ the probability that the size of the outbreak is $n$. In the infinite-population limit, $A_n(k; \infty)\equiv A_n^{(k)}$ is given by \eqref{Ank-gamma}; it approaches the scaling form \eqref{Ank-scaling}--\eqref{mu-scaling} when $k\gg 1$. The probability distribution $A_n(N)\equiv A_n(1; N)$ for the critical SIR process starting with a single initially infected individual has been previously investigated in Refs.~\cite{bk,KS,Gordillo,Hofstad,bk12}. The probability disrtibution $A_n(N)$ acquires a scaling form \begin{equation} \label{AAF} A_n(N)= A_n\, F(\nu) \end{equation} in the scaling limit \begin{equation} \label{scaling} n\to\infty, ~~N\to\infty, ~~\nu=\frac{n}{N^{2/3}}=\text{finite} \end{equation} This scaling was proposed and numerically supported in \cite{bk}. Kessler and Shnerb \cite{KS} derived the scaling function $F(\nu)$. The moments $\langle n^a\rangle$ which diverge in the infinite-population limit when $a\geq \frac{1}{2}$ are now finite. In this range, the scaling \eqref{AAF}--\eqref{scaling} implies the following leading asymptotic behavior \begin{equation} \label{mom-a-k-N} \langle n^a\rangle\simeq \begin{cases} (9\pi)^{-1/2}\ln N & a = \frac{1}{2}\\ C_a N^\frac{2a-1}{3} & a > \frac{1}{2} \end{cases} \end{equation} with \begin{equation} \label{Ca} C_a = \int_0^\infty \frac{d\nu}{\sqrt{4 \pi}}\,\nu^{a-3/2}F(\nu) \end{equation} Two most important cumulants are the average $\mathbb{E}_k(N)=\langle n\rangle$ and the variance $\mathbb{V}_k(N)=\langle n^2\rangle- \langle n\rangle^2$. When $k=1$, these cumulants exhibit the following growth with the population size \begin{subequations} \begin{equation} \label{EV:CC} \mathbb{E}_1(N) \simeq C_1 N^{1/3}, \qquad \mathbb{V}_1(N) \simeq C_2 N \end{equation} The amplitudes can be (numerically) computed using the exact expression \cite{KS} for the scaling function to give \begin{equation} \label{CC:12} C_1=1.4528\ldots, \quad C_2\approx 3.99 \end{equation} \end{subequations} In the general case, the distribution $A_n(k,N)$ depends on three variables. The interesting range is \begin{equation} \label{nNkN} n\sim N^{2/3}, \quad k\sim N^{1/3} \end{equation} The first scaling in \eqref{nNkN} follows from \eqref{scaling}, the second is an outcome of \eqref{mu-scaling} and \eqref{scaling}. In the scaling region \eqref{nNkN}, the distribution $A_n(k,N)$ is expected to acquire a scaling form \begin{equation} \label{ANG} A_n(k,N) = N^{-2/3}\, G(\kappa,\nu) \end{equation} with $\nu=n/N^{2/3}$, see Eq.~\eqref{scaling}, and the scaled initial number of infected individuals $\kappa=k/N^{1/3}$. More precisely, \eqref{ANG} should hold in the scaling limit \eqref{scaling} and \begin{equation} \label{kN-scaling} k\to\infty, ~~N\to\infty, ~~\kappa=\frac{k}{N^{1/3}}=\text{finite} \end{equation} The normalization condition, $\sum_{n\geq k}A_n(k,N)=1$, gives $\int_0^\infty d\nu\, G(\kappa,\nu)=1$ and explains the pre-factor in \eqref{ANG}. The two-variable distribution $G(\kappa,\nu)$ is unknown, so let us discuss the average outbreak size which is the basic quantity with simpler scaling behavior. The average outbreak size $\mathbb{E}_k(N)$ depends on two variables and its conjectural scaling behavior is \begin{equation} \label{av-scaling} \mathbb{E}_k(N) = N^{2/3}\Psi(\kappa) \end{equation} The two scaling behaviors, \eqref{ANG} and \eqref{av-scaling}, are compatible if $\Psi(\kappa) = \int_0^\infty d\nu\, \nu G(\kappa,\nu)$. We now show that the scaled distribution $\Psi(\kappa)$ has simple extremal behaviors \begin{equation} \label{kappa-extreme} \Psi(\kappa) = \begin{cases} C_1\kappa &\text{when}\quad \kappa\ll 1\\ \sqrt{2\kappa} &\text{when}\quad \kappa\gg 1 \end{cases} \end{equation} with $C_1$ appearing in \eqref{EV:CC}--\eqref{CC:12}. To establish the small $\kappa$ asymptotic we note that in the $k\ll N^{1/3}$ regime, the infectious processes generated by each initially infected individual are mutually independent. Thus \begin{equation} \label{NkN-asymp} \mathbb{E}_k(N) \simeq C_1\, k\, N^{1/3} \qquad\text{when}\quad k\ll N^{1/3} \end{equation} Comparing \eqref{av-scaling} and \eqref{NkN-asymp} we obtain $\Psi(\kappa)\simeq C_1\kappa$ as $\kappa\to 0$ as asserted in \eqref{kappa-extreme}. To establish the large $\kappa$ behavior we first mention that $\mathbb{E}_N(N) = N$. This suggests that $\Psi(N^{2/3}) \sim N^{1/3}$, from which $\Psi(\kappa)\sim \sqrt{\kappa}$ as $\kappa\to \infty$. This argument is heuristic. In Sec.~\ref{sec:EA}, we derive the large $\kappa$ asymptotic asserted in \eqref{kappa-extreme}. In Appendix \ref{ap:det}, we present an elementary derivation based on the observation that the behavior in the $\kappa\to \infty$ limit is essentially deterministic. The deterministic analysis is significantly simpler than the exact approach, but it cannot be used to study fluctuations while using the exact approach we also compute the variance (Sec.~\ref{sec:EA}). Simulation results \cite{Ginestra} are in a reasonably good agreement with the (conjectural) scaling behavior \eqref{kN-scaling}--\eqref{av-scaling}. The numerical data \cite{Ginestra} well agree with \eqref{kappa-extreme} in the small $\kappa$ limit: $\Psi(\kappa) = C_1\kappa$ with $C_1\approx 1.5$ in simulations, the analytical prediction is $C_1=1.4528\ldots$. In the large $\kappa$ limit, numerical data in \cite{Ginestra} were fitted to $\sqrt{\kappa}$ up to a logarithmic correction. We now turn to the variance. For sufficiently small $k$, we rely again on the mutual independence of $k$ infectious processes to deduce \begin{equation} \label{Var-asymp} \mathbb{V}_k(N) \simeq C_2\, k\, N \qquad\text{when}\quad k\ll N^{1/3} \end{equation} The scaling region is given by \eqref{kN-scaling}. The natural scaling behavior of the variance compatible with \eqref{Var-asymp} is \begin{equation} \label{var-scaling} \mathbb{V}_k(N) = N^{4/3}\Psi_2(\kappa) \end{equation} where $\Psi_2(\kappa)\simeq C_2\kappa$ when $\kappa\to 0$. The asymptotically exact behaviors in the complimentary $\kappa\to \infty$ limit is established in Sec.~\ref{sec:EA}. Summarizing, \begin{equation} \label{var-extreme} \Psi_2(\kappa) \simeq \begin{cases} C_2\kappa &\text{when}\quad \kappa\ll 1\\ \sqrt{2/\kappa} &\text{when}\quad \kappa\gg 1 \end{cases} \end{equation} Simulation results \cite{Ginestra} support an algebraic decay in the $\kappa\to \infty$ limit: $\Psi_2\sim \kappa^{-\gamma}$. The numerical uncertainty \cite{Ginestra} in the magnitude of the exponent $\gamma$ is rather significant, $\gamma=0.75\pm 0.15$. \section{Outbreak Size Distribution: Exact treatment} \label{sec:EA} The critical SIR process admits an exact treatment. Denote by $s, i$ and $r$ the population sizes in the susceptible, infected and recovered individuals. The entire population is constant: \begin{equation} \label{all} s + i + r = N \end{equation} Due to the constraint \eqref{all}, the state of the process can be described by any pair of variables $s, i, r$. We choose $(i,x)$ with $x=N-s$. For the critical SIR process, in the interesting regime $s$ is close to $N$, viz. $N-s\ll N$, and hence $x$ is a more convenient variable than $s$. The constraint \eqref{all} shows that $x=i+r$, so $x\geq i$. Infection and recovery events are symbolically \begin{subequations} \begin{align} \label{inf} & (i,x) \to (i+1,x+1) ~\quad \text{rate} ~~ i(N-x)/N\\ \label{rec} & (i,x) \to (i-1,x) \quad\qquad \text{rate} ~~ i \end{align} \end{subequations} Denote by $t(i,x)$ the number of transitions from the state $(i,x)$ to termination. We are mostly interested in $t(k,k)$, i.e., starting with $k$ infected and no recovered. The process terminates at some state $(0,n)$, where $n$ is the size of the outbreak. The rules \eqref{inf} and \eqref{rec} show that the quantity $i-2x$ decreases by 1 in each transition. Thus starting at $(i,x)=(k,k)$ gives $i-2x=-k-T$ after $T$ transitions, and in particular \begin{equation} \label{n:tkk} n=\frac{k+t(k,k)}{2} \end{equation} The rates of the processes \eqref{inf} and \eqref{rec} imply that they occur with probabilities \begin{equation} p_+(x)=\frac{N-x}{2N-x}\,, \quad p_-(x)=\frac{N}{2N-x} \end{equation} The stochastic transition time $t(i,x)$ evolves according to the rules \begin{equation} \label{tix:rules} t(i,x) = \begin{cases} 1+t(i+1,x+1) & \text{prob} ~p_+(x)\\ 1+t(i-1,x) & \text{prob} ~p_-(x) \end{cases} \end{equation} \subsection{Average number of transitions} Averaging \eqref{tix:rules} we find that $T_1(i,x)=\langle t(i,x)\rangle$ satisfies \begin{equation} \label{T1:eq} T_1 = 1 + p_+T_1(i+1,x+1)+ p_-T_1(i-1,x) \end{equation} To avoid cluttering of formulae, we write $p_\pm \equiv p_\pm(x)$ and $T_1\equiv T_1(i,x)$ when there is no confusion. The recurrence \eqref{T1:eq} should be solved subject to the boundary condition \begin{equation} \label{BC:cat} T_1(0,x)=0 \end{equation} The boundary-value problem \eqref{T1:eq}--\eqref{BC:cat} admits an exact solution \begin{eqnarray} \label{T1:exact} T_1 &=& i +2(N-x)\nonumber\\ & - & \sum_{j=1}^{N-x} \left(\frac{N}{N+j}\right)^{i+N-x-j} B_{j}^{(N-x)}(N) \end{eqnarray} with $B_{j}^{p}(N)$ determined recurrently from \begin{equation} \begin{split} \label{Bjp} & B_{j}^{(p)}(N) = \frac{p}{p-j}\,B_{j}^{(p-1)}(N) \,, \quad j=1,\ldots,p-1\\ & B_{p}^{(p)}(N) = 2p - \sum_{j=1}^{p-1} \left(\frac{N}{N+j}\right)^{p-j} B_{j}^{(p)}(N) \end{split} \end{equation} One can verify by direct substitution that Eq.~\eqref{T1:exact} with amplitudes determined from the recurrent relations \eqref{Bjp} satisfies \eqref{T1:eq}--\eqref{BC:cat}. In Appendix \ref{ap:exact}, we show that the guess form \eqref{T1:exact} is rather natural. Specializing \eqref{T1:exact} to $i=x=k$ we obtain \begin{eqnarray} \label{Tkk} T_1(k,k) &=& 2N -k \nonumber\\ & - & \sum_{j=1}^{N-k} \left(\frac{N}{N+j}\right)^{N-j} B_{j}^{(N-k)}(N) \end{eqnarray} from which the average size of an outbreak is \begin{equation} \label{av:outbreak} \mathbb{E}_k(N)=N-\frac{1}{2}\sum_{j=1}^{N-k} \left(\frac{N}{N+j}\right)^{N-j} B_{j}^{(N-k)}(N) \end{equation} Thus, we have found an exact formula \eqref{av:outbreak} for the average size of the outbreak. We have not succeeded in extracting an asymptotic behavior of the sum in \eqref{av:outbreak}. There are two technical challenges. First, the amplitudes, which are in principle known from the recurrence relations \eqref{Bjp}, are unwieldy. Second, the sum involves $N-k$ terms. One can find compact exact results when $N-k=O(1)$, see Appendix \ref{ap:exact}. In the interesting range $k=O(N^{1/3})$, and hence the number of terms in the sum is huge. Another line of attack on discrete problems relies on continuum methods. We assume that $T_1(i,x)$ is a smooth function of $i$ and $x$, and we expand $T_1(i+1,x+1)$ and $T_1(i-1,x)$ appearing in \eqref{T1:eq} up to the second order \begin{equation} \label{T1:exp} \begin{split} T_1(i-1,x) &= T_1 - \partial_i T_1 + \tfrac{1}{2}\partial_i^2 T_1 \\ T_1(i+1,x+1) &= T_1 + \partial_i T_1 + \partial_x T_1 \\ &+ \tfrac{1}{2}\partial_i^2 T_1 + \tfrac{1}{2}\partial_x^2 T_1 + \partial_i \partial_x T_1 \end{split} \end{equation} Here $\partial_i=\partial/\partial i$, $\partial_x=\partial/\partial x$, etc. denote partial derivatives. Inserting \eqref{T1:exp} into \eqref{T1:eq} and keeping only dominant terms we obtain \begin{equation} \label{t:ix} \partial_i^2 T_1 + \partial_x T_1 + 2 = \frac{x}{N}\,\partial_i T_1 \end{equation} Suppose that the scaling in the interesting range is \begin{equation} \label{abc} i\sim N^\alpha, \quad x\sim N^\beta, \quad T_1\sim N^\gamma \end{equation} Plugging \eqref{abc} into \eqref{t:ix} we find that the terms in are comparable only when $\alpha=\frac{1}{3}$ and $\beta=\gamma=\frac{2}{3}$. Thus we re-scale the variables \begin{equation} \label{IX} i = N^{1/3} I, \quad x = N^{2/3} X \end{equation} and the average number of transitions \begin{equation} \label{TIX:def} T_1(i,x) = N^{2/3} \mathcal{T}(I, X) \end{equation} One can verify that terms not included in \eqref{t:ix} are subdominant. For instance, computing the second derivates gives $\partial_i \partial_x T_1=O(N^{-1/3})$ and $\partial_x^2 T_1=O(N^{-2/3})$, so these derivatives can indeed be dropped. The transformation \eqref{IX}--\eqref{TIX:def} turns \eqref{t:ix} into a partial differential equation (PDE) \begin{equation} \label{TIX} \frac{\partial^2 \mathcal{T}}{\partial I^2} + \frac{\partial \mathcal{T}}{\partial X} + 2= X\frac{\partial \mathcal{T}}{\partial I} \end{equation} for the re-scaled transition time $\mathcal{T}(I, X)$. We must solve \eqref{TIX} in the quadrant $I\geq 0$ and $X\geq 0$. The boundary condition \eqref{BC:cat} yields \begin{equation} \label{BC:cont} \mathcal{T}(0, X) = 0 \end{equation} Solving the boundary-value problem \eqref{TIX}--\eqref{BC:cont} is an intriguing challenge that we leave for the future. Here we limit ourselves by a simpler problem of computing the asymptotic behavior of $T_1(k,k)$ when $k\gg N^{1/3}$. In the realm of the framework \eqref{IX}--\eqref{BC:cont}, we should learn how to extract the large $I$ behavior of $\mathcal{T}(I, X)$. This can be done by noting that when $I\gg 1$, the diffusion term can be dropped from Eq.~\eqref{TIX}. Thus we arrive at the first order PDE \begin{equation} \label{PDE} \frac{\partial \mathcal{T}}{\partial I} - \frac{1}{X}\,\frac{\partial \mathcal{T}}{\partial X} = \frac{2}{X} \end{equation} Introducing new variables \begin{equation} \label{uv} u = I + \tfrac{1}{2}X^2\,, \qquad v = I - \tfrac{1}{2}X^2 \end{equation} we recast \eqref{PDE} into \begin{equation} \label{PDE:uv} \frac{\partial \mathcal{T}}{\partial v} = \frac{1}{\sqrt{u-v}} \end{equation} The solution is \begin{equation*} \mathcal{T}=-2\sqrt{u-v}+f(u) \end{equation*} with an arbitrary function $f(u)$. The boundary condition \eqref{BC:cont} gives $\mathcal{T} = 0$ when $v=-u$. This fixes $f(u)=2\sqrt{2u}$. Combining $\mathcal{T}= 2\sqrt{2u}-2\sqrt{u-v}$ and \eqref{uv} we obtain \begin{equation} \label{far} \mathcal{T}(I, X) = 2\sqrt{2I+X^2}-2X \end{equation} We want to determine $T_1(k,k) = N^{2/3} \mathcal{T}(\kappa, N^{-1/3}\kappa)$. Thus $I=\kappa\gg 1$ and $X=0$ as we always consider large populations, $N\gg 1$. More precisely, setting $X=0$ amounts for a tacit assumption $\kappa\ll N^{1/3}$. Summarizing, our asymptotic results are valid in the range \begin{equation} \label{k-bounds} N^{1/3}\ll k \ll N^{2/3} \end{equation} The upper and lower bounds are well separated when $N^{1/3}\gg 1$. This is satisfied for large populations, yet the convergence may be slow as the effective small parameter is $N^{-1/3}$. Thus $T_1(k,k) = N^{2/3} \mathcal{T}(\kappa, 0)$ when the bounds \eqref{k-bounds} are obeyed. Using Eq.~\eqref{far} we get $T_1(k,k) = \sqrt{8kN}$ which we insert into $\mathbb{E}_k(N)=[k+T_1(k,k)]/2$ obtained after averaging Eq.~\eqref{n:tkk}. Keeping only the leading term gives $\mathbb{E}_k(N) = \sqrt{2kN}$. This completes the derivation of the large $\kappa$ behavior announced in Eq.~\eqref{kappa-extreme}. \subsection{Variance} Taking the square of Eq.~\eqref{tix:rules} and averaging we find that $T_2(i,x)=\langle t^2(i,x)\rangle$ satisfies \begin{eqnarray} \label{T2:eq} T_2 &=& 1 + p_+T_2(i+1,x+1)+ p_- T_2(i-1,x) \nonumber\\ &+& 2 p_+ T_1(i+1,x+1)+ 2p_- T_1(i-1,x) \end{eqnarray} Again we shortly write $p_\pm \equiv p_\pm(x)$ and $T_2\equiv T_2(i,x)$. We now subtract the square of Eq.~\eqref{T1:eq} from Eq.~\eqref{T2:eq} and find that the variance \begin{equation} V(i,x) = \langle t^2(i,x)\rangle - \langle t(i,x)\rangle^2 \end{equation} satisfies \begin{eqnarray} \label{V:eq} V &=&p_+V(i+1,x+1)+ p_- V(i-1,x) \nonumber\\ &+& p_+ p_- [T_1(i+1,x+1) - T_1(i-1,x)]^2 \end{eqnarray} Similar to \eqref{T1:exp} we expand the variance \begin{equation} \label{V:exp} \begin{split} V(i-1,x) &= V - \partial_i V + \tfrac{1}{2}\partial_i^2 V \\ V(i+1,x+1) &= V + \partial_i V + \partial_x V \\ &+ \tfrac{1}{2}\partial_i^2 V + \tfrac{1}{2}\partial_x^2 V + \partial_i \partial_x V \end{split} \end{equation} Plugging the expansions \eqref{T1:exp} and \eqref{V:exp} into \eqref{V:eq} and keeping only dominant terms we obtain \begin{equation} \label{V:ix} \partial_i^2 V + \partial_x V -\frac{x}{N}\, \partial_i V + 2(\partial_i T_1)^2 = 0 \end{equation} We use the same rescaled variables \eqref{IX} as before, and seek the variance in the scaling form \begin{equation} \label{VIX:def} V(i,x) = N^{4/3} \mathcal{V}(I, X) \end{equation} The transformation \eqref{IX} and \eqref{VIX:def} turns \eqref{V:ix} into \begin{equation} \label{VIX} \frac{\partial^2 \mathcal{V}}{\partial I^2} + 2 \left(\frac{\partial \mathcal{T}}{\partial I}\right)^2= X\frac{\partial \mathcal{V}}{\partial I} - \frac{\partial \mathcal{V}}{\partial X} \end{equation} When $I\gg 1$, we can drop again the diffusion term from \eqref{VIX}. We also use the asymptotic expression \eqref{far} for $\mathcal{T}(I,X)$ and arrive at the first order PDE \begin{equation} \label{VIX:1} X\frac{\partial \mathcal{V}}{\partial I} - \frac{\partial \mathcal{V}}{\partial X} = \frac{8}{2I+X^2} \end{equation} Using the variables \eqref{uv} we recast \eqref{VIX:1} into \begin{equation} \label{PDE:V} \frac{\partial \mathcal{V}}{\partial v} = \frac{2}{u\sqrt{u-v}} \end{equation} which is integrated to give $\mathcal{V}=4u^{-1}\left[\sqrt{2u}-\sqrt{u-v}\right]$, or \begin{equation} \label{far:V} \mathcal{V}(I, X) = 8\frac{\sqrt{2I+X^2}-X}{2I+X^2} \end{equation} We set again $I=\kappa$ and $X=0$ in \eqref{far:V} and arrive at the asymptotic $\mathcal{V}(\kappa, 0) = 4 \sqrt{2/\kappa}$ when $\kappa\gg 1$. Using Eq.~\eqref{n:tkk} we find $\mathbb{V}_k(N)=N^{4/3}\,\tfrac{1}{4}\mathcal{V}(\kappa, 0)$ which is indeed the large $\kappa$ behavior announced in Eq.~\eqref{var-extreme}. \section{Duration of Outbreaks} \label{sec:SIR-time} Some basic features of the duration of the outbreaks in the critical SIR process in a finite system can be extracted from the temporal behaviors in the infinite-population limit. We first recall these infinite-population results in the simplest case with one initially infected individual \cite{Bailey,bk12}. The probability $P_i(t)$ to have $i$ infected individuals at time $t$ satisfies \begin{subequations} \begin{align} \label{Pi:eq} \dot P_i & = (i-1)P_{i-1}-2iP_i+(i+1)P_{i+1}, \quad i\geq 1\\ \label{P0:eq} \dot P_0 & = P_1 \end{align} \end{subequations} where dot denotes the derivative with respect to time. A solution of an infinite set of equations \eqref{Pi:eq}--\eqref{P0:eq} subject to the initial condition $P_i(0)=\delta_{i,1}$ reads \begin{subequations} \begin{align} \label{Pi:sol} P_i(t) &=(1+t)^{-2}\, \tau^{i-1}, \quad i\geq 1\\ \label{P0:sol} P_0(t)&= \tau \equiv \frac{t}{1+t} \end{align} \end{subequations} This soultion can be verified by a direct substitution, or derived using e.g. generating function techniques [see Appendix \ref{ap:time} for details]. The probability that the outbreak is still alive at time $t$, is \begin{equation} \label{s} P(t)=\sum_{i\geq 1} P_i(t)=1-P_0(t)=\frac{1}{1+t} \end{equation} The average number of infected individuals in outbreaks which are still alive at time $t$ is therefore \begin{equation} \label{iav} \langle i\rangle=\frac{\sum iP_i(t)}{\sum P_i(t)}=1+t \end{equation} A general solution of Eqs.~\eqref{Pi:eq}--\eqref{P0:eq} describing an infinite-population limit subject to an arbitrary number of initially infected individuals is somewhat cumbersome, it is presented in Appendix \ref{ap:time}. In a finite population, the infection process eventually comes to an end. To estimate heuristically this final time $t_\text{f}$ one uses \eqref{iav} to express \cite{bk} the final size of the outbreak through the final time: $n_\text{f} \sim\int^{t_\text{f}} dt\,\langle i\rangle \sim t_\text{f}^2$. The maximal outbreak size scales as $n_*\sim N^{2/3}$ (see e.g. \cite{bk,KS,bk12}) and hence the maximal duration is \begin{equation} \label{TN3} t_* \sim n_*^{1/2} \sim N^{1/3} \end{equation} The average duration of the outbreak is formally \begin{equation} \label{time-av} \mathbb{E}[t] = \int_0^\infty dt\,t\left(-\frac{dP}{dt}\right) = \int_0^\infty dt\,t P_1(t) \end{equation} Recalling that $P_1(t)=(1+t)^{-2}$ in the infinite-population limit (equivalently, for the critical branching process), we notice that the integral in \eqref{time-av} diverges. We should use, however, the finite upper limit given by \eqref{TN3}. This leads to an estimate \begin{equation} \label{time-av-log} \mathbb{E}_1[t] \simeq \int_0^{\sqrt[3]{N}} dt\,\frac{t}{(1+t)^2} \simeq \frac{1}{3}\,\ln N \end{equation} where the subscript reminds that the process begins with a single infected individual. The logarithmic growth of the average duration time was predicted by Ridler-Rowe many years ago \cite{rr}, albeit with incorrect amplitude; the correct amplitude $1/3$ is easy to appreciate \cite{caveat}, it was argued and numerically supported in \cite{bk,bk12}. The above argument also suggests the more precise asymptotic \begin{equation} \label{time-av-log-1} \mathbb{E}_1[t] = \tfrac{1}{3}\ln N + c_1 + o(1/N) \end{equation} Since the logarithm is a slowly growing function, the sub-leading constant term $c_1$ significantly contributes to the average duration. The computation of the sub-leading term requires much more comprehensive analysis than what we have used so far. If the number of initially infected individuals is sufficiently small, $k\ll N^{1/3}$, one can generalize the prediction \eqref{time-av-log} for the average duration of an outbreak without using a complete solution of the infinite-population limit (Appendix \ref{ap:time}), it suffices to rely on the independence of infection processes generated by each initially infected individual. The probability that the infection is over at time $t$ is $P_0^k$, with $P_0$ given by \eqref{P0:sol}. Thus $-dP_0^k/dt=kP_0^{k-1}/(1+t)^2$ is the probability density that the infection is eradicated at time $t$, from which \begin{equation} \label{time-av-log-k} \mathbb{E}_k[t] \simeq \int_0^{\sqrt[3]{N}} dt\,\frac{kt^k}{(1+t)^{k+1}} \simeq \frac{k}{3}\,\ln N \end{equation} implying that the average duration of the outbreak exhibits a simple logarithmic scaling with amplitude proportional to the initial number of infected individuals. To guess the scaling form we notice that \eqref{time-av-log-k} can be re-written as $\mathbb{E}_k[t] \simeq k\, \ln(N^{1/3} k^{-1})$ with the same leading accuracy. Thus one plausible scaling form is \begin{equation} \label{av-time-scaling} \mathbb{E}_k[t] = N^{1/3}\, \Theta(\kappa) \end{equation} with $\Theta(\kappa)\simeq -\kappa \ln \kappa$ when $\kappa\to 0$. The variance can be probed similarly to the average, see \eqref{time-av-log}. One establishes the scaling law \begin{equation} \label{time-var} \mathbb{V}_1[t] \sim \int_0^{\sqrt[3]{N}} dt\,\frac{t^2}{(1+t)^2} \sim N^{1/3} \end{equation} but not an amplitude. Independence gives $\mathbb{V}_1[t] \sim kN^{1/3}$ when $k\ll N^{1/3}$, and hence the hypothetical scaling form of the variance is \begin{equation} \label{var-time-scaling} \mathbb{V}_k[t] = N^{2/3}\, \Theta_2(\kappa) \end{equation} with $\Theta_2(\kappa)\sim \kappa$ when $\kappa\to 0$. Simulations \cite{Ginestra} support the scaling law \eqref{var-time-scaling} and the linear small $\kappa$ behavior. Simulations also suggest \cite{Ginestra} that the scaled distribution $\Theta_2(\kappa)$ is inversely proportional to $\kappa$ in the large $\kappa$ limit. Thus \begin{equation} \label{var-time-extreme} \Theta_2(\kappa)\sim \begin{cases} \kappa & \kappa\to 0\\ \kappa^{-1} & \kappa\to\infty \end{cases} \end{equation} The scaling behavior of the average outbreak duration seems rather tricky. A scaling form with pre-factor being a product of an algebraic and a logarithmic in $N$ terms has been used in \cite{Ginestra} to fit simulation data. This scaling form is notably different from three other scaling forms that all have a standard purely algebraic in $N$ pre-factor [cf. Eqs.~\eqref{av-scaling}, \eqref{var-scaling}, and \eqref{var-time-scaling}]. It may be worthwhile to try to fit numerical data for the average outbreak duration with the standard scaling form \eqref{av-time-scaling}, but allowing the possibility of an anomalous small $\kappa$ behavior such as $\Theta(\kappa)\simeq -\kappa \ln \kappa$ argued above. \section{Conclusions} We have studied the critical SIR process starting with a large number of initially infected individuals, $k\gg 1$. Particularly interesting behaviors emerge when $k$ scales as a cubic root of the population size, $k\sim N^{1/3}$. The critical SIR process exhibits large fluctuations, so we have relied on the stochastic formulation. We have treated the problem using a combination of exact calculations and asymptotic methods. We have focused on the size and duration of the outbreaks, more precisely on the average and variance of these quantities. The analysis of the size of outbreaks is rather detailed, Secs.~\ref{sec:SIR}--\ref{sec:EA}. Our analytical and asymptotic predictions qualitatively agree with simulation results \cite{Ginestra}. Whenever there is a little discrepancy between simulation results and theoretical predictions, it seems that data may be fitted using slightly different scaling forms, simpler than the fits used in Ref.~\cite{Ginestra}. The chief reason for subtle behaviors are algebraic tails, the average size and duration of outbreaks are especially sensitive to these tails. There are many remaining challenges. For instance, we have found the average size of outbreaks (Sec.~\ref{sec:EA}). The exact expression for the average size involves the sum of $N-k$ terms, with amplitudes determined recurrently but becoming increasingly cumbersome. We have not succeeded in extracting a clean asymptotic behavior of this sum. We have also shown that continuum methods in principle allow one to determine the scaling functions, one should just solve linear PDEs with non-constant coefficients. We have used continuum methods in extracting asymptotic behaviors of the scaling functions. The derivation of the exact average size in Sec.~\ref{sec:EA} can be probably generalized to establish the variance, and perhaps all cumulants (that is, to compute the cumulant generating function). \vskip 1cm \noindent {\bf Acknowledgments.} I want to thank Ginestra Bianconi and Sid Redner for collaboration on similar problems, G. Bianconi and F. Radicchi for sending a preliminary version of Ref.~\cite{Ginestra}, and Boston University Network group for discussions.
{'timestamp': '2020-09-21T02:17:50', 'yymm': '2009', 'arxiv_id': '2009.08940', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.08940'}
arxiv
\section{Introduction} Robotic arms are showing a continual expansion in use, with expected growth continuing into the foreseeable future \cite{marketreport}. While the use of robotic arms continues to grow, they do not have a standard form of communication \cite{saunderson2019robots}, and current methods are costly to implement from both a technical and financial perspective. These systems generally focus on communicating intent, or describing what the arm will be about to perform, while less research has been done on the application of social and emotional communication. For collaborative processes, displaying emotion has repeatedly been shown to increase key collaboration metrics in robotics, such as likelihood of humans to follow social norms in robotic interactions\cite{jost2019examining}, better engagement with disability \cite{10.1145/3369457.3370915} and treating robots like an equal human collaborator \cite{desideri2019emotional}. It is even argued that no real collaboration can take place without social and emotional display \cite{fischer2019collaborative}. We believe musical prosody, that uses non-linguistic audio phrases based on musical melodies, can be used for effective interaction with human collaborators without requiring a change in core functionality. The ability for sound to display information for robotic platforms beyond trivial indicators is often underutilized, despite the use of intentional sound to deliver information in almost every device we encounter day to day \cite{walker1996human}. It has also been shown that displaying emotion is key for creating believable agents that people enjoy collaborating with \cite{Mateas:1999:ORI:1805750.1805762}, and prosody is effective in displaying emotions for humans and robots \cite{crumpton2016survey}. While affective nonverbal behavior has been shown to affect HRI metrics like humans' emotional state, self-disclosure, and perceived animacy of the robot \cite{rosenthal2018effects}, gestures are often studied \cite{beck2010towards}, but non-linguistic forms of audio feedback are under-explored \cite{macdorman2006subjective}. Prosody has the potential to allow the robot to communicate in a manner relatable to that of humans, but still different enough from human speech to avoid the uncanny valley \cite{macdorman2006subjective}. Emotional musical prosody is therefore uniquely positioned to enable better robotic communication and collaboration, capturing the advantages of sonic interaction, emotion conveyance and avoiding uncanny valley. In this paper we describe our approach to musical prosody using a custom dataset of musical phrases for robotic arm interaction. We evaluate these interactions firstly to confirm that there is no impact through potential distraction in collaboration with a robotic arm. We then measure how musical prosody compares to single-pitch audio and no audio systems for trust, trust recovery, likeability and the perception of intelligence and safety. \section{Background} \subsection{Robotic Arm Forms of Communication} Amongst research into methods for robotic arms to communicate and signal their intent, there is no standardized set of approaches \cite{cha2018survey}. In social robotics communication is often derived from human behaviour - such as gestures and gaze - these are not however readily available to robotic arms \cite{rosen2019communicating}. Additionally when these forms of communication are added to arms they require significant expense, such as extra visual displays like a face\cite{6839819}, or in the case of added gestures risk challenging and reducing the core functionality of the arm. In robotic research, forms of non-verbal communication can generally be split into four categories; kinesics, proxemics, haptics and chronemics, none of which are easily applied to an existing robotic system \cite{saunderson2019robots}. While varying movement to show intent has shown successful results \cite{bodden2016evaluating}, changes to path planning and movement dynamics is often not feasible. Another effective method for arms to display their intent is through vision of a robot's future trajectory, such as by a human worn head mounted display \cite{ruffaldi2016third}, however this requires a significant investment and potential distraction to the user. Emotion has been more commonly used as an input to robotic arms, such as facial emotion recognition to control and change the behaviour of robotic arms \cite{saverysurvey}. Likewise, Galvanic Skin Response emotional evaluation on humans has been used to impact a robot's control pattern \cite{takahashi2001human}. Nevertheless, robotic arm displays of emotion in work and collaboration, or interaction beyond showing intent are widely overlooked in robotics literature. \subsection{Communication for Trust and Trust Recovery} For collaboration with robotic arms trust is required, without which they can be underutilized \cite{johndlee}. Trust is largely developed in the first phase of a relationship both between humans and robots \cite{kim2009repair}, meaning first impressions are crucial for trust. First impressions from audio and visual stimulus can also damage the ability to develop trust later on \cite{Schaefer2016}. In this work we focus on affective trust, which is developed through emotional bonds and personal relationship, not competence \cite{freedy2007measurement}. Affective trust makes relationships more resilient to mistakes by either party \cite{rousseau1998not}. The display of emotion is critical for affective trust and increases the willingness of collaboration \cite{gompei2018factors}. Music and prosody has been shown as a powerful medium to convey emotions \cite{sloboda1999music}. In music and robotics emotion can be categorized in many ways, such as a discrete categorical manner (happiness, sadness, fear, etc.) \cite{devillers2005challenges}, and through continuous dimensions such as valence and arousal \cite{russell2009emotion}. Most recent efforts to generate and manipulate robotic emotions through prosody focused on linguistic robotic communication \cite{crumpton2016survey}. \section{Methods} \subsection{Research Questions and Hypotheses} Our first research question focuses on understanding the role of musical prosody and trust for a robotic arm. \begin{itemize} \item [RQ1] \textit{How does emotional musical prosody alter trust and trust recovery from mistakes, compared to no audio and single-pitch audio?} \end{itemize} For this question our hypothesis is that the overall trust at the end of the interaction will be significantly higher for musical prosody over single-pitch and higher for single-pitch audio over no audio. Our next research question compares common HRI metrics between each system; the perceived intelligence, perceived safety and likeability of the robotic system. \begin{itemize} \item [RQ2] \textit{How does emotional musical prosody alter perceived safety, perceived intelligence and likeability? } \end{itemize} Our second research question explores the relation between users' self-reported metrics, gathered through highly cited surveys and their actual responses collected through a performance based task. We are interested in comparing whether the system that is trusted more through self-reports is actually then utilized more in performance based tasks. \begin{itemize} \item [RQ3] \textit{When a user indirectly self-reports higher levels of trust in a robot, does this in turn lead to higher utilization and trust in a robotic arm's suggestions?} \end{itemize} We hypothesize that users' self-reported trust ratings will correspond to their actual use and trust levels implied by choice to follow the decisions of the robotic system. We also hypothesize that by using musical prosody after mistakes, human collaborators will be more likely to trust the robotic arm's suggestions directly after a mistake. For the first two research questions, we believe that participants will develop an internal model of the robot as an interactive emotional collaborator for the prosody model. This will lead to higher levels of trust and improved perception of safety and intelligence. \subsection{Experimental Design} Our experiment requires participants to perform a pattern learning and prediction task collaboratively with a robot. This is followed by two commonly used surveys; Schaefer's survey for robotic trust \cite{schaefer2016measuring}, and the Godspeed measurement for Anthropomorphism, Animacy, Likeability, Perceived Intelligence, and the Perceived Safety of Robots\cite{bartneck2009measurement}. The study process followed 5 steps for each participant: \begin{enumerate} \item Consent form and introduction to online form \item Description of the pattern recognition task \item 20 Trial Pattern Recognition Tasks \item 80 Pattern Recognition Tasks, recorded for data \item Godspeed and Schaefer Trust Survey (order randomized per participant) \end{enumerate} The pattern learning method was originally created by Dongen et al. to understand the reliance on decisions and develop a framework for testing different agents\cite{van2013framework}. Since then it has been re-purposed many times, including for comparing the dichotomy of human-human and human-automation trust \cite{de2012world}, as well as the use of audio by cognitive agents\cite{muralidharan2014effects}. In our version of the pattern recognition task, participants attempted to correctly predict the next number in a sequence. Participants were told beforehand that humans and the pattern recognition software being tested in the experiment tend to be about 70\% accurate on average, which has been shown to cause humans to alternate between relying on themselves and a decision agent. No further information was provided to the participants about the sequence's structure. The sequence was made up of a repeated sub-sequence that was 5 numbers long, containing only 1, 2, or 3 (such as 3, 1, 1, 2, 3). To prevent the ability for participants to quickly identify the pattern, 10\% of the numbers in the sequence were randomly altered. Participants first completed a training exercise to learn the interface, in which a sub-sequence was repeated 4 times (20 total numbers). Then participants were informed a new sequence had been generated for the final task. This was generated in the same way, using a new sub-sequence with 16 repetitions (80 total numbers). Before the user chose which number they believed came next in the sequence, the robot would suggest an answer, with the robot being correct 70\% of the time (see Figure \ref{fig:sequence}). This process mirrors the process from the original paper \cite{van2013framework}. The previous timestep's correct answer was displayed for the user at decision time to help them better keep track of the pattern throughout the time the robot takes to perform its movements. We required participants to submit their answer after the robot finished pointing to its prediction, which took between 2.5 and 4.5 seconds. This also forced participants to spend time considering their decision given the robot's recommendation. The robot would respond to the user's choice depending on the outcome and the version of the experiment, described in the following section. \begin{figure} [t] \centering \includegraphics[width=5cm]{images/flowchart.png} \caption{Robot Arm Emotional Response} \label{fig:sequence} \end{figure} \subsection{Experimental Groups and Robot Reactions} \label{subsec:groups} Our study was designed as a between-group experiment, where participants were randomly allocated to one of three groups. These groups were a prosody audio group (prosody), a single-pitch audio group (notes), and a control with no audio (gesture). The robot always responded to a user's action with the emotion determined by the process shown in Figure \ref{fig:sequence}. In all three versions of the experiment, the robot responded with the emotional gestures described in Section \ref{sec:gestures}. In the prosody group, the robot additionally responded with prosody-based audio sample, randomly selected each time from the five phrases matching the response emotion. These phrases which were obtained using the process described in Section \ref{sec:dataset}. In the notes group, the robot additionally responded instead with an audio file playing one note. Each emotion was randomly assigned one pitch from the midi pitches 62, 65, 69, and 72. This assignment remained consistent throughout the experiment to maintain a relation between the sounds and the outcome. For each pitch, five different audio files were available to be selected, each with a different instrument timbre and length (varying from 2-5 seconds), to provide variety similar to that of the five different prosody phrases available for each emotion. Finally, in the gesture group, the gesture was performed in silence. \subsection{Participants} We recruited 46 participants through the online survey platform Prolific\footnote{https://www.prolific.co/}. The participants ages ranged from 19 to 49, while the mean age was 25, with a standard deviation of 7. Participants were randomly sorted into one of the three categories, audio with emotional musical prosody (15 participants), single-pitch audio (16 participants), and no audio (15 participants). Each experiment took approximately 30 minutes to complete. Participants were paid \$4.75USD. \subsection{Dataset} \label{sec:dataset} In past work we created a deep learning generation system for musical prosody \cite{savery_finding_2019,savery2019establishing}. For this paper and experiment, we chose to use our recently created dataset of a human singing emotional phrases, to avoid any potential noise added by a generative system. The recorded dataset contains 4.22 hours of musical material recorded by Mary Carter\footnote{https://maryesthercarter.com/}, divided into 1-15 second phrases each corresponding to one of the 20 different emotions in the Geneva Emotion Wheel \cite{sacharin2012geneva} shown in Figure \ref{fig:geneva}. \begin{figure} [t] \centering \includegraphics[width=7cm]{images/geneva.png} \caption{Geneva Emotion Wheel} \label{fig:geneva} \end{figure} As part of our evaluation of the dataset, we manually selected 5 phrases for each emotion that we felt best represented the emotion, and had participants select an emotion and intensity when listening to each provided phrase. Participants recruited from Prolific and MTurk were used. For quality assurance, participants were randomly given test questions throughout the experiment telling them to select a certain answer. Each participant was given 6.5 on average, and responses which had more than one incorrect attention question were ignored, leaving a total of 45 participants for data analysis. In order to prevent the survey from being overly long, questions were randomly allocated, with 12 participants on average evaluating each individual phrase. Answers of None or Other were ignored in the analysis, resulting in an average of 11.3 valid evaluations for each phrase. Our analysis of the phrases used the metrics defined by Coyne et al\cite{coyne2020using}. We calculated the rated emotion's mean and variance in units of emotion (converted from degrees on the wheel), weighted by user-rated intensity. For the experiment, we used phrases for the four emotions joy, shame, sadness, and anger. These emotions were chosen as both being the emotions that best matched the outcomes in \ref{fig:sequence} and had gesture descriptions specified in \cite{walbott98}. 5 phrases for each emotion were chosen to add variety to the robot's response to not tire the user with the same sounds, while still allowing for only high-quality phrases to be included. In selecting the phrases for each of the four emotions, phrases from the closest two other emotions on the wheel within the same quadrant were also considered for selection. The sets were therefore \{joy, pride, pleasure\}, \{shame, disappointment, regret\}, \{sadness, guilt, regret\}, and \{anger, hate, contempt\}. We selected 5 of the 15 potential phrases for each by limiting length to be between 4 and 10 seconds, restricting the variance to be less than 2, requiring the weighted mean emotion rating to fall within the correct quadrant of the wheel, and finally selecting the phrases with the smallest difference between the actual emotion and mean rated emotion. \subsection{Interaction} Participants interacted with a virtual 3-D model of the robot in an application designed in Unity. Each time a participant was asked to answer a question, the robot acted as a decision agent, pointing to an answer that may be correct or incorrect. The user would then type their answer using their computer keyboard. There were three versions of the interaction application, varying the way the robot reacted to the user's answer, that are described in Section \ref{subsec:groups}. An example image of the interface is shown in Figure \ref{fig:interface}. \begin{figure} [h] \centering \includegraphics[width=7cm]{images/interface.png} \caption{Example image from the robot interaction application} \label{fig:interface} \end{figure} \subsection{Gestures} \label{sec:gestures} We created a gesture for each of the emotions joy, shame, sadness, and anger, as one way the robot reacted to user input. We designed the gestures by utilizing the table of emotion-specific nonverbal behaviors provided in \cite{walbott98}, which is based on work by Darwin, as well as their post-hoc overview of discriminative body movements and poses. These ideas have been used before in designing emotional robot gestures \cite{bretan2015emotionally}. Our joy gesture has the robot lift its arm up high, making three quick upwards movements alternating which side it faces. The shame gesture has the robot slowly bend down and away from the camera to one side. The sadness gesture has the robot slowly bend down while still centered with respect to the camera. The anger gesture has the robot first lean downwards and make two fast lateral movements, and then lean upwards to make two more fast lateral movements. Examples of poses encountered during each gesture are shown in Figure \ref{fig:gesturePoses}. \begin{figure} [h] \centering \includegraphics[width=7cm]{images/gesture_poses.png} \caption{Example poses passed through during emotional gestures} \label{fig:gesturePoses} \end{figure} \section{Results} \begin{figure} \centering \includegraphics[width=6.5cm]{images/Trust.png} \caption{Box plot of trust scores} \label{fig:trust} \end{figure} \begin{figure} \centering \includegraphics[width=6.5cm]{images/robotAgreementPlot.png} \caption{Box plot showing percentage of answers agreeing with the robot overall and after the robot made a mistake (means indicated by white squares)} \label{fig:agreeBox} \end{figure} \subsection{RQ1: Trust Recovery} We first calculated Cronbach's alpha for each metric in the trust survey, which gave a high reliability of 0.92. We then calculated the overall trust score by inverting categories when appropriate and then generating the mean for each individual. The mean trust of each group was prosody 0.71, notes 0.57 and gesture 0.62 (see Figure \ref{fig:trust}). After running a one-way ANOVA the p-value was significant, \textit{p}=0.041. Pair-wise t-tests between groups' trust rating gave the results: notes-gestures \textit{p}= 0.46, notes-prosody \textit{p}=0.025, and gesture-prosody \textit{p}=0.025. This supports our hypothesis that trust would be higher from the arm using prosody. We also evaluated trust based on participants' actual use of the system. The percentage of answers for which users agreed with the robot for each group are plotted in Figure \ref{fig:agreeBox}. We performed a one-way ANOVA test to test whether there was a significant difference in this metric between groups, \textit{p}=0.68, which was not significant. To compare trust recovery after mistakes between groups, we analyzed the percentage of times each user agreed with the robot immediately after an instance of following the robot's incorrect suggestion. The results are plotted in Figure \ref{fig:agreeBox}. The one-way ANOVA test yielded \textit{p}=0.87, which was not significant. \subsection{RQ2: Safety, Intelligence and Likeability} \begin{figure} \centering \includegraphics[width=7cm]{images/Metrics.png} \caption{Box plot of HRI metrics} \label{fig:metrics} \end{figure} Cronbach's alpha for Anthropomorphism (0.85), Intelligence (0.89) and Likeability (0.92) all showed high reliability values above 0.85. Safety's coefficient was slightly lower at 0.75. Across each category results showed a higher median for each metric for the system using emotional prosody (see Figure \ref{fig:metrics}), while gestures consistently outperformed notes. We performed a one-way ANOVA on each category, and only Anthropomorphism was significant, \textit{p}=0.006. \subsection{RQ3: Trust Survey and Participant Choices} We calculated the Pearson correlation coefficient between the final trust scores, and the percentage of answers users agreed with the robot. The result was \textit{r}=0.12, which indicates a weak correlation between the two metrics. \subsection{User Comments} The comments provided by participants indicate that it was possible, in all groups, to perceive the emotions the robot was trying to convey. In the prosody group, one user said, `The arm seems quite emotional! When it's right it is quite happy, but when it is wrong it gets particularly sad.' In the notes group, a user said `When we got the right answer the robot seemed cheerful, as opposed to when we selected the wrong answer (based on the robot's recommendation) it seemed as if he was sorry for giving wrong suggestions. If I chose an option different than the robot's suggestion and its answer was correct, it seemed as if he gave the look of I told you the right answer!' And in the gesture group, one comment was `the emotions were very easily perceivable.' Two participants in the notes group had negative comments on the audio response, describing it as `horrible' and `annoying', while one participant in the prosody group said the `humming was annoying.' Several participants mentioned that the robot moved too slowly. Some comments mentioned having a hard time detecting any pattern in the sequence, while in others users discussed their strategies. \section{Discussion and Conclusion} This study was performed using virtual interactions with a robot, and 46 participants. It would be useful to investigate this further with a larger sample size, and to have participants interact with a physical robot for comparison. Additionally, more variations of robot responses could be compared and analyzed beyond the three that we investigated. For example, prosodic audio of a human voice could be compared with that of musical instruments. Our results support that when the robot responded with musical prosody (alongside the gestures present for all groups), users reported higher trust metrics than when the robot responded with single-pitched notes or no audio. This supports that musical prosody has a positive effect on humans' trust of a robot. Comparing the Godspeed metrics, it was unsurprising to find that the addition of human vocalizations increased the Anthropomorphism of the system. We had expected likeability to be higher, and while it was not a significant result, it would still be worth investigating further with more subjects. The most surprising result was that the notes audio fell well below the median of gestures-only in every category. We believe this shows that while prosody can have positive outcomes, audio when implemented ineffectively has the capability to drastically reduce HRI metrics. The reason for this is likely due to the fact that the notes audio was not related to the emotion being displayed by the gesture beyond remaining consistent throughout the experiment. However, it would be interesting to further explore more types of audio responses. Users' ratings of trust in the survey did not strongly correlate with their actual behavior during the task, in terms of how often they agreed with the robot's suggestions. This is consistent with the fact that while users reported significantly higher trust for audio with musical prosody, no significant differences were found in their actual choices during the interactions. A similar conflict between these types of metrics was found in the original decision framework paper \cite{van2013framework}, where higher reported trust in the decision aid did not always result in higher percent agreement with the aid. Some potential explanations include cognitive biases and reliance heuristic. \section{Acknowledgements} This material is based upon work supported by the National Science Foundation under Grant No. 1925178 \bibliographystyle{IEEEtran} \subsection{Robotic Arm Forms of Communication} Amongst research into methods for robotic arms to communicate and signal their intent, there is no standardized set of approaches \cite{cha2018survey}. In social robotics communication is often derived from human behaviour - such as gestures and gaze - these are not however readily available to robotic arms \cite{rosen2019communicating}. Additionally when these forms of communication are added to arms they require significant expense, such as extra visual displays like a face\cite{6839819}, or in the case of added gestures risk challenging and reducing the core functionality of the arm. In robotic research, forms of non-verbal communication can generally be split into four categories kinesics, proxemics, haptics and chronemics, none of which are easily applied to an existing robotic system \cite{saunderson2019robots}. While varying movement to show intent has shown successful results \cite{bodden2016evaluating}, changes to path planning and movement dynamics is often not feasible. Another effective method for arms to display their intent is through vision of a robot's future trajectory, such as by a human worn head mounted display \cite{ruffaldi2016third}, however this requires a significant investment and potential distraction to the user. Emotion has been more commonly used as an input to robotic arms, such as facial emotion recognition to control and change the behaviour of robotic arms \cite{mei2016emotion,iengo2012attentional,ying2016emotion}. Likewise, GSR emotional evaluation on humans has been used to impact a robot's control pattern \cite{takahashi2001human}. Nevertheless, robotic arm displays of emotion in work and collaboration, or interaction beyond showing intent are widely overlooked in robotics literature. \subsection{Communication for Trust and Trust Recovery} For collaboration with robotic arms trust is required, without which they can be underutilized \cite{johndlee}. Trust is largely developed in the first phase of a relationship both between human's and robots \cite{kim2009repair,miles1995organizational}, meaning first impressions are crucial for trust. First impressions from audio and visual stimulus can also damage the ability to develop trust later on \cite{Schaefer2016}. In this work we focus on affective trust, which is developed through emotional bonds and personal relationship, not competence \cite{freedy2007measurement}. Affective trust makes relationships more resilient to mistakes by either party \cite{rousseau1998not}. The display of emotion is critical for affective trust and increases the willingness of collaboration \cite{gompei2018factors}. Music and prosody has been shown as a powerful medium to convey emotions \cite{sloboda1999music}. In music and robotics emotion can be categorized in many ways, such as a discrete categorical manner (happiness, sadness, fear, etc.) \cite{devillers2005challenges}, and through continuous dimensions such as valence, arousal \cite{russell2009emotion}. While some recent efforts to generate and manipulate robotic emotions through prosody focused on linguistic robotic communication \cite{crumpton2016survey}, \cite{breazeal2002recognition}, there has only recently been work focusing on musical prosody \cite{savery_finding_2019,savery2019establishing}. One of the main aims of the presented work concerns recovery of trust, which it assumes a loss of trust. I think the background could be extended by including a deeper discussion concerning trust and sounds, and the communication of errors.
{'timestamp': '2020-09-22T02:02:29', 'yymm': '2009', 'arxiv_id': '2009.09048', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09048'}
arxiv
\section{#1}\vspace{-2ex}} \newcommand{\subsectionsmall}[1]{\subsection{#1}\vspace{-1ex}} \newcommand{\supplementary}{ \clearpage \newpage \setcounter{table}{0} \renewcommand{\thetable}{S\arabic{table}} \setcounter{figure}{0} \renewcommand{\thefigure}{S\arabic{figure}} \setcounter{section}{0} \renewcommand{\thesection}{S\arabic{section}} \onecolumn } \makeatletter \newcommand{\@maketitle}{\@maketitle} \makeatother \newcommand{\mathsf{c}}{\mathsf{c}} \DeclarePairedDelimiterX{\dotp}[2]{\langle}{\rangle}{#1, #2} \newcommand{\ramp}[1]{\left [ #1 \right]_+} \newcommand{\PRIME}[1]{#1^\prime} \newcommand{\dotP}[2]{#1 \cdot #2} \DeclareMathOperator*{\argmin}{\arg\!\min} \DeclareMathOperator*{\argmax}{\arg\!\max} \newcommand{\relu}[1]{\phi(#1)} \makeatletter \newcommand*\bigcdot{\mathpalette\bigcdot@{.5}} \newcommand*\bigcdot@[2]{\mathbin{\vcenter{\hbox{\scalebox{#2}{$\m@th#1\bullet$}}}}} \makeatother \newcommand{\begin{equation}}{\begin{equation}} \newcommand{\end{equation}}{\end{equation}} \newcommand{\frac{1}{2}}{\frac{1}{2}} \newcommand{\stackrel{i.i.d.}{\sim}}{\stackrel{i.i.d.}{\sim}} \newcommand{\normsmall}[1]{\| #1\|} \newcommand{\norm}[1]{\left\lVert#1\right\rVert \newcommand{\br}[1]{\left\{#1\right\}} \newcommand{\qquad \qquad}{\qquad \qquad} \newcommand{\abs}[1] {| #1 |} \newcommand{\hbox{\rlap{$\sqcap$}$\sqcup$}}{\hbox{\rlap{$\sqcap$}$\sqcup$}} \newcommand{\eps}{\ensuremath{\varepsilon}} \renewcommand{\epsilon}{\varepsilon} \newcommand{\texttt{Median}}{\texttt{Median}} \DeclareMathOperator*{\Var}{Var} \newcommand{\Var}{\Var} \DeclarePairedDelimiter{\ceil}{\lceil}{\rceil} \DeclarePairedDelimiter{\floor}{\lfloor}{\rfloor} \newcommand{\inprod}[1]{\left\langle #1 \right\rangle} \newcommand{\mathbin{\stackrel{\rm def}{=}}}{\mathbin{\stackrel{\rm def}{=}}} \DeclareMathOperator*{\rank}{\text{rank}} \DeclareMathOperator*{\sign}{\text{sign}} \declaretheorem[name=Theorem]{theorem} \declaretheorem[name=Corollary, numberlike=theorem]{corollary} \declaretheorem[name=Lemma, numberlike=theorem]{lemma} \declaretheorem[name=Proposition, numberlike=theorem]{proposition} \declaretheorem[name=Definition]{definition} \declaretheorem[name=Assumption]{assumption} \declaretheorem[name=Remark, numberlike=theorem]{Remark} \declaretheorem[name=Claim, numberlike=theorem]{Claim} \declaretheorem[name=Example, numberlike=theorem]{Example} \declaretheorem[name=Observation, numberlike=theorem]{Observation} \newenvironment{itemizeAlg}{\begin{itemize}[topsep=1pt,itemsep=-1ex,partopsep=1ex,parsep=1ex]}{\end{itemize}} \newcommand{\mid \, }{\mid \, } \newcommand{{\mathrm{D}}}{{\mathrm{D}}} \newcommand\supp{\mathrm{supp}(\DD)} \newcommand{\size}[1]{\mathrm{size}({#1})} \newcommand{\nnz}[1]{\mathrm{nnz}(#1)} \newcommand{\ensuremath{\mathbb{R}}}{\ensuremath{\mathbb{R}}} \newcommand{\REAL}{\ensuremath{\mathbb{R}}} \newcommand{\ensuremath{\mathbb{N}}}{\ensuremath{\mathbb{N}}} \DeclareMathOperator*{\E}{\mathbb{E} \,} \let\Pr\relax \DeclareMathOperator*{\Pr}{\mathbf{Pr}} \DeclareMathOperator*{\1}{\mathbf{1}} \newcommand\BigO{\mathcal{O}} \newcommand\Bigo{\BigO} \newcommand\PP{\mathcal{P}} \newcommand\DD{\mathcal{D}} \newcommand\QQ{\mathcal{Q}} \renewcommand\SS{\mathcal{S}} \newcommand\MM{\mathcal{M}} \renewcommand{\AA}{{\mathcal{A}}} \newcommand\LLL{\mathcal{L}} \newcommand\GG{\mathcal{G}} \newcommand\TT{\mathcal{T}} \newcommand\BB{\mathcal{B}} \newcommand\UU{\mathcal{U}} \newcommand{\xmark}{\ding{55}}% \newcommand*{o.o.d.\@\xspace}{o.o.d.\@\xspace} \newtheorem{claim}[theorem]{Claim} \newcommand{C_{size}}{C_{size}} \newcommand{Q_{size}}{Q_{size}} \newcommand{epochs}{epochs} \DeclareMathOperator*{\argmina}{arg\,min} \section{Introduction}\label{sec:introduction}} \IEEEPARstart{C}{oreset} is usually defined as a small weighted subset of the original input set that provably approximates the given loss (objective) function for every query in a given set of queries. Coresets are useful in machine learning applications as they offer significant efficiency improvements. Namely, traditional (possibly inefficient, but provably optimal) algorithms can be applied on coresets to obtain an approximation of the optimal solution on the full dataset using time and memory that are smaller by order of magnitudes. Moreover, existing heuristics that already run fast can be improved in terms of accuracy by running them many times on the coreset in the time it takes for a single run on the original (big) dataset. Finally, coresets can be maintained for a distributed \& streaming data, where the stream is distributed in parallel from a server to $m$ machines (e.g. cloud), and the goal is to maintain the optimal solution (or an approximation to it) for the whole input seen so far in the stream using small update time, memory, and communication to the server. In the recent decade, coresets, under different formal definitions, were applied to many machine learning algorithms e.g. logistic regression~\cite{huggins2016coresets,munteanu2018coresets}, SVM~\cite{har2007maximum,tsang2006generalized,tsang2005core,tsang2005very,tukan2020coresets}, clustering problems~\cite{ feldman2011scalable,gu2012coreset,jubran2020sets,lucic2015strong, schmidt2019fair}, matrix approximation~\cite{feldman2013turning, maalouf2019fast,maalouf2020tight, sarlos2006improved,maalouf2021coresets}, $\ell_z$-regression~\cite{cohen2015lp, dasgupta2009sampling, sohler2011subspace}, decision trees~\cite{jubran2021coresets}, and others; see surveys~\cite{feldman2020core,phillips2016coresets,jubran2019introduction}. Some attempts of using coresets were recently suggested in application to deep networks. Apart from the standard use of coresets for reducing the amount of computations in training, e.g., by replacing full data~\cite{mirzasoleiman-icml-2020} or a batch~\cite{batchSizeReduction} with a coreset, there are other applications that motivate the use of summarization methods in deep networks, e.g., model compression, continual learning, domain adaptation, federated learning, neural architecture search. We discuss some of the them below. \noindent\textbf{Model Compression.} Deep networks are highly over-parametrized, resulting in high memory requirements and slower inference. While many methods have been developed for reducing the size of a previously trained network with no (or small) accuracy loss~\cite{liu2019metapruning,li2019learning,chen2020storage,he2019filter,dong2017more,kang2020operation,ye2020good, ye2018rethinking,maalouf2021deep}, most of them relied on heuristics, which performed well on known benchmarks, but diverged considerably from the behavior of the original network on specific sub-sets of input distribution~\cite{brain_workshop}. Few previous works~\cite{MussayOBZF20,Mussai20a,baykal2018datadependent,Liebenwein2020Provable} tried to resolve this problem by deriving a coreset for a fully connected or a convolutional layer with provable trade-off between the compression rate and the approximation error for any future input. However, since these works construct a coreset for a layer, the full network compression is performed in a layer-by-layer fashion. \noindent\textbf{Limited Data Access.} Problems, such as continual / incremental learning~\cite{LwF,iCarl,Few_shot_reminder,Prototype_reminder,Lopez-PazR17,BorsosM020}, domain adaptation~\cite{LiSWZG17,Asami}, federated learning~\cite{goetz2020federated} do not have access to the full data (due to memory limitation or privacy issues) and only a small summary of it can be used. Coresets offer a natural solution for these problems. \noindent\textbf{NAS.} Another important application that could benefit from coresets is neural architecture search (NAS). Evaluating different architectures or a choice of parameters using a large data set is extremely time consuming. A representative, small summary of the training set could be used for a reliable approximation of the full training, while greatly speeding up the search. Few recent works~\cite{Condensation, GTN} (inspired by the work of~\cite{wang2018dataset}) tried to learn a small synthetic set that summarizes the full set for NAS. Previous attempts of summarizing a full training set with a small subset or a synthetic set showed a merit of using coresets in modern AI (e.g., for training deep network). However, the summarization methods that they suggested were based on heuristics with no guarantees on the approximation error. Hence, it is not clear that existing heuristics for data summarization could scale up to real-life problems. On the other hand, theoretical coresets that provably quantify the trade-off between data reduction and information loss for an objective function of interest, are mostly limited to simple, shallow models due to the challenges discussed below in Section~\ref{subsection:challanges}. From the theoretical perspective, it seems that we cannot have coresets for a reasonable neural network under the classic definition of the worst case query (e.g. see Theorem 6~\cite{MussayOBZF20}). In this paper we try to find a midway between these two paradigms. \subsection{Coreset challenges}\label{subsection:challanges} In many modern machine learning problems, obtaining non-trivial theoretical worst-case guarantees is usually impossible (due to a high complexity of the target model, e.g. deep networks or since every point in the input set is important in the sense of high sensitivity~\cite{tukan2020coresets2}). Even for the simple problems, it may take years to design a coreset and prove its correctness for a specific problem at hand. Another problem with the existing theoretical frameworks is the lack of generality. Even the most generic frameworks among them~\cite{feldman2011unified, langberg2010universal} replace the problem of computing a coreset for $n$ points with $n$ new optimization problems (known as sensitivity bound), one for each of the $n$ input points. Solving these, however, might be harder than solving the original problem. Hence, different approximation techniques are usually tailored for each and every problem. \subsection{Our Contribution} The above observations suggest that there is a need in a more generic approach that can compute a coreset automatically for a given pair of dataset and loss function, and can be applied to hard problems, such as deep networks. It seems that this would require some relaxation in the standard coreset definition. Would such a relaxed coreset produced by a generic algorithm yield comparable empirical results with the traditional coresets that have provable guarantees? We affirmably answer this question by providing: \begin{enumerate}[(i)] \item A new definition of a coreset, which is a relaxation of the traditional definition of the strong coreset. \item AutoCL: a generic and simple algorithm that is designed to compute a coreset (under the new definition) for almost any given input dataset and loss function. \item Example applications with highly competitive empirical results for: (a) problems with known coreset construction algorithms, namely, linear regression and logistic regression, where the goal is to summarize the input training set, and (b) model compression, i.e., learning a coreset of all training parameters of a deep neural network at once (useful for model pruning). To our knowledge, this is the first algorithm that aims to compute a coreset for the network at once, and not layer by layer or similar divide-and-conquer methods. It is also the first approach that suggests to represent the coreset itself as a small (trainable) network that keeps improving on each iteration. In this sense we suggest "coreset for deep learning using deep learning". \item Open code for reproducing our results~\cite{opencode}. We expect that it would be the baseline for producing ``empirical" coresets for many problems in the future. Mainly, since it requires very little familiarity with the existing theoretical research on coresets. \end{enumerate} \section{Preliminaries} \textbf{Notations.} For a set $P$ of $n$ items, we use $\abs{P}$ to denote the number of items in $P$ (i.e., $\abs{P}=n$). For an event $B$ we use $\Pr(B)$ as the probability that event $B$ occurs, and for a random variable $x$ with a probability measure $\mu$, we use $\mathbb{E}_{\mu}(x)$ to denote its mean (expected value). Finally, for a loss function $\mathrm{loss}$ and an input set of variables $C$ (from any form), we use $\nabla \mathrm{loss}(C)$ to denote a standard gradient computation of $\mathrm{loss}$ with respect to the set of variables $C$, and $C- \alpha\nabla \mathrm{loss}(C)$ to denote a standard variables update ($C$) using a gradient step, where $\alpha>0$ is the learning rate. The following (generic) definition of a query space encapsulates all the ingredients required to formally define an optimization problem. \begin{definition} [Query space; see Definition 4.2 in~\cite{braverman2016new}] \label{def:querySpace} Let $\mathbb{P}$ be a (possibly infinite) set called \emph{ground set}, $Q'$ be a (possibly infinite) set called \emph{query set}, and let $f:\mathbb{P}\times Q' \to [0,\infty)$ be a loss (or cost) function. Let $P\subseteq \mathbb{P}$ be a finite set called \emph{input set}, and let $w:P\to [0,\infty)$ be a \emph{weight function}. The tuple $(P,w,Q',f)$ is called a \emph{query space} over $\mathbb{P}$. \end{definition} Typically, in the training step (of machine learning model), we solve the optimization problem, i.e., we aim at finding the solution $q^*$ that minimizes the sum of fitting errors $\sum_{p\in P} w(p) f(p,q)$ over every $q\in Q'$. \begin{definition} [Query cost] \label{def:onequerycost} Let $(P,w,Q',f)$ be a query space over $\mathbb{P}$. Then, for a query $q\in Q'$ we define the total cost of $q$ as $f(P,w,q) = \sum_{p\in P} w(p)f(p,q).$ \end{definition} In the next definition, we describe formally a (strong) coreset for a given optimization problem. \begin{definition}[Traditional Coresets]\label{def:strongCoreset} For a query space $(P,w,Q',f)$, and an error parameter $\eps\in (0,1)$, an $\eps$-coreset is a pair $(C,u)$ such that $C\subseteq P$, $u:C\to \ensuremath{\mathbb{R}}$ is a weight function, and for every $q\in Q'$, $f(C,u,q)$ is a $1\pm\eps$ multiplicative approximation for $f(P,w,q)$, i.e., \begin{equation} \abs{f(P,w,q) - f(C,u,q)} \leq \eps f(P,w,q). \label{eq:traditional-coreset} \end{equation} \end{definition} \section{Method} In this section we first explain our approach in general, emphasising its novelty and then, we present our suggested framework including all the details. \subsection{Novel Framework} We propose a \emph{practical} and \emph{generic} framework for coreset construction to a wide family of problems via the following steps: \begin{enumerate}[(a)] \item \emph{Make a problem simpler by relaxing the definition of a coreset.}\label{framework:1} Namely, we propose a new $(\eps,\mu)$-coreset for the Average Loss (in Definition~\ref{def:aca}) that is a relaxation of the standard definition (in Definition~\ref{def:strongCoreset}), and is more suited for the learning formalism. \item \emph{Define coreset construction as a learning problem}. Here, the coreset (under the new definition in Definition~\ref{def:aca}) is the training variable. \label{framework:2} \item \emph{Find the coreset that optimizes the empirical risk over a training set of queries.} \label{framework:3} We assume that we are given a set of queries, chosen i.i.d. from an unknown distribution and we find a coreset that approximates the average loss of the original input data over the training set of queries. \item \emph{Show that the optimized coreset generalizes to all members in the query set.} \label{framework:4} Namely, the expected loss on the coreset over all queries approximates the expected loss on the original input data. \end{enumerate} \subsection {$(\eps,\mu)$-Coreset for the Average Loss} We relax the definition of a coreset by observing that in data mining and machine learning problems we are usually interested in approximating the average loss over the whole set of queries rather than approximating the loss of a specific query. To this end, we define a distribution over the set of queries in Definition~\ref{def:prob-querySpace}, and then focus on approximating the expected loss in Definition~\ref{def:aca}. \begin{definition} [Measurable query space] \label{def:prob-querySpace} Let $(P,w,Q',f)$ be a query space over the ground set $\mathbb{P}$, and let $\mu$ be a probability measure on a Probability space $(Q',2^{Q'})$. Then, the tuple $(P,w,Q',f,\mu)$ is called a measurable query space over $\mathbb{P}$. \end{definition} \begin{definition} [$(\eps,\mu)$-coreset for the Average Loss]\label{def:aca} Let $(P,w ,Q',f,\mu)$ be a measurable query space over $\mathbb{P}$. Let $\eps \in [0,\infty)$ be an error parameter, $C\subset \mathbb{P}$ be a set, and $u:C\to\ensuremath{\mathbb{R}}$ be a weight function such that: $$\abs{\mathbb{E}_\mu(f(P,w,q)) - \mathbb{E}_\mu (f(C,u,q))} \leq\eps,$$ i.e., the expected loss of the original set $P$ over the randomness of sampling a query $q$ from the distribution $\mu$ is approximated by the expected loss on $C$. Then, the pair $(C,u)$ is called an $(\eps,\mu)$-coreset for the measurable query space $(P,w,Q',f,\mu)$. \end{definition} While, $(P,w)$ is also an $(\eps,\mu)$-coreset of $(P,w,Q',f,\mu)$, coreset $(C,u)$ is efficient if the cardinality of $C$ is significantly smaller than $P$, i.e., $|C|\ll|P|$, hopefully by order of magnitude. \textbf{Remark:} Throughout the literature, the term ``coreset'' usually refers to a small weighted \textbf{subset} of the input set (data). However, in other works (and in ours), this requirement is relaxed~\cite{cohen2015dimensionality,phillips2016coresets}. In many applications this relaxation gives a significant benefit as it supports a much larger family of instances as coreset candidates. \subsection{Coreset Learning}\label{sec:coreset-learning} \newcommand{\textsc{AutoCL}}{\textsc{AutoCL}} \begin{algorithm}[b] \small \caption{$\textsc{AutoCL}(P,w,Q,f,C_{size})$} \label{alg:main-new} \textbf{Input:} {A finite input set $P$, and its weight function $w:P\to \ensuremath{\mathbb{R}}$, a finite set of queries $Q$, a loss function $f:P \times Q\to [0,\infty)$, and an integer $C_{size}\geq1$.} \begin{spacing}{1.1} \begin{algorithmic}[1] \small \STATE $C:=\br{c_i}_{i=1}^{C_{size}}$ is an arbitrary set of $C_{size}$ vectors in $\mathbb{P}$.\label{line:initc-new}\\ \STATE $u(c):=1/C_{size}$ for every $c\in C$.\label{line:initu-new}\\ \FOR{$i:= 1 \to epochs$} \label{lin:opt_start} \STATE $f_C:= \frac{1}{k}\sum_{q\in Q}f(C,u,q)$ \label{line:cerror-new} \COMMENT{The average loss on $C$.} \\ \STATE $f_P:= \frac{1}{k}\sum_{q\in Q}f(P,w,q)$\label{line:perror-new} \COMMENT{The average loss on $P$.} \STATE $\mathrm{loss}:= \abs{f_P - f_C} + \lambda \abs{\sum_{p\in P}w(p) - \sum_{p\in C}u(p)}$\label{line:apperror-new} \\ \COMMENT{The approximation error that we wish to minimize, $\lambda>0$ is a hyper-parameter to balance the two losses.} \STATE $C:= C - \alpha \nabla \mathrm{loss}(C)$\label{line:updatec-new} \\ \COMMENT{Update $C$, where $\alpha>0$ is the learning rate.}\\ \STATE $u:= \max\{0,u - \alpha \nabla loss(u)\}$ \label{line:updateu-new}\COMMENT{Update $u$.} \ENDFOR \label{lin:opt_end} \STATE \textbf{return} $(C,u)$ \end{algorithmic} \end{spacing} \end{algorithm} We propose to learn a coreset (and its weights) as in Definition~\ref{def:aca} using gradient-based methods. We assume that we are given a set $P$, its weights $w$ such that $\sum_{p\in P} w(p) =1$,\footnote{We use this assumption for simplicity of the writing. Practically, we can implement it by scaling the input weights to sum to $1$, and formally, all is needed is scaling the sample size of the queries according to the sum of weights.} and a set $Q$ of $|Q|=k$ queries sampled i.i.d. from $Q'$ (according to the measure $\mu$). First, we aim to compute an $(\eps,\mu)$-coreset $(C,u)$ of $(P,w)$ with respect to the finite set of queries $Q$. Formally speaking, $(C,u)$ should satisfy: \begin{align} \left|\sum_{q\in Q}\frac{1}{k}f(P,w,q)-\sum_{q\in Q}\frac{1}{k}f(C,u,q)\right| \leq \eps. \label{ALG:guarantee} \end{align} To do so, we can treat $Q$ as our training data and learn coreset $(C,u)$ of $(P,w)$ with respect to the objective $f$ by minimizing the following loss: $$\left|{\frac{1}{k}\sum_{q\in Q}f(P,w,q)-\frac{1}{k}\sum_{q\in Q}f(C,u,q)}\right|.$$ This will guarantee that $(C,u)$ is an $(\eps,\mu)$-coreset for the measurable query space $(P,w,Q,f,\pazocal{U})$, where $\pazocal{U}:Q\to [0,1]$ is the uniform distribution over the finite set $Q$, i.e., $\pazocal{U}(q)=1/k=1/|Q|$ for every $q\in Q$. However, we wish that the constraint in Eq.~\eqref{ALG:guarantee} would hold for the whole set of queries $Q'$ in order to obtain an $(\eps,\mu)$-coreset for our desired (original) measurable query space $(P,w,Q',f,\mu)$. \begin{comment} To understand which modifications should be done to the loss function in order to obtain a generalized solution, we first state the sufficient guarantees for the $(\eps,\mu)$-coreset: \begin{enumerate}[(i)] \item \label{firststep} With high probability, the expected loss on the set $P$ over all queries in $Q'$ (i.e., $\mathbb{E}_\mu(f(P,w,q))$) is approximated by the average loss on the same set $P$ over the sampled set $Q$ of $k$ queries, i.e., with high probability $$\abs{\frac{1}{k}\sum_{q\in Q} f(P,w,q) - \mathbb{E}_\mu (f(P,w,q))}\leq \eps$$ \item \label{secondstep} The same should hold for $(C,w)$, i.e., with high probability $$\abs{\frac{1}{k}\sum_{q\in Q} f(C,u,q) - \mathbb{E}_\mu (f(C,u,q))}\leq \eps.$$ \end{enumerate} Finally, by Eq.~\eqref{ALG:guarantee} we have that $\frac{1}{k}\sum_{q\in Q} f(C,u,q)$ approximates $\frac{1}{k}\sum_{q\in Q} f(P,w,q)$, hence combining~\ref{firststep} and~\ref{secondstep} with Eq.~\eqref{ALG:guarantee}, yields that $\mathbb{E}_\mu (f(C,u,q))$ approximates $\mathbb{E}_\mu (f(P,w,q))$. For~\ref{firststep} to hold, we can rely on Hoeffding's inequality, which informally states that, with high probability, the average loss on the set $P$ over the i.i.d sampled set $Q$ of $k$ queries approximates the expected loss on the set $P$ over all queries in $Q'$ (i.e., $\mathbb{E}_\mu(f(P,w,q))$). However, the size $k$ of $Q$ should be large enough and proportional to the approximation error $\eps$, the probability of failure $\delta$, and finally, the maximum loss over every $q\in Q'$, i.e., $\sup_{q\in Q'}{f(P,w,q)}$ (see Claim~\ref{hofff}). Now, recall that $\mathbb{P}$ is the ground set, i.e., $P,C \subset \mathbb{P}$, and let $M=\sup_{q\in Q',p\in \mathbb{P}}\abs{f(p,q)}$. Since, $\eps$ and $\delta$ are fixed, and since $\sup_{q\in Q'}{f(P,w,q)} = \sup_{q\in Q'}{\sum_{p\in P}w(p)f(p,q)} \leq \sum_{p\in P}w(p)M =M$, all is needed for~\ref{firststep} to hold, is to sample enough queries (based on the Hoeffding's inequality). Now, for~\ref{secondstep} to hold, we can also use the Hoeffding's inequality. Also here, we have that $\eps$ and $\delta$ are fixed, but what about $\sup_{q\in Q'}{f(C,u,q)}$? \end{comment} To obtain a generalized solution (as we show in Section~\ref{sec:generalization}), we need to bound $\sup_{q\in Q'}{f(C,u,q)}$. To do so, we should guarantee that the sum of coreset weights approximates the original sum of weights, i.e: \begin{align} \abs{\sum_{p\in P}w(p) - \sum_{p\in C}u(p)} \leq \eps. \label{ALG:guarantee2} \end{align} The motivation behind bounding Eq~\eqref{ALG:guarantee2} is as follows. Recall that $\mathbb{P}$ is the ground set, i.e., $P,C \subset \mathbb{P}$. Let $M=\sup_{q\in Q',p\in \mathbb{P}}\abs{f(p,q)}$, so that enforcing Eq.~\eqref{ALG:guarantee2}, yields for every $q\in Q'$ $$f(C,u,q) \leq \sum_{p\in C}u(p)f(p,q) \leq (\sum_{p \in P}w(p)+\eps)M= (1+\eps)M.$$ Hence, we ``force'' our coreset to have a bounded loss over the whole query space $\sup_{q\in Q'}f(C,u,q) \leq (1+\eps)M$, furthermore, this bound is proportional to the bound of the loss on the original input $P$, i.e, it is proportional to $$\sup_{q\in Q'}f(P,w,q)\leq \sum_{p\in P} w(p) M =M,$$ and the approximation error $\eps$. To summarize, we learn an $(\eps,\mu)$-coreset $(C,u)$ of $(P,w)$ with respect to the objective $f$ given a training data (set of queries) $Q$. To enforce the conditions in Eqs.~\eqref{ALG:guarantee} and~\eqref{ALG:guarantee2} to hold with small $\eps$, we minimize the following loss: \begin{equation} \begin{split} \mathrm{loss}(Q;C,u)&:=\left|\frac{1}{k}\sum_{q\in Q}f(P,w,q)-\frac{1}{k}\sum_{q\in Q}f(C,u,q)\right| \\ &\quad + \lambda \left|{\sum_{p\in P}w(p) - \sum_{p\in C}u(p)}\right|. \label{alg:loss} \end{split} \end{equation} Here, $\lambda>0$ is a hyper-parameter to balance the two losses. The algorithm for coreset learning is summarised in Algorithm~\ref{alg:main-new}. \subsection{Generalization} \label{sec:generalization} We start by stating the sufficient guarantees for the $(\eps,\mu)$-coreset (i.e., the sufficient guarantees to obtain a generalized solution): \begin{enumerate}[(i)] \item \label{firststep} With high probability, the expected loss on the set $P$ over all queries in $Q'$ (i.e., $\mathbb{E}_\mu(f(P,w,q))$) is approximated by the average loss on the same set $P$ over the sampled set $Q$ of $k$ queries, i.e., with high probability $$\abs{\frac{1}{k}\sum_{q\in Q} f(P,w,q) - \mathbb{E}_\mu (f(P,w,q))}\leq \eps.$$ \item \label{secondstep} The same should hold for $(C,u)$, i.e., with high probability $$\abs{\frac{1}{k}\sum_{q\in Q} f(C,u,q) - \mathbb{E}_\mu (f(C,u,q))}\leq \eps.$$ \end{enumerate} Then, by Eq.~\eqref{ALG:guarantee}, we have that $\frac{1}{k}\sum_{q\in Q} f(C,u,q)$ approximates $\frac{1}{k}\sum_{q\in Q} f(P,w,q)$, hence combining~\ref{firststep} and~\ref{secondstep} with Eq.~\eqref{ALG:guarantee}, yields that $\mathbb{E}_\mu (f(C,u,q))$ approximates $\mathbb{E}_\mu (f(P,w,q))$. To show that~\ref{firststep} holds, we rely on Hoeffding's inequality as follows. \begin{claim}[Mean of Losses] \label{hofff Let $(P,w,Q',f,\mu)$ be a measurable query space such that $\sum_{p\in P}w(p)=1$, and let $M=\sup_{q\in Q'}\abs{f(P,w,q)}$. Let $\eps \in (0,\infty)$ be an approximation error, and let $\delta \in (0,1)$ be a probability of failure. Let $Q$ be a sample of $k\geq \frac{2M^2\ln(2/\delta)}{\eps^2} $ queries from $Q'$, chosen i.i.d, where each $q\in Q'$ is sampled with probability $\mu(q)$. Then, with probability at least $1-\delta$, $$\abs{\frac{1}{k}\sum_{q\in Q} f(P,w,q) - \mathbb{E}_\mu (f(P,w,q))} \leq \eps .$$ \end{claim} This claim states that, with high probability, the average loss on the set $P$ over the i.i.d sampled set $Q$ of $k$ queries approximates the expected loss on the set $P$ over all queries in $Q'$ (i.e., $\mathbb{E}_\mu(f(P,w,q))$). However, the size $k$ of $Q$ should be large enough and proportional to the approximation error $\eps$, the probability of failure $\delta$, and finally, the maximum loss over every $q\in Q'$, i.e., $\sup_{q\in Q'}{f(P,w,q)}$ (see Claim~\ref{hofff}). Now, recall that $\mathbb{P}$ is the ground set, i.e., $P,C \subset \mathbb{P}$, and $M=\sup_{q\in Q',p\in \mathbb{P}}\abs{f(p,q)}$. As we formally show in Section~\ref{ProofofClaim1}, since, $\eps$ and $\delta$ are fixed, and since $\sup_{q\in Q'}{f(P,w,q)} = \sup_{q\in Q'}{\sum_{p\in P}w(p)f(p,q)} \leq \sum_{p\in P}w(p)M =M$, all is needed for Claim~\ref{hofff} to hold, is to sample enough queries (based on the Hoeffding's inequality). To show that~\ref{secondstep} holds, we can also use the Hoeffding's inequality, but additionally we need to bound $\sup_{q\in Q}f(C,u,q)$. This was the reason for adding the constraint on the sum of weights: $\abs{\sum_{p\in P}w(p) - \sum_{p\in C}u(p)}\leq \eps ,$ to obtain $\sup_{q\in Q}f(C,u,q)\leq (1+\eps)M$. Formally, \newcommand{ALG}{ALG} \begin{claim}\label{main:theroem} Let $(P,w,Q',f,\mu)$ be a measurable query space over $\mathbb{P}$, where $\sum_{p\in P}w(p)=1$, and let $M=\sup_{q\in Q',p\in \mathbb{P}}\abs{f(p,q)}$. Let $\eps\in (0,\infty)$ be an approximation error, $\delta \in (0,1)$ be a probability of failure, and let $C_{size} \geq 1$ be an integer. Let $Q$ be a sample of $k \geq \frac{2((1+\eps)M)^2\ln(2/\delta)}{\eps^2}$ queries from $Q'$, chosen i.i.d, where each $q\in Q'$ is sampled with probability $\mu(q)$. Let $(C,u)$ be the output of a call to $\textsc{AutoCL}(P,w,Q, f,C_{size})$; see Algorithm~\ref{alg:main-new}. If \begin{enumerate} \item $\abs{\sum_{p\in P}w(p) - \sum_{p\in C}u(p)}\leq \eps ,$ and\label{assump1} \item $\abs{\frac{1}{k}\sum_{q\in Q} f(P,w,q) - \frac{1}{k}\sum_{q\in Q} f(C,u,q)} \leq \eps.$ \label{assump} \end{enumerate} Then, we obtain that, with probability at least $1-\delta$, $$\abs{\mathbb{E}_\mu (f(P,w,q)) - \mathbb{E}_\mu (f(C,u,q))} < 3\eps.$$ \end{claim} \begin{proof} See proof in Section~\ref{ProofofClaim2} in the appendix. \end{proof} \subsection{Bridging the Gap Between Theory and Practice} We take one more step towards deriving effective, practical coresets and replace the loss in Eq.~\ref{alg:loss} (and Line~\ref{line:apperror-new} in Algorithm~\ref{alg:main-new}) with a formulation that is more similar to the standard coreset definition, namely, $loss(q;C,u)=\abs{1 - \frac{ f(C,u,q)}{f(P,w,q)}} + \lambda \abs{\sum_{p\in P}w(p) - \sum_{p\in C} u(p)}$ and we minimize this loss on average over the training set of queries $Q$; See Algorithm~\ref{alg:main} in the appendix. A solution obtained by Algorithm~\ref{alg:main} aims to minimize the average approximation error over every query $q$ in the sampled set $Q$ and thus is very similar to the Definition~\ref{def:strongCoreset} with the modification of average instead of the worst case. This enables us to obtain a better coreset in practice that approximates the loss of every query $q$ (as the minimization is on the average approximation error over all queries and not only on the difference between the average losses of the coreset and the original data over all queries). Our empirical evaluation in Section~\ref{sec:exp} verifies that the coreset obtained by running Algorithm~\ref{alg:main} generalizes to unseen queries, i.e., the average approximation error of the coreset over all queries is small compared to other coreset construction algorithms. Moreover, we show below that the solution obtained by Algorithm~\ref{alg:main} satisfies Definition~\ref{def:aca}. Let $(C^*,u^*)$ be a solution that minimizes the average loss in Algorithm~\ref{alg:main}. We can find a constant $\eps'>0$, such that \begin{align} \frac{1}{k}\sum_{q\in Q} \abs{1-\frac{f(C^*,u^*,q)}{f(P,w,q)}}\leq \eps'. \label{ALG:guarantee_new} \end{align} For a constant $\eps$ from Definition~\ref{def:aca}, let $M=\sup_{q\in Q}|f(P,w,q)|$, and let $\eps = \eps'M $. By simple derivations (see Section~\ref{proofeq5} in the appendix) we can show that \begin{equation} \label{eq:M} \begin{split} &\abs{\frac{1}{k}\sum_{q\in Q}f(P,w,q)-\frac{1}{k}\sum_{q\in Q} f(C^*,u^*,q)} \leq \eps. \end{split} \end{equation} Hence by Claim~\ref{main:theroem} the solution obtained by Algorithm~\ref{alg:main} generalizes to the whole measurable query space $(P,w,Q',f,\mu)$ and thus it satisfies the definition of $(\eps,\mu)$-coreset, while simultaneously satisfying Eq.~\eqref{ALG:guarantee_new} which is closely related to the original definition of coresets as in Definition~\ref{def:strongCoreset}. \section{Experimental Results}\label{sec:exp} We proposed a unified framework for coreset construction that allows us to use the same algorithm for different problems. We demonstrate this on the examples of training set reduction for linear and logistic regression in Section~\ref{sec:exp_data_reduction} and on the examples of model size reduction a.k.a. model compression of MLP and CNN in Section~\ref{sec:exp_model_compr}. We show that in both cases our unified framework yields comparable or even better results than previous coresets, which are specifically fitted to the problem at hand. \begin{figure*} \centering \includegraphics[width=0.3\textwidth,height=0.2\textwidth]{images3/linear_weak_new.png} \includegraphics[width=0.48\textwidth,height=0.2\textwidth]{images3/linear_strong_mean_mean_with_arrow_new.png} \caption{\small Linear regression: a -- Approximation error for the optimal solution as a function of the coreset's size; b -- average approximation error on the unseen test data as a function of the coreset's size.} \label{fig:linearresst} \end{figure*} \begin{figure*} \centering \includegraphics[width=0.3\textwidth,height=0.2\textwidth]{images3/logistic_weak.png} \includegraphics[width=0.48\textwidth,height=0.2\textwidth]{images3/logistic_strong_mean_mean.png} \caption{\small Logistic regression: a -- Approximation error for the optimal solution as a function of the coreset's size; b -- average approximation error on the unseen test data as a function of the coreset's size.} \label{fig:logisticresst} \end{figure*} \subsection{Training Data Coresets}\label{sec:exp_data_reduction} We demonstrate the practical strength of our coreset construction scheme in the context of data reduction for linear and logistic regression. \subsubsection{Setup} For linear regression, we ran our experiments on the 3D Road Networks dataset\footnote{\url{https://archive.ics.uci.edu/ml/datasets/3D+Road+Network+(North+Jutland,+Denmark)}} (North Jutland, Denmark)~\cite{kaul2013building} that contains 434,874 records. We used two attributes: ``Longitude'' [Double] and ``Latitude'' [Double] to predict the third attribute ``Height in meters'' [Double]. We created a set of queries by sampling models from training trajectories of linear regression computed using the full data set from 20 random starting points. We split the sampled models into training, validation and tests sets of sizes 20,000 ($|Q|$=20,000), 2,000, 2,000 correspondingly. We computed weighted coresets of different sizes, from 50 to 140. For each coreset size, we invoked Algorithm~\ref{alg:main} with Adam optimizer~\cite{kingma2014adam} for 10 epochs with a batch size of 25 and learning rate of 0.01. The results were averaged across $10$ trials. In this experiments we used $\lambda = 1$. For the logistic regression we performed the experiments on HTRU~\footnote{\url{https://archive.ics.uci.edu/ml/datasets/HTRU2}} dataset, comprising 17,898 radio emissions of the pulsar star represented by 8 features and a binary label~\cite{lyon2016fifty}. We created a set of queries similarly to linear regression and we sampled from this set training, validation and test sets of sizes 8,000, 1,600, 800 correspondingly. The results were averaged across $5$ trials. To make the optimization simpler, we removed the weight fitting term from the loss in Algorithm~\ref{alg:main} and assumed that all members of the coreset have the same weight $1/|C|$. We ran the optimization for $1000$ epochs with the batch size of $100$ using Adam optimizer and learning rate of $0.001$. Using this modification, we computed coresets of different sizes randing from 100 to 500. The differences in hyper-parameters and the coreset sizes between the logistic and linear regression experiments are due to the higher complexity of the problem for logistic regression. First, computing a coreset for logistic regression is known to be a complex problem where (high) lower bounds on the coreset size exists~\cite{munteanu2018coresets}. The second (and probably less significant) reason is the dimension of the input data, where we used a higher dimensional input in logistic regression. \subsubsection{Results} We refer to a weighted labeled input dataset by $(P,w,b)$, where $P$ is the dataset, $b:P\to \ensuremath{\mathbb{R}}$ and $w:P\to[0,\infty)$ are the labeling function and weight function respectively, i.e., each point $p$ in $P$ is a sample in the dataset, $b(p)$ is its corresponding label and, $w(p)$ is its weight. Similarly, we refer to the compressed labeled data set (coreset) by $(C,u,y)$. We report the results using two measures as explained below. \begin{enumerate} \item \textbf{Approximation error for the optimal solution.} Let $q^*$ be the query that minimizes the corresponding objective loss function, e.g., in linear regression: $q^*\in \argmina_{q\in \ensuremath{\mathbb{R}}^{d}} f(P,w,b,q)$, where $f(P,w,b,q) = \sum_{p\in P}w(p)({p^Tq-b(p)})^2$. For each coreset $(C,u,y)$, we compute $q^*_{c}\in \argmina_{q\in \ensuremath{\mathbb{R}}^{d}} f(C,u,y,q)$, then we calculate the approximation error for the optimal solution as $Err_{opt}=\abs{1-\frac{f(P,w,b,q^*_{c})}{f(P,w,b,q^*)}}.$ \item \textbf{Average approximation error.} For every coreset $(C,u,y)$, we report the average case approximation error over every query $q$ in the test set $Q_{test}$, i.e., $Err_{avg}=\frac{1}{|Q_{test}|}\sum_{q\in Q_{test} }\abs{1-\frac{f(C,u,y,q)}{f(P,w,b,q)}}.$ \end{enumerate} We compare our coresets for linear regression with uniform sampling and with the coreset from~\cite{maalouf2020tight}; $Err_{opt}$ of the three methods is shown in Figure~\ref{fig:linearresst}(a) and $Err_{avg}$ in Figure~\ref{fig:linearresst}(b). We compare our coreset for logistic regression with uniform sampling and with the coreset from~\cite{tukan2020coresets}; $Err_{opt}$ of the compared methods is shown in Figure~\ref{fig:logisticresst}(a) and $Err_{avg}$ in Figure~\ref{fig:logisticresst}(b). In both experiments we observe that our learned coresets outperform the uniform sampling, and the theoretical counterparts. Our method yields very low average approximation error, because it was explicitly trained to derive a coreset that minimizes the average approximation error on the training set of queries, and the learned coreset succeeded to generalize to unseen queries. \subsection{Model Coreset for Structured Pruning}\label{sec:exp_model_compr} The goal of model compression is reducing the run time and the memory requirements during inference with no or little accuracy loss compared to the original model. Structured pruning reduces the size of a large trained deep network by reducing the width of the layers (pruning neurons in fully-connected layers and filters in convolutional layers). An alternative approach is sparsification, which zeros out unimportant parameters in a deep network. The main drawback of sparsification is that it leads to an irregular network structure, which needs a special treatment to deal with sparse representations, making it hard to achieve actual computational savings. Structured pruning simply reduces the size of the tensors, which allows running the resulting network without any amendment. Due to the advantage of structured pruning over sparsification, we perform structured pruning of a deep networks in our experiments. We assume that the target small architecture is given, and our task is to compute the training parameters of the small architecture that best approximate the original large network. We view filters in CNN or neurons in a fully connected network as items in the full set $P$, and the training data as the query set $Q$. We use the small architecture to define the coreset size in each layer and we learn an equally weighted coreset $C$ (the small network) using Algorithm~\ref{alg:main} and setting $\lambda=0$. We report the experiments for structured pruning of a fully connected network in Section~\ref{subsec:neuralpruning} and of channel pruning in Section~\ref{subsec:chanpruning}. \subsubsection{Neuron Pruning}\label{subsec:neuralpruning} \textbf{Setup.} We used LeNet-$300$-$100$ model with 266,610 parameters trained on MNIST~\cite{lecun1998gradient} as our baseline fully-connected model. It comprises two fully connected hidden layers with $300$ and $100$ neurons correspondingly, each followed with a ReLu activation. After training the baseline model with Adam optimizer for $40$ epochs and batch size of $64$, it achieved test accuracy of $97.93\%$ and loss = $0.0917$. The target small architecture included $30$ neurons in the first layer and $100$ in the second, resulting in $89.63\%$ compression ratio. We applied the training procedure in Algorithm~\ref{alg:main} to learn the weights of this network using Adam optimizer with $L_2$ regularization for $400$ epochs with the batch size of $500$. \noindent\textbf{Results.} The coreset (compressed) model achieved $97.97\%$ accuracy and $0.0911$ loss on the test data, i.e., improvement in both terms. Next, we compare our results to a pair of other coreset-based compression methods in Table~\ref{table:comparison-lenet}, and to non-coreset methods: Filter Thresholding (FT)~\cite{li2016pruning}, SoftNet~\cite{he2018soft}, and ThiNet~\cite{luo2017thinet} implemented in~\cite{Liebenwein2020Provable}. We observe that the learned coreset performs better than most compared methods and comparably to the algorithm derived from the theoretical coreset framework. Note that previous coreset methods~\cite{MussayOBZF20,Liebenwein2020Provable} are designed for a single layer, while our algorithm does not have this limitation and can be applied to compress all layers of the network in a single run. Moreover applied to DNN compression, our framework can work on individual weights (sparcification), neurons (as shown above) and channels (as we show next). \subsubsection{Channel Pruning}\label{subsec:chanpruning} \textbf{Setup.} We used Pytorch implementation of VGGNet-19 network \footnote{\href{https://github.com/Eric-mingjie/network-slimming/blob/master/models/vgg.py}{VGG-code-link}} for CIFAR10 from~\cite{liu2017learning} with about 20M parameters as our baseline CNN model (see Table~\ref{table:vggarch} for more details). The baseline accuracy and loss in our experiments was $93.25\%$ and $0.3387$ correspondingly. The target architecture\footnote{https://github.com/foolwood/pytorch-slimming} of the small network (see Table~\ref{table:vggarch}) corresponds to 70\% compression ratio and to the reduction of the parameters by roughly 88\%. We ran Algrothm~\ref{alg:main} using the small architecture to define the size of each layer for $180$ epochs with batch size of $500$ using Adam optimizer and $L_2$ regularization. \noindent\textbf{Results.} Our compressed model improved the baseline network and achieved $93.51\%$ accuracy and $0.32$ loss. Table~\ref{table:comparison-vgg} compares the small network accuracy of the learned coreset with the channel pruning coreset from~\cite{Mussai20a} and several non-coreset methods. While the results are comparable, our algorithm is much simpler and is not tailored to the problem at hand. The coreset reported in~\cite{Mussai20a} was constructed by applying a channel pruning coreset in a layer by layer fashion, while our learned coreset is computed in one-shot for the entire network. Finally, we remind the reader that our framework is generic and could be applied to many other applications in addition to compressing DNNs. \begin{table}[!h] \begin{center} \begin{tabular}{| c || c | c |} \hline Layer & {Width (original)} & {Width (compressed)} \\ \hline \hline 1 & 64 & 49 \\ \hline 2 & 64 & 64 \\ \hline 3 & 128 & 128\\ \hline 4 & 128 & 128\\ \hline 5 & 256 & 256\\ \hline 6 & 256 & 254\\ \hline 7 & 256 & 234\\ \hline 8 & 256 & 198\\ \hline 9 & 512 & 114 \\ \hline 10 & 512 & 41\\ \hline 11 & 512 & 24\\ \hline 12 & 512 & 11\\ \hline 13 & 512 & 14\\ \hline 14 & 512 & 13\\ \hline 15 & 512 & 19\\ \hline 16 & 512 & 104\\ \hline \end{tabular} \end{center} \caption{VGG-19 original and compressed architectures.} \label{table:vggarch} \end{table} \begin{table}[!h] \centering \begin{adjustbox}{width=1\columnwidth} \begin{tabular}{|l|ccc|} \hline Pruning Method & Baseline & Small Model& Compression \\ & Error(\%)&Error(\%)&Ratio \\\hline \hline FT\cite{li2016pruning} & 1.59 & +0.35 & 81.68\%\\ \hline SoftNet~\cite{he2018soft}& 1.59& +0.41& 81.69\% \\ \hline ThiNet~\cite{luo2017thinet}&1.59& +10.58& 75.01\% \\ \hline Sample-based& & &\\ Coreset~\cite{Liebenwein2020Provable}& 1.59&+0.41&84.32\% \\ \hline Pruning& & & \\ via Coresets~\cite{Mussai20a} &2.16 &-0.13& $\sim 90$\%\\ \hline Learned Coreset (ours)& 2.07 &-0.04 &89.63\%\\ \hline \end{tabular} \end{adjustbox} \caption{\small Neural Pruning of LeNet-300-100 for MNIST. The results of FT, SoftNet, ThiNet and Sample-Based Coreset are reported in~\cite{Liebenwein2020Provable}. `+' and `-' correspond to increase and decrease in error, respectively.} \label{table:comparison-lenet} \end{table} \begin{table}[!h] \centering \begin{adjustbox}{width=1\columnwidth} \begin{tabular}{|l|ccc|} \hline Pruning Method & Baseline & Small Model& Compression \\ & Error(\%)&Error(\%)&Ratio \\\hline \hline Unstructured Pruning~\cite{han2015learning}& 6.5 & -0.02 & 80\%\\ \hline Structured Pruning~\cite{liu2017learning}& 6.33 & -0.13 & 70\% \\ \hline Pruning via Coresets~\cite{Mussai20a} &6.33 &-0.29 & 70\%\\ \hline Learned Coreset (ours) & 6.75&-0.26&70\%\\ \hline \end{tabular} \end{adjustbox} \caption{\small Channel Pruning of VGG-19 for CIFAR-10} \label{table:comparison-vgg} \end{table} \section{Conclusions} We proposed a novel unified framework for coreset learning that is theoretically motivated and can address problems for which obtaining theoretical worst-case guarantees is impossible. Following this framework, we suggested a relaxation of the coreset definition from the worst case to the average loss approximation. We proposed a learning algorithm that inputs a sample set of queries and a loss function associated with the problem at hand and outputs an average-loss coreset that holds for the training set of queries and generalizes to unseen queries. We showed that if the sample set of queries is sufficiently large, then the average loss over the coreset closely approximates the average loss over the full set for the entire query space. We then showed empirically, that our learned coresets are capable to generalize to unseen queries even for arbitrary sampling sizes. Our experiments demonstrated that coresets learned by our new approach yielded comparable and even better approximation of the optimal solution loss and average loss over the unseen queries than coresets that have worst-case guarantees. Moreover, our method applied to the problem of deep networks pruning provides the first full-network coreset with excellent performance. In future work we will try reducing the sampling bound and will apply the proposed framework to derive new coresets. \bibliographystyle{plain}
{'timestamp': '2021-11-05T01:22:22', 'yymm': '2111', 'arxiv_id': '2111.03044', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03044'}
arxiv
\section{Missing Proofs from Section \ref{sec:gaussian}}\label{sec:proof-gaussian} \subsection{Missing proofs from Section~\ref{sec:median-general}} \label{sec:proof-median-general} \begin{customtheorem}{\ref{thm:medianub}} Let $\mathcal{C}$ be a class of distributions over $\mathbb{R}$ with median in $[0,1]$. Define: $$a_F:=\sup_{F\in\mathcal{C}}\log{\textstyle|F^{-1}(\frac{1}{2}+\frac{\epsilon}{3})-F^{-1}(\frac{1}{2}-\frac{\epsilon}{3})|^{-1}}.$$ We have \[\textsc{PriceCplx}_{\mathcal{C},\theta}(\epsilon) \leq \tilde{O}(1/\epsilon^2)a_F\log a_F.\] \end{customtheorem} \begin{proof}[Proof of Theorem \ref{thm:medianub}] Algorithm \ref{alg:binary_ucb} searches for a price $p^*$ with $F(p^*)\in[\frac{1}{2}-\epsilon,\frac{1}{2}+\epsilon]$. The algorithm starts with a range $[0,1]$ of the potential median, and repeatedly price at the middle point $p=\frac{1}{2}$ of the range. After $n$ queries, if the current acceptance rate of the price $p$ is $\bar{q}$, then the true quantile $q=Q(p)=1-F(p)$ is bounded in a confidence interval $[\bar{q}-\tilde{O}(n^{-1/2}),\bar{q}+\tilde{O}(n^{-1/2})]$ with high probability by Chernoff bound. If $\frac{1}{2}$ is outside the confidence interval after $n$ steps, assume that $\frac{1}{2}>\bar{q}+\tilde{O}(n^{-1/2})$, then with high probability $q=Q(p)<\frac{1}{2}$, and $|\frac{1}{2}-q|=\Omega(n^{-1/2})$. The algorithm proceeds with a new range $[\frac{1}{2},1]$, and repeat the binary search process until it finds a price $p$ with $\Omega(n^{-1/2})<\epsilon$.\\ Consider any iteration with price $p$ and corresponding quantile $q=Q(p) := 1 - F(p)$. Assume that $q<\frac{1}{2}$, the case where $q>\frac{1}{2}$ is similar. Let $\alpha=6\sqrt{\log(t/\delta)/n}$. By Chernoff bound, after $n$ pricing queries on $p$, the probability that the selling rate $\bar{q}=\frac{k}{n}\not\in[q-\alpha,q+\alpha]$ is \begin{eqnarray*} \Pr[\bar{q}\not\in[q-\alpha,q+\alpha]]\leq 2\exp\left(-\frac{1}{2}n\alpha^2\right)=\frac{2\delta^3}{t^3}<\frac{\delta}{2t^3} \end{eqnarray*} when $\delta\leq\frac{1}{2}$. Thus by union bound, the probability that at any time the true quantile $q\in[\bar{q}-\alpha,\bar{q}+\alpha]$ is $>1-\sum_t\frac{\delta}{t^2}>1-\delta$. Thus with probability $1-\delta$, the algorithm never falsely searches a range $[\ell,r]$ that does not contain $p^*$. When $\bar{q}$ is not out of the confidence interval, we have $|\frac{1}{2}-\bar{q}|\leq 2\alpha$, while $|\bar{q}-q|\leq \alpha$ with probability $1-\delta$. Thus with probability $1-\delta$, $\epsilon_p=3\alpha\geq |\frac{1}{2}-q|$. Therefore $\epsilon_p$ is indeed an upper bound of $|\frac{1}{2}-q|$. Now we analyze the pricing complexity of the algorithm. When the algorithm prices at $p$ with $q=Q(p)$ such that $|q-\frac{1}{2}|\leq \frac{1}{3}\epsilon$, we show that the algorithm always returns with this price. Consider the following two cases. If the algorithm observes $|\frac{1}{2}-\bar{q}|>2\alpha$, then since with probability $1-\delta$ $|\bar{q}-q|\leq\alpha$, we have $|\frac{1}{2}-q|>\alpha$. Then $\epsilon_p=3\alpha<3|\frac{1}{2}-q|\leq \epsilon$, which means the algorithm returns the current price $p$. Otherwise the algorithm observes $\epsilon_p\leq \epsilon$ and returns. Thus if the algorithm sets some price $p$ with $q=Q(p)$ satisfying $|q-\frac{1}{2}|\leq \frac{1}{3}\epsilon$, then the algorithm would always return with this price. Since the algorithm always finds a price $p$ with $|Q(p)-\frac{1}{2}|\leq \frac{1}{3}\epsilon$ in $a_F=\log\frac{1}{F^{-1}(\frac{1}{2}+\frac{\epsilon}{3})-F^{-1}(\frac{1}{2}-\frac{\epsilon}{3})}$ rounds of different prices. Let $n$ be the number of queries in the last round of pricing. Then $t\leq a_Fn$, and $18\sqrt{\frac{\log(a_Fn/\delta)}{n}}<\epsilon$. Therefore $n=\tilde{O}(\frac{1}{\epsilon^2})\log\frac{a}{\delta}$, which means the query complexity of the algorithm is at most $a\tilde{O}(\frac{1}{\epsilon^2})\log\frac{a_F}{\delta}$. \end{proof} \subsection{Missing proofs from Section~\ref{sec:mean-normal}} \label{sec:proof-mean-normal} \begin{customcorollary}{\ref{cor:median-ub}} Let $\bar\mathcal{C}_{\bar\sigma} = \left\{ \mathcal{N}(\mu, \sigma) \text{ s.t. } \mu \in [0,1],\ \sigma\leq\bar\sigma\right\}$ be the class of normal distributions with variance at most $\bar\sigma^2$ with the loss $\L(\theta, \hat \theta) = \abs{\theta - \hat \theta}$. Then the pricing complexity of computing the mean is: $$\textsc{PriceCplx}_{\bar\mathcal{C}_{\bar\sigma},\mu}(\epsilon)= O(\bar\sigma^2/\epsilon^2).$$ \end{customcorollary} \begin{proof}[Proof of Corollary~\ref{cor:median-ub}] use the following variant of the algorithm for Theorem~\ref{lm:norm}: \begin{itemize} \item Use Algorithm~\ref{alg:binary_ucb} with $\epsilon = \frac{1}{12}$ to find $p_1$ and $p_2$ with $Q(p_1) \in [1/6, 2/6]$ and $Q(p_2) \in [4/6, 5/6]$, \item Using $O(\bar \sigma^2/\epsilon^2)$ pricing queries, find estimates $\hat q_i$ such that $\abs{\hat q_i - Q_{\mu,\sigma}(p_i)} \leq \epsilon/\bar \sigma$. \item Solve the system of equations $\hat{q}_1 = Q_{\hat \mu, \hat \sigma}(p_1)$ and $\hat{q}_2 = Q_{\hat \mu, \hat \sigma}(p_2)$ to find estimates of $\hat \mu, \hat \sigma$. \end{itemize} By the same argument as in the proof of Theorem~\ref{lm:norm}, the equations above can be re-written in linear form: $$\hat \mu + \hat \sigma \cdot Q_{0,1}^{-1}(\hat q_1) = p_1 \qquad \hat \mu + \hat \sigma \cdot Q_{0,1}^{-1}(\hat q_2) = p_2$$ The actual mean and variance are solutions to the same equation with exact quantiles: $$ \mu + \sigma \cdot Q_{0,1}^{-1}( q_1) = p_1 \qquad \mu + \sigma \cdot Q_{0,1}^{-1}( q_2) = p_2$$ Comparing those equations we can observe the following (we omit the details of the calculations as they are quite standard): $$\abs{\mu - \hat \mu} \leq O\left( \sigma \abs{p_1 - p_2} \cdot \max_i \abs{Q_{0,1}^{-1}(\hat q_i) - q_i} \right) = O\left(\sigma \cdot \frac{\epsilon}{\bar \sigma}\right) = O(\epsilon)$$ This leads to an algorithm with $O(\bar \sigma^2 / \epsilon^2)$ pricing queries that only requires knowledge of a \emph{variance upper bound}. \end{proof} \section {Missing Proofs from Section \ref{sec:monopoly}} \label{sec:proof-monopoly} \begin{customlemma}{\ref{lem:repeatprice}} For any value distribution $F$ and value $p$, let $Q(p)=1-F(p)$ be the probability that a random sample from $F$ is at least $p$. Then if we make $m=\tilde{O}(\frac{1}{\epsilon^2}\log\frac{1}{\delta})$ pricing queries with price $p$, then with probability $>1-\delta$ the price is accepted $m(Q(p)\pm\epsilon)$ times. \end{customlemma} \begin{proof}[Proof of Lemma~\ref{lem:repeatprice}] Let $q^*=Q(p)$ be the probability that $v\sim F$ is at least $p$. For any $m$ queries of price $p$, suppose that there are $t$ queries with signal ``$v\geq p$''. By Chernoff bound, \begin{eqnarray*} \Pr\left(t\not\in[m(q^*-\epsilon)]\right)\leq 2\exp\left(-\frac{\epsilon^2m}{2q^*}\right)\leq 2\exp\left(-\frac{\epsilon^2m}{2}\right). \end{eqnarray*} When $m=2\frac{1}{\epsilon^2}\log\frac{2}{\delta}=\Theta(\frac{1}{\epsilon^2}\log\frac{1}{\delta})$, the right hand side of the above inequality be at most $\delta$. Thus if $q^*\not\in[q-\epsilon,q+\epsilon]$ for some probability $q$, after $m=\Theta(\frac{1}{\epsilon^2}\log\frac{1}{\delta})$ pricing queries on $p$, with probability $<\delta$ the number of queries with signal ``$v\geq p$'' is in $[m(q^*-\epsilon),m(q^*+\epsilon)]$. \end{proof} \subsection{Missing proofs from Section~\ref{sec:regular}} \label{sec:proof-regular} \begin{customlemma}{\ref{lem:myerson-average}}[Relative Flatness of Regular Distributions] Let $\textsc{Rev}$ be the revenue curve of a regular distribution. Consider four equidistant values $p_1<p_2<p_3<p_4=cp_1$ in $[0,1]$ and let $\textsc{Rev}_{\max}$ and $\textsc{Rev}_{\min}$ be the maximum and minimum value of the revenue curve at those four points. Then if $\textsc{Rev}_{\min} \geq \textsc{Rev}_{\max}-\epsilon$, for some $\epsilon>0$, then for any $p\in[p_1,p_4]$, $\textsc{Rev}(p)\leq \textsc{Rev}_{\max}+O(c\epsilon)$. \end{customlemma} \begin{proof}[Proof of Lemma~\ref{lem:myerson-average}] For each $i=1,2,3,4$, let $q_i=Q(p_i)$. Denote $q=Q(p)$. Since $p_1-\ell=p_2-p_1=p_3-p_2=p_4-p_3$, we have $p_1<p_4=cp_1$. If $\textsc{Rev}_{\max}<2\epsilon$, then for any $p\in[p_1,p_4]$, $\textsc{Rev}(p)=pQ(p)\leq p_4Q(p_1)=cp_1Q(p_1)\leq c\textsc{Rev}_{\max}=O(c\epsilon)$, thus $\textsc{Rev}(p)\leq\textsc{Rev}_{\max}+O(c\epsilon)$. Therefore we assume $\textsc{Rev}_{\max}\geq 2\epsilon$, then $\textsc{Rev}(p_1),\textsc{Rev}(p_2),\textsc{Rev}(p_3),\textsc{Rev}(p_4)\geq \frac{1}{2}\textsc{Rev}_{\max}$. Thus $q_1=\frac{1}{p_1}\textsc{Rev}(p_1)\leq \frac{c}{p_4}\cdot2\textsc{Rev}(p_4)=2cq_4$, in other words, all $q\in[q_4,q_1]$ are within a constant factor of $2c$. Since $\textsc{Rev}$ is the revenue curve of a regular distribution, it is a concave function in quantile space. Consider the following two cases: \noindent\emph{Case 1:} $p\geq Q^{-1}(\frac{q_2+q_3}{2})$. We can express $q_2$ as a linear combination of $q_1$ and $q$ by $q_2=\frac{q_2-q}{q_1-q}q+\frac{q_1-q_2}{q_1-q}q_1$, thus \[\textsc{Rev}(p_2)\geq \frac{q_2-q}{q_1-q}\textsc{Rev}(p)+\frac{q_1-q_2}{q_1-q}\textsc{Rev}(p_1).\] Then \begin{eqnarray} \textsc{Rev}(p)&\leq&\frac{(q_1-q)\textsc{Rev}(p_2)-(q_1-q_2)\textsc{Rev}(p_1)}{q_2-q}\leq\frac{(q_1-q)(\textsc{Rev}(p_1)+\epsilon)-(q_1-q_2)\textsc{Rev}(p_1)}{q_2-q}\nonumber\\ &=&\textsc{Rev}(p_1)+\frac{q_1-q}{q_2-q}\epsilon=\textsc{Rev}(p_1)+\frac{q_1-q_2}{q_2-q}\epsilon+\epsilon\leq\textsc{Rev}(p_1)+\frac{q_1-q_2}{q_2-q_3}2\epsilon+\epsilon.\label{eqn:revp} \end{eqnarray} Here the last inequality is by $q\leq\frac{q_2+q_3}{2}$. If $\epsilon>\frac{1}{2}q_3(p_3-p_2)$, then \[\epsilon>\frac{1}{2}q_3(p_3-p_2)\geq \frac{1}{2}\cdot\frac{1}{2c}q\cdot\frac{1}{2}(p-p_2)\geq\frac{1}{8c}(qp-q_2p_2)=\frac{1}{8c}(\textsc{Rev}(p)-\textsc{Rev}(p_2)).\] Here the second inequality is by $q\geq\frac{1}{2c}q_3$, and $p-p_2\leq p_4-p_2=2(p_3-p_2)$; the third inequality is by $q\leq q_2$. Therefore $\textsc{Rev}(p)\leq\textsc{Rev}(p_2)+O(c\epsilon)=\textsc{Rev}_{\max}+O(c\epsilon)$ if $\epsilon>\frac{1}{2}q_3(p_3-p_2)$. Now we assume that $\epsilon\leq\frac{1}{2}q_3(p_3-p_2)$. Since $\textsc{Rev}(p_1)\leq \textsc{Rev}(p_2)+\epsilon$, we have $p_1q_1\leq p_2q_2+\epsilon$, then $q_1-q_2\leq\frac{q_1(p_2-p_1)+\epsilon}{p_1}$. At the same time, $\textsc{Rev}(p_2)\geq\textsc{Rev}(p_3)-\epsilon$, we have $p_2q_2\geq p_3q_3-\epsilon$, then $q_2-q_3\geq\frac{q_3(p_3-p_2)-\epsilon}{p_2}$. Thus \begin{eqnarray*} \frac{q_1-q_2}{q_2-q_3}&\leq& \frac{p_2(q_1(p_2-p_1)+\epsilon)}{p_1(q_3(p_3-p_2)-\epsilon)}\leq \frac{p_2(q_1(p_2-p_1)+\frac{1}{2}q_3(p_3-p_2))}{p_1(q_3(p_3-p_2)-\frac{1}{2}q_3(p_3-p_2))}\\ &\leq&\frac{2(q_1+\frac{1}{2}q_3)}{(q_3-\frac{1}{2}q_3)}=2+\frac{4q_1}{q_3}\leq 2+8c=O(c). \end{eqnarray*} Here the second inequality is by $\epsilon\leq\frac{1}{2}q_3(p_3-p_2)$; the third inequality is by $p_2\leq 2p_1$ and $p_3-p_2=p_2-p_1$; the last inequality is by $q_1\leq 2cq_3$. By \eqref{eqn:revp} we have $\textsc{Rev}(p)\leq \textsc{Rev}_{\max}+O(c\epsilon)$. \noindent\emph{Case 2:} $p< Q^{-1}(\frac{q_2+q_3}{2})$. We can express $q_3$ as a linear combination of $q$ and $q_4$ by $q_3=\frac{q-q_3}{q-q_4}q+\frac{q_3-p_4}{q-q_4}q_4$. Thus by concavity of $\textsc{Rev}$ in the quantile space, \[\textsc{Rev}(p_3)\geq \frac{q-q_3}{q-q_4}\textsc{Rev}(p)+\frac{q_3-q_4}{q-q_4}\textsc{Rev}(p_4).\] Then \begin{eqnarray} \textsc{Rev}(p)&\leq&\frac{(q-q_4)\textsc{Rev}(p_3)-(q_3-q_4)\textsc{Rev}(p_4)}{q-q_3}\leq\frac{(q-q_4)(\textsc{Rev}(p_4)+\epsilon)-(q_3-q_4)\textsc{Rev}(p_4)}{q-q_3}\nonumber\\ &=&\textsc{Rev}(p_4)+\frac{q-q_4}{q-q_3}\epsilon=\textsc{Rev}(p_4)+\frac{q_3-q_4}{q-q_3}\epsilon+\epsilon<\textsc{Rev}(p_4)+\frac{q_3-q_4}{q_2-q_3}2\epsilon+\epsilon.\label{eqn:revp-case2} \end{eqnarray} Here the last inequality is by $q>\frac{q_2+q_3}{2}$. If $\epsilon>\frac{1}{2}q_3(p_3-p_2)$, then as we have reasoned in Case 1, $\textsc{Rev}(p)\leq \textsc{Rev}_{\max}+O(c\epsilon)$. Now we assume that $\epsilon\geq\frac{1}{2}q_3(p_3-p_2)$. Since $\textsc{Rev}(p_3)\leq \textsc{Rev}(p_4)+\epsilon$, we have $p_3q_3\leq p_4q_4+\epsilon$, then $q_3-q_4\leq\frac{(p_4-p_3)q_4+\epsilon}{p_3}$. At the same time, as we have shown in Case 1, $q_2-q_3\geq\frac{q_1(p_3-p_2)-\epsilon}{p_2}$. Thus \begin{eqnarray*} \frac{q_3-q_4}{q_2-q_3}&\leq& \frac{p_2(q_4(p_4-p_3)+\epsilon)}{p_3(q_3(p_3-p_2)-\epsilon)}\leq \frac{p_2(q_4(p_4-p_3)+\frac{1}{2}q_3(p_3-p_2))}{p_3(q_3(p_3-p_2)-\frac{1}{2}q_3(p_3-p_2))}\\ &\leq&\frac{q_4+\frac{1}{2}q_3}{q_3-\frac{1}{2}q_3}=1+\frac{2q_4}{q_3}\leq 1+2=3. \end{eqnarray*} Here the second inequality is by $\epsilon\leq\frac{1}{2}q_3(p_3-p_2)$; the third inequality is by $p_2\leq p_3$ and $p_3-p_2=p_4-p_3$; the last inequality is by $q_4\leq q_3$. By \eqref{eqn:revp-case2} we have $\textsc{Rev}(p)\leq \textsc{Rev}_{\max}+O(c\epsilon)$. \end{proof} \subsection{Mission proofs from Section~\ref{sec:mhr}} \label{sec:proof-mhr} In this section, we prove the pricing query complexity for estimating the monopoly price of MHR distributions. \begin{customtheorem}{\ref{thm:mhrlb}} Let $\mathcal{C}_{\textsc{MHR}}$ be the class of Monotone Hazard Rate distributions supported in $[0,1]$ and let $\theta$ be the monopoly price. Then $$\textsc{PriceCplx}_{\mathcal{C}_{\textsc{MHR}},\theta}(\epsilon) = \Omega(1/\epsilon^2).$$ \end{customtheorem} Before proving the theorem, we start with a technical lemma bounding the KL-divergence of two Bernoulli variables. \begin{lemma}\label{lem:kl-bernoulli} For any $\epsilon<\frac{\sqrt{2}}{2}$ and two Bernoulli variables $X,Y$ with $\frac{1}{1+\epsilon}\leq \frac{\Pr[X=1]}{\Pr[Y=1]},\frac{\Pr[X=0]}{\Pr[Y=0]}\leq 1+\epsilon$, $D_{\textrm{KL}}(X\|Y)<\epsilon^2$. \end{lemma} \begin{proof}[Proof of Lemma~\ref{lem:kl-bernoulli}] Let $q=\Pr[X=1]$, $q'=\Pr[Y=1]$. Without loss of generality assume $q\leq \frac{1}{2}$ (otherwise just set $q\leftarrow 1-q$ and $q'\leftarrow 1-q'$). Let $f(q,q')=D_{\textrm{KL}}(X\|Y)$. Then \begin{equation*} f(q,q')=D_{\textrm{KL}}(X\|Y)=q\ln\frac{q}{q'}+(1-q)\ln\frac{1-q}{1-q'}=q\ln q-q\ln q'+(1-q)\ln(1-q)-(1-q)\ln (1-q'). \end{equation*} Then \begin{equation*} \frac{\partial}{\partial q}f(q,q')=\ln q-\ln q'-\ln(1-q)+\ln(1-q')=\ln\frac{q}{q'}-\ln\frac{1-q}{1-q'} \end{equation*} has unique zero point $q=q'$, which means $f(q,q')$ increases when $q>q'$, and decreases when $q<q'$. Therefore, to upper bound $f(q,q')$, it suffices to bound it for $q=(1+\epsilon)q'$ and $q=(1-\epsilon)q'$. \paragraph{Case 1.} When $q=(1+\epsilon)q'$, \begin{eqnarray*} f(q,q')&=&q\ln\frac{q}{q'}+(1-q)\ln\frac{1-q}{1-q'}\\ &=&q\ln(1+\epsilon)+(1-q)\ln(1-q)-(1-q)\ln\left(1-\frac{q}{1+\epsilon}\right). \end{eqnarray*} Take the derivative of the right hand side with respect to $q$, we have \begin{eqnarray*} \frac{\partial}{\partial q}f\left(q,\frac{q}{1+\epsilon}\right)&=&\ln(1+\epsilon)-1-\ln(1-q)+\ln\left(1-\frac{q}{1+\epsilon}\right)+(1-q)\frac{1}{1+\epsilon}\frac{1}{1-\frac{q}{1+\epsilon}}\\ &=&(\ln(1+\epsilon)-1)+\ln\frac{1-\frac{q}{1+\epsilon}}{1-q}+\frac{1-q}{1+\epsilon-q}>0. \end{eqnarray*} The inequality is true since each term in the sum is non-negative. Thus $f(q,\frac{q}{1+\epsilon})$ is maximized when $q=\frac{1}{2}$, and \begin{eqnarray*} f\left(q,\frac{q}{1+\epsilon}\right)\leq f\left(\frac{1}{2},\frac{1}{2+2\epsilon}\right) =\frac{1}{2}\ln(1+\epsilon)+\frac{1}{2}\ln\frac{\frac{1}{2}}{1-\frac{1}{2+2\epsilon}}=\frac{1}{2}\ln\frac{(1+\epsilon)^2}{1+2\epsilon}<\frac{1}{2}\frac{\epsilon^2}{1+2\epsilon}<\epsilon^2, \end{eqnarray*} here the second inequality is by $\ln(1+x)<x$ for any $x>0$. \paragraph{Case 2.} When $q=\frac{1}{1+\epsilon}q'$, \begin{eqnarray*} f(q,q')&=&q\ln\frac{q}{q'}+(1-q)\ln\frac{1-q}{1-q'}\\ &=&-q\ln(1+\epsilon)+(1-q)\ln(1-q)-(1-q)\ln\left(1-(1+\epsilon)q\right). \end{eqnarray*} Take the derivative of the right hand side with respect to $q$, we have \begin{eqnarray*} \frac{\partial}{\partial q}f\left(q,(1+\epsilon)q\right)&=&-\ln(1+\epsilon)-1-\ln(1-q)+\ln\left(1-(1+\epsilon)q\right)+(1-q)(1+\epsilon)\frac{1}{1-(1+\epsilon)q}\\ &=&-\ln\frac{(1-q)(1+\epsilon)}{1-(1+\epsilon)q}-1+\frac{(1-q)(1+\epsilon)}{1-(1+\epsilon)q}\geq0. \end{eqnarray*} The inequality follows from $-\ln x-1+x\geq0$ for any $x\geq 0$. Thus $f\left(q,(1+\epsilon)q\right)$ is maximized when $q=\frac{1}{2}$, and \begin{eqnarray*} f\left(q,(1+\epsilon)q\right)\leq f\left(\frac{1}{2},\frac{1+\epsilon}{2}\right) =-\frac{1}{2}\ln(1+\epsilon)+\frac{1}{2}\ln\frac{\frac{1}{2}}{1-\frac{1}{2}(1+\epsilon)}=\frac{1}{2}\ln\frac{1}{1-\epsilon^2}<\frac{1}{2}\frac{\epsilon^2}{1-\epsilon^2}< x^2, \end{eqnarray*} here the second inequality is by $\ln(1+x)<x$ for any $x>0$, and the last inequality is by $\epsilon>\frac{\sqrt{2}}{2}$. \end{proof} The lemma is then used to give a lower bound on the pricing query complexity of distinguishing two distributions whose c.d.f. $F(p)$ and quantiles $Q(p) = 1-F(p)$ are both within $1\pm \epsilon$ of each other. \begin{customlemma}{\ref{lem:query-complexity}} For two value distributions $D$ and $D'$, if $\frac{1}{1+\epsilon}\leq\frac{Q_D(v)}{Q_{D'}(v)},\frac{F_D(v)}{F_{D'}(v)} \leq (1+\epsilon)$ for every $v\in[0,1]$, then $\Omega(\frac{1}{\epsilon^2})$ pricing queries are needed to distinguish the two distributions with probability $>1-\delta$. \end{customlemma} The proof idea of Lemma~\ref{lem:query-complexity} is as follows. For two such distributions $D$ and $D'$, and any pricing algorithm $\mathcal{A}$, let $X_i$ and $X'_i$ be the bit each algorithm receives from the $i$-th pricing query. To show that $\mathcal{A}$ needs $m=\Omega(\epsilon^{-2})$ queries to distinguish the two distribution, it suffices to show that $(X_1,\cdots,X_m)$ and $(X'_1,\cdots,X_m)$ has $\Omega(1)$ statistical distance (thus KL-divergence $\Omega(1)$) only if $\Omega(\epsilon^{-2})$. By Lemma~\ref{lem:kl-bernoulli} the gain of relative entropy from each query is at most $\epsilon^2$, thus $\Omega(\epsilon^{-2})$ queries are needed for the KL-divergence to become $\Omega(1)$. \begin{proof}[Proof of Lemma~\ref{lem:query-complexity}] Consider any algorithm $\mathcal{A}$ that adaptively sets a pricing query in each step. For every $i\geq 1$, let $X_{i}$ be a boolean random variable that denotes whether the $i$-th sampled value $v_i\sim D$ is at least the price $p_{i,D}$ at the $i$-th step in algorithm $\mathcal{A}$ for value distribution $D$. In other words, $X_i=\mathbf{1}[v_i\geq p_{i,D}]$. Similarly, define $X'_{i}$ to be a boolean random variable that denotes whether the $i$-th sampled value $v'_i\sim D'$ is at least the price $p_{i,D'}$ at the $i$-th step in algorithm $\mathcal{A}$ for value distribution $D'$. For each $n\geq 1$, denote $\mathbf{X}_{\leq n}=(X_1,X_2,\cdots,X_n)$ and $\mathbf{X}'_{\leq n}=(X'_1,X'_2,\cdots,X'_n)$. For any price $p\in[0,1]$, random values $v\sim D$ and $v'\sim D'$, and random variables $X=\mathbf{1}[v\geq p]$ and $Y=\mathbf{1}[v'\geq p]$, let $q=\Pr[X=1]$ and $q'=\Pr[Y=1]$. The Kullback–Leibler divergence of $X$ and $Y$ can be bounded by Lemma \ref{lem:kl-bernoulli}. Then for any fixed $(x_1,\cdots,x_{m-1})\in\{0,1\}^{m-1}$, conditioned on $(X_1,\cdots,X_{m-1})=(x_1,\cdots,x_{m-1})$ algorithm $\mathcal{A}$ sets a random price $p$; $X_{m}$ is a Bernoulli variable with probability $q=\mathbb{E}_{p}[\Pr_{v\sim D}[v\geq p]]=\mathbb{E}_{p}[Q_D(p)]$ being 1; $X'_{m}$ is a Bernoulli variable with probability $q'=\mathbb{E}_{p}[\Pr_{v\sim D'}[v\geq p]]=\mathbb{E}_{p}[Q_{D'}(p)]$ being 1. By the condition of Lemma~\ref{lem:query-complexity}, $\frac{1}{1+\epsilon}<\frac{q}{q'},\frac{1-q}{1-q'}<1+\epsilon$. Thus by Lemma~\ref{lem:kl-bernoulli}, \begin{equation*} D_{\textrm{KL}}\bigg(X_m|_{\mathbf{X}_{\leq m-1}=(x_1,\cdots,x_{m-1})}\bigg\|X'_m|_{\mathbf{X}'_{\leq m-1}=(x_1,\cdots,x_{m-1})}\bigg)<\epsilon^2. \end{equation*} For any $n\geq 1$, let $\mathbf{x}_{\leq n}=(x_1,x_2,\cdots,x_n)$. Then by the chain rule of KL divergence, \begin{eqnarray*} D_{\textrm{KL}}(X_{\leq m}\|X'_{\leq m}) &=&D_{\textrm{KL}}(X_{\leq m-1}\|X'_{\leq m-1})+\mathbb{E}_{\mathbf{X}_{\leq m-1}}D_{\textrm{KL}}\bigg(X_m|_{\mathbf{X}_{\leq m-1}=\mathbf{x}_{\leq m-1}}\bigg\|X'_m|_{\mathbf{X}'_{\leq m-1}=\mathbf{x}_{\leq m-1}}\bigg)\\ &<&D_{\textrm{KL}}(X_{\leq m-1}\|X'_{\leq m-1})+\epsilon^2<D_{\textrm{KL}}(X_{\leq m-2}\|X'_{\leq m-2})+2\epsilon^2<\cdots<m\epsilon^2. \end{eqnarray*} Let $D_m$ and $D'_m$ be the distribution of $\mathbf{X}_{\leq m}$ and $\mathbf{X}'_{\leq m}$ respectively. The probability that algorithm $\mathcal{A}$ can identify the distribution with $m$ samples is at most $\frac{1+\delta(D_m,D'_m)}{2}$, here $\delta(A,B)=\frac{1}{2}\int |f_A(x)-f_B(x)|dx$ represents the statistical distance of two distributions $A$ and $B$ with density $f_A$ and $f_B$ respectively. Thus to identify distribution $D$ and $D'$ with probability $1-\delta$, the number of samples $m$ need to be large enough such that $\delta(D_m,D'_m)=\Omega(1)$. By Pinsker's inequality, \begin{equation*} \delta(D_m,D'_m)\leq\sqrt{\frac{1}{2}D_{\textrm{KL}}(D_m,D'_m)}<\sqrt{\frac{m}{2}\epsilon^2}. \end{equation*} Thus when $\delta(D_m,D'_m)=\Omega(1)$, $\sqrt{\frac{m}{2}\epsilon^2}=\Omega(1)$. Thus $m=\Omega(\frac{1}{\epsilon^2})$ samples are necessary to distinguish $D$ and $D'$ with probability $>\frac{2}{3}$ for any (randomized adaptive) algorithm $\mathcal{A}$. \end{proof} Finally, we are ready to analyze the pricing query complexity for estimating the monopoly price for MHR distributions. \begin{proof} [Proof of Theorem~\ref{thm:mhrlb}] We consider the following MHR distribution $D$ with sample complexity $\Omega(\epsilon^{-3/2})$ that is modified from an example in Huang et al \cite{HMR18}. Let $\epsilon_0=16\epsilon$, and $f$ be the density of $D$ as follows: \begin{equation*} f_D(v)=\begin{cases} 0.4 &\textrm{ if } 0\leq v< \frac{1}{2};\\ 1.6-3.2\sqrt{\epsilon_0}&\textrm{ if } \frac{1}{2}\leq v< \frac{1}{2}+\frac{1}{2}\sqrt{\epsilon_0};\\ 1.6+\frac{3.2\epsilon_0}{1-\sqrt{\epsilon_0}}&\textrm{ if } \frac{1}{2}+\frac{1}{2}\sqrt{\epsilon_0}\leq v\leq 1. \end{cases} \end{equation*} Let $f_{D'}(v)$ be the density of distribution $D'$ as follows: \begin{equation*} f_{D'}(v)=\begin{cases} 0.4 & \textrm{ if } 0\leq v< \frac{1}{2};\\ 1.6 & \textrm{ if } \frac{1}{2}\leq v\leq 1. \end{cases} \end{equation*} In other words, distribution $D'$ is uniform on $[0,\frac{1}{2}]$ and $[\frac{1}{2},1]$, while distribution $D$ is a perturbation of $D'$ on $[\frac{1}{2},1]$, with the density of $D'$ in $[\frac{1}{2},\frac{1}{2}+\frac{1}{2}\sqrt{\epsilon_0}]$ scaled down by a factor of $1-2\sqrt{\epsilon_0}$, and the density of $D'$ in $[\frac{1}{2}+\frac{1}{2}\sqrt{\epsilon_0},1]$ scaled up by a factor of $1+\frac{2\epsilon_0}{1-\sqrt{\epsilon_0}}$ in $D$. Let $F_D$ and $F_{D'}$ be the cumulative density function of $D$ and $D'$ respectively, and let $Q_D(v)=1-F_D(v)$, $Q_{D'}(v)=1-F_{D'}(v)$. Then for any $v\in[0,1]$, $Q_{D'}(v)\leq Q_{D}(v)\leq \left(1+\frac{2\epsilon_0}{1-\sqrt{\epsilon_0}}\right)Q_{D'}(v)$. In other words, when setting any pricing query over the two distributions, the probability that the buyer can afford to purchase the item differs by only a factor of $1+\frac{2\epsilon_0}{1-\sqrt{\epsilon_0}}<1+3\epsilon_0$ for small enough $\epsilon_0$. For uniform distribution $D'$, the optimal monopoly price is $p_{D'}^*=\frac{1}{2}$, with revenue $0.4$. Only prices in $p\leq p_0=\frac{1}{2}+\sqrt{\epsilon}$ would lead to revenue $\geq0.4-1.6\epsilon$. For uniform distribution $D$, the optimal monopoly price is $p_D^*=\frac{1}{2}+\frac{1}{2}\sqrt{\epsilon_0}$, with revenue $0.4+0.4\epsilon_0+0.8\epsilon_0^{3/2}=0.4+6.4\epsilon+51.2\epsilon^{3/2}>p^*_{D'}Q_{D'}(p^*_{D'})+\epsilon$. For $p\leq p_0$, the revenue is \begin{eqnarray*} pQ_D(p)&\leq& p_0Q_D(p_0)=(0.5+\sqrt{\epsilon})(0.8-1.6\sqrt{\epsilon}(1-2\sqrt{\epsilon_0})) =0.4-1.6\epsilon+1.6\sqrt{\epsilon\eps_0}+3.2\epsilon\sqrt{\epsilon_0}\\ &=&0.4+4.8\epsilon+12.8\epsilon^{3/2}<p^*_{D}Q_D(p^*_D)-\epsilon. \end{eqnarray*} Thus no price can get $\epsilon$-close to the optimal revenue for both distribution $D$ and $D'$ at the same time. Consider a distribution that is one of $D$ and $D'$. To learn the optimal monopoly price or the optimal revenue of the distribution, one must be able to distinguish the two distributions with pricing queries. Observe that for any $v\leq\frac{1}{2}$, $F_D(v)=F_{D'}(v)$ and $Q_D(v)=Q_{D'}(v)$, thus $\frac{F_D(v)}{F_{D'}(v)}=\frac{Q_D(v)}{Q_{D'}(v)}=1$. For any $v\in(\frac{1}{2},1]$, \begin{equation*} 1\geq \frac{F_D(v)}{F_{D'}(v)}\geq\frac{F_D(\frac{1}{2}+\frac{1}{2}\sqrt{v_0})}{F_{D'}(\frac{1}{2}+\frac{1}{2}\sqrt{v_0})}=1-\frac{1.6\epsilon_0}{0.2+0.8\sqrt{\epsilon_0}}=\frac{1}{1+O(\epsilon)} \end{equation*} and \begin{equation*} 1\leq \frac{Q_D(v)}{Q_{D'}(v)}\leq\frac{Q_D(\frac{1}{2}+\frac{1}{2}\sqrt{v_0})}{Q_{D'}(\frac{1}{2}+\frac{1}{2}\sqrt{v_0})}= 1+\frac{1.6\epsilon_0}{0.8-0.8\sqrt{\epsilon_0}}=1+O(\epsilon) \end{equation*} by $\epsilon_0=16\epsilon$. Thus for any $v\in[0,1]$, $\frac{1}{1+O(\epsilon)}\leq \frac{F_D(v)}{F_{D'}(v)},\frac{Q_D(v)}{Q_{D'}(v)}\leq 1+O(\epsilon)$. By Lemma~\ref{lem:query-complexity} the number of queries needed to distinguish $D$ and $D'$ is $\Omega(\frac{1}{\epsilon^2})$, which is also a lower bound on the pricing complexity of estimating the monopoly price for MHR distributions. \end{proof} \subsection{Missing proofs from Section~\ref{sec:general-distribution}}\label{sec:proof-general} \begin{customtheorem}{\ref{thm:general-distribution}} Let $\mathcal{C}_{\textsc{ALL}}$ be the class of all value distributions on $[0,1]$ and $\theta$ be the monopoly. Then $$\textsc{PriceCplx}_{\mathcal{C}_{\textsc{ALL}},\theta}(\epsilon)= \tilde{\Theta}(1/\epsilon^3).$$ \end{customtheorem} \begin{proof}[Proof of Theorem~\ref{thm:general-distribution}] Firstly we show that $\textsc{PriceCplx}_{\mathcal{C}_{\textsc{ALL}},\theta}(\epsilon)= \tilde{O}(1/\epsilon^3).$ Actually, consider the following simple algorithm: price at every multiple of $\epsilon$ in $[0,1]$ for $\tilde{O}(\frac{1}{\epsilon^2})$ times such that for every such price $p$, $Q(p)$ is estimated by $\tilde{Q}(p)\in Q(p)\pm\epsilon$ (by Lemma~\ref{lem:repeatprice}). Notice that for price $p^*$ that maximizes the revenue $\textsc{Rev}(p^*)=p^*Q(p^*)$, the revenue from price $p=\epsilon\lfloor\frac{p^*}{\epsilon}\rfloor$ is $\textsc{Rev}(p)=pQ(p)\geq (p^*-\epsilon)Q(p^*)\geq \textsc{Rev}(p^*)-\epsilon$. Since the algorithm estimate $Q(p)$ with additive error $\epsilon$, thus $\widetilde{\rev}(p)\geq \textsc{Rev}(p)-\epsilon\geq \textsc{Rev}(p^*)-2\epsilon$. This means that the price $\hat{p}$ being a multiple of $\epsilon$ that maximizes $\hat{p}\tilde{Q}(\hat{p})$ estimates the optimal revenue with error $O(\epsilon)$. Now we show that the $\Omega(\frac{1}{\epsilon^3})$ pricing complexity is unavoidable. Consider the following $m=\frac{1}{16\epsilon}$ distributions $F_0, F_1,\cdots,F_{m}$. Distribution $F_i$ has support $\frac{1}{2}+4\epsilon$, $\frac{1}{2}+8\epsilon$, $\cdots$, $\frac{3}{4}-4\epsilon$, $\frac{3}{4}$, with the item-pricing revenue and quantiles satisfying \begin{equation*} \textsc{Rev}_i\left(\frac{1}{2}+4k\epsilon\right)=\left(\frac{1}{2}+4k\right) \cdot Q_i\left(\frac{1}{2}+4k\right)=\begin{cases} \frac{1}{4},&\textrm{ if }k\neq i;\\ \frac{1}{4}+\epsilon,&\textrm{ if }k=i. \end{cases} \end{equation*} In other words, for $i\geq 1$, each distribution $F_i$ has a unique revenue-maximizing price $\frac{1}{2}+4i\epsilon$ with revenue $\frac{1}{4}+\epsilon$, while other prices leads to revenue $\frac{1}{4}$ that is $\epsilon$-far from the optimal revenue. $F_0$ is an equal-revenue distribution with revenue $\frac{1}{4}$ for every price $\frac{1}{2}+4k\epsilon$. Thus the quantile of any two distributions $F_0$ and $F_{i}$ only differs at one point: $Q_i(\frac{1}{2}+4i\epsilon)=Q_{0}(\frac{1}{2}+4i\epsilon)+\Theta(\epsilon)$. For any other price $p=\frac{1}{2}+4k\epsilon$ with $k\neq i,j$, $Q_i(p)=Q_0(p)$. Then for any $i\in[\frac{m}{3},\frac{2m}{3}]$, since $Q_i(\frac{1}{2}+4i\epsilon)=\Theta(1)$ and $F_i(\frac{1}{2}+4i\epsilon)=\Theta(1)$, $\frac{1}{1+O(\epsilon)}\leq \frac{Q_i(v)}{Q_0(v)},\frac{F_i(v)}{F_0(v)}\leq 1+O(\epsilon)$. By Lemma~\ref{lem:query-complexity}, to distinguish $F_i$ and $F_0$, $\Omega(\frac{1}{\epsilon^2})$ pricing queries on $\frac{1}{2}+4i\epsilon$ are needed. Consider a setting where the underlying value distribution is $F_i$ for $i$ uniformly selected from $[\frac{1}{3}m,\frac{2}{3}m]$ but unknown beforehand. To find out the optimal revenue and the corresponding price, it is equivalent to find out the underlying value distribution. To distinguish $F_0$ and $F_i$, at least $\Omega(\frac{1}{\epsilon^2})$ pricing queries are needed on price $\frac{1}{2}+4i\epsilon$. Thus to distinguish $F_0$ and all other distributions, at least $\Omega(\frac{1}{\epsilon^2})$ pricing queries are needed on every price $\frac{1}{2}+4i\epsilon$, thus the query complexity is $\Omega(\frac{1}{\epsilon^3})$. \end{proof} \section*{Acknowledgement} \bibliographystyle{plainnat} \section{Introduction} An important question in the intersection of economics and statistics is to estimate properties of a buyer's willingness-to-pay (a.k.a. value) from samples. Samples typically come from buyer's bids in a truthful auction. In various economic setups though, collecting samples of true value is quite hard or impossible. For example, in many settings auction is not an option; often, posting prices is the only option. And the seller therefore has access only to a buyer's decision to buy or not at a given price. This is also true for auctions with very few buyers (not too uncommon in digital auctions as targeting becomes increasingly narrow and focused): if a buyer is the sole competitor, they may decide to bid just above the reserve price that is sent to them, or to not bid at all when their value is below the reserve price, in order to conceal information about their valuation. Likewise in non-truthful auctions, we don't have access to true value samples; we just have access to past bids. One thing we do have in all these scenarios is whether or not the true value exceeded a (reserve) price. Our goal in this paper to compare the power of \emph{value samples} (namely, samples from the buyer's value distribution) to that of \emph{pricing queries} (namely, a price $p$ and a response to whether or not the buyer's value is at least $p$).\\ What can we do with a single value sample? Dhangwatnotai et al.~\cite{DRY15} say that we can do a lot: we can price the buyer using that sample to extract \emph{half of the expected optimal revenue} achievable with full knowledge of the regular value distribution. Similarly a single value sample acts as an unbiased estimator of the mean of the distribution. Now consider a single pricing query. It is not possible to extract \emph{any non-zero fraction of the optimal revenue} from a single pricing query. Likewise there is nothing meaningful to estimate about the mean using a single pricing query. Both of these hold regardless of our choice of the price $p$. The contrast between the power of a single value sample and that of a single pricing query cannot be more stark. The question we investigate in this paper is what happens when we have a large number of pricing queries. How do the number of value samples required to get a $1-\epsilon$ approximation of the optimal revenue, or to estimate the mean within $\epsilon$ compare with the number of pricing queries required?\\ Let $\mathcal{C}$ be a class of distributions over $\mathbb{R}$ and $\theta:\mathcal{C} \rightarrow \mathbb{R}$ a parameter (such as the mean, the variance or the monopoly price). Let $\L:\mathbb{R}^2 \rightarrow \mathbb{R}$ be a loss function estimating the error in the parameter estimator\footnote{The loss can implicitly depend on the distribution $\mathcal{D} \in \mathcal{C}$.}. We will consider the following parameters and respective losses: \begin{itemize} \item \emph{Median:} $\theta(\mathcal{D}) = \text{median}(\mathcal{D})$ with loss $\L(\theta; \hat\theta) = \abs{F_\mathcal{D}(\theta) - F_\mathcal{D}(\hat \theta)}$, where $F_\mathcal{D}$ is the c.d.f. \item \emph{Mean:} $\theta(\mathcal{D}) = \mathbb{E}_{v \sim \mathcal{D}}[v]$ with loss $\L(\theta; \hat\theta) = \abs{\theta - \hat \theta}$. \item \emph{Monopoly price:} $\theta(\mathcal{D}) = \text{argmax}_p \textsc{Rev}_\mathcal{D}(p) := \mathbb{E}_{v \sim \mathcal{D}} [p \cdot \mathbf{1}\{v \geq p\}]$ with the loss that compares the revenue at the optimal and estimated point: $\L(\theta; \hat \theta) = \abs{\textsc{Rev}_\mathcal{D}(\theta) - \textsc{Rev}_\mathcal{D}(\hat \theta)}$. \end{itemize} In our last example, the parameter is a function rather than a real number: \begin{itemize} \item \emph{CDF:} $\theta(\mathcal{D}) = F_\mathcal{D}(\cdot)$ with loss $\L(F_\mathcal{D}; \hat F) = \textsf{LevyDistance}(F_\mathcal{D}; \hat F)$ which corresponds to the infimum over $\epsilon>0$ such that $F_\mathcal{D}(v-\epsilon)-\epsilon \leq \hat F(v) \leq F_\mathcal{D}(v+\epsilon)+\epsilon$ for all $v \in \mathbb{R}$. \end{itemize} A pricing estimator with $m$ queries consists of an algorithm that posts $m$ prices\footnote{We allow both values $v_t$ and prices $p_t$ to be negative. A negative value means that the buyer has a disutility for the good, while a negative price means that the buyer is compensated for acquiring the good. Negative values are allowed for convenience to obtain cleaner algorithms. The same results can be obtained for non-negative values by dealing with the corner cases around zero.} $p_1, p_2, \hdots, p_m \in \mathbb{R}$. For each price $p_t$ posted the algorithm observes if a buyer with a freshly drawn value buys or not at that price. In other words, we observe $s_t = \textsf{sign}(v_t - p_t) \in \{-1,+1\}$ for some $v_t \sim \mathcal{D}$. The prices can be computed adaptively. Finally, the algorithm outputs an estimate $\hat \theta (s_1, \hdots, s_m)$. An $(\epsilon,\delta)$-pricing-query-estimator is an algorithm such that: $$\P_{v_1, \hdots, v_m \sim \mathcal{D}} \left( \L(\theta(\mathcal{D}); \hat \theta (s_1, \hdots, s_m)) \leq \epsilon \right) \geq 1-\delta, \quad \forall \mathcal{D} \in \mathcal{C}$$ Given a class $\mathcal{C}$ and parameter $\theta$ and loss $\L$ we define the \emph{pricing query complexity} $\textsc{PriceCplx}_{\mathcal{C},\theta}(\epsilon)$ to be the minimum $m$ such that there exists a $(\epsilon,1/2)$-pricing-query-estimator for $\mathcal{C}$, $\L$ and $\delta$. It is useful to compare with traditional estimators and sample complexity. A traditional $(\epsilon,\delta)$-estimator is an algorithm that processes the samples $v_1, \hdots, v_m$ directly and produces an estimator $ \hat \theta (v_1, \hdots, v_m)$ such that: $$\P_{v_1, \hdots, v_m \sim \mathcal{D}} \left( \L(\theta(\mathcal{D}); \hat \theta (v_1, \hdots, v_m)) \leq \epsilon \right) \geq 1-\delta, \quad \forall \mathcal{D} \in \mathcal{C}$$ Similarly, we can define the sample complexity as $\textsc{SampleCplx}_{\mathcal{C},\theta}(\epsilon)$ as the minimum $m$ such that there exists a $(\epsilon,1/2)$-traditional-estimator for $\mathcal{C}$ and $\delta$. Since one can simulate a pricing estimator from a traditional estimator we have: \begin{equation} \textsc{PriceCplx}_{\mathcal{C},\theta}(\epsilon) \geq \textsc{SampleCplx}_{\mathcal{C},\theta}(\epsilon) \end{equation} The main question we ask is how big is this gap? I.e. how much harder is it to estimate a parameter from pricing queries as compared to samples. \paragraph{Practical Motivation and Relation to Bandits} In practice auctions are optimized by using a small fraction of traffic (say 1\%) to run experiments and the remaining 99\% runs the deployed production auction. After a period (say a few days) we use what we learned in the experimental slice to deploy in the main slice. Typically one does not care about the revenue in the experimental slice, but we do care about making that slice as small as possible. This translates directly to the goal of pricing query complexity: how to learn the most with the fewest possible queries? The alternative to run a small experimental slice to collect data in order to optimize the main mechanism is to apply a bandit algorithm on the full traffic. This may be appealing in theory, but it is not viable in practice where upper bounds on experimental traffic is a reality. For one, bandit algorithms would lead to a more unstable system for the bidders. Furthermore, only learning in a small (typically random) experimental slice minimizes incentives for bidders to strategize against the learning algorithm, since any given query will only be used to learn a price for the next day with a very small probability. This practical difference also explains how our objectives and guarantees differ from those of bandit learning for revenue optimization. While the bandit approach focuses on optimizing average revenue while learning, the sample/pricing complexity approach provides a guarantee on the loss of the final estimator with high probability, but doesn't care about the actual revenue obtained during the learning phase. This is very much in line with the literature on sample complexity. \paragraph{Our Results} We give matching upper and lower bounds (up to $\text{polylog}(1/\epsilon)$ factors) for the pricing complexity of various parameters and classes of distributions. Our results are summarized in Table~\ref{tab:results}. For each row of the table, we assume for the pricing complexity bounds that the parameter being estimated is in the range $[0,1]$. Since pricing queries only receive binary feedback, we need an initial range to be able to return any meaningful guarantee. It is interesting to compare our bounds with the sample complexity for the same regime. Interestingly in many important cases, such as estimating the mean of a normal distribution or the monopoly price of a regular distribution, pricing queries don't pose any significant handicap when one looks at the asymptotic regime. This is however not always the case: when computing the monopoly price of an MHR distribution, we establish a clear demarcation: we show a tight bound of $\widetilde{O}(1/\epsilon^2)$ for pricing complexity which is asymptotically higher than the known bound of $\widetilde{O}(1/\epsilon^{3/2})$ for sample complexity by Huang et al \cite{HMR18}. We also show a gap for computing the monopoly price for general distributions, while $\Omega(1/\epsilon^3)$ is required for pricing queries, $\widetilde{O}(1/\epsilon^2)$ is sufficient for value samples. \begin{table}[h] \centering \begin{tabular}{ |c|c|c|c| } \hline Parameter & Distribution & Pricing Complexity & Sample Complexity \\ \hline Median & General & $\tilde{O}(1/\epsilon^2)$, $ \Omega(1/\epsilon^2)$ & $O(1/\epsilon^2)$,$ \Omega(1/\epsilon^2)$ \\ Mean & Normal & ${O}(\sigma^2/\epsilon^2)$, $\Omega(\sigma^2/\epsilon^2)$ & $O(\sigma^2/\epsilon^2)$, $\Omega(\sigma^2/\epsilon^2)$ \\ CDF & General & $\tilde{O}(1/\epsilon^3)$, $\Omega(1/\epsilon^3)$ & $\tilde{O}(1/\epsilon^2)$, $\Omega(1/\epsilon^2)$ \\ CDF & Regular & $\tilde{O}(1/\epsilon^3)$, $\Omega(1/\epsilon^{2.5})$ & $\tilde{O}(1/\epsilon^2)$ \\ Monopoly Price & MHR & $\tilde{O}(1/\epsilon^2), \Omega(1/\epsilon^2)$ & $\tilde{O}(1/\epsilon^{1.5}), \Omega(1/\epsilon^{1.5})$ \\ Monopoly Price & Regular & $\tilde{O}(1/\epsilon^2)$ , $\Omega(1/\epsilon^{2})$ & $\tilde{O}(1/\epsilon^{2})$ \\ Monopoly Price & General & $\tilde{O}(1/\epsilon^3)$, $\Omega(1/\epsilon^3)$ & $\tilde{O}(1/\epsilon^2)$, $\Omega(1/\epsilon^2)$ \\ \hline \end{tabular} \caption{Our upper and lower bounds for various estimators and comparison with sample complexity. In each case, the pricing complexity bounds assume that the parameter being estimated is in $[0,1]$. $\sigma$ is the standard deviation of the normal distribution.} \label{tab:results} \end{table} \paragraph{Techniques: Mean and Median} As a warm up, we first study how to estimate the median of a distribution using pricing queries. The algorithm is a hybrid of binary search and the UCB algorithm. The algorithm both keeps a range $[\ell, r]$ that contains the median (as in binary search) and builds a confidence interval (like the UCB algorithm) to estimate the quantile of $p = (\ell + r)/2$. Whenever the confidence bound can safely separate the quantile of $p$ from $1/2$, a binary search step is performed. The algorithm requires very few queries to perform a binary search step that is far from the median, but starts requiring more and more as we approach the median. The algorithm is agnostic to $\epsilon$ and works in the streaming model: it keeps an estimate of the median through the execution that gets better as it receives more pricing query opportunities. Surprisingly, its performance matches what one could obtain from value samples. We then use the algorithm to estimate the mean of a normal distribution. Remarkably, we obtain the same guarantee of $O(\sigma^2/\epsilon^2)$ (up to constant factors) as the optimal algorithm that has access to sample values. We obtain a guarantee of $\tilde{O}(\sigma^2/\epsilon^2)$ without needing to know $\sigma$ at all. To obtain a bound of $O(\sigma^2/\epsilon^2)$ the algorithm needs to know $\sigma$; or if the algorithm knows only an upper bound $\bar{\sigma}$ on $\sigma$, we can obtain a guarantee of $O(\bar{\sigma}^2/\epsilon^2)$. \paragraph{Techniques: Monopoly Price} For the monopoly price our techniques are significantly more involved. At the heart of the analysis is a new property of regular distributions called \emph{relative flatness}, which is of potential independent interest. It says that if the revenue curve has roughly the same value at $4$ different equidistant points, it can't hide a point with very high revenue point in between those four points. This is not just a consequence of a single-peaked curve, as such curves can easily hide a high revenue point between four points of equal revenue. The concavity of the revenue curve in the quantile space is well known for regular distributions. The novelty is in finding the right property in the \emph{value space} to be used. Using this property we design an algorithm that keeps a list of subintervals of $[0,1]$ to explore. Unlike binary search we are not able to keep a single interval. Once the algorithm explores an interval it may discard it, but it may also break it into multiple subintervals and add them to the list. The relative flatness is put to use in efficiently discarding intervals that don't contain the monopoly price. We design a potential function to control the number of sub-intervals to guarantee we explore a small number of them. The argument is delicate: even the next subinterval to pick needs care; picking an arbitrary subinterval to process does not yield the desired bound. This algorithm obtains a bound of $\tilde{O}(1/\epsilon^2)$ for regular distributions. We then turn our attention to MHR distributions. For value samples, it is known that learning the monopoly price for MHR distribution is easier than learning the monopoly price of regular distributions. Surprisingly, this is no longer the case for pricing complexity. To prove this fact, we design two distributions such that no price is an $\epsilon$-approximation simultaneously for both distributions even though the distributions have very close c.d.f. and quantiles. We then use an information-theoretic argument to show that the sequence of bits obtained by the pricing queries for both distributions will be indistinguishable with fewer than $\Omega(1/\epsilon^2)$ queries. We do so by bounding the KL-divergence between the distribution of bits observed by running any algorithm on both distributions. \paragraph{Why Not Learn the CDF of the Whole Distribution?} Known results on sample complexity for revenue maximization typically use a variant of optimal reserve price of the empirical distribution. In the case of pricing queries, first, there is no clear notion of what the empirical distribution is. Second, even if one is tempted to learn the CDF of the entire distribution within an $\epsilon$ distance in Levy metric, we show that this is provably inferior (see Table~\ref{tab:results} for CDF Parameter) to the tight bounds we get. Our technique of quickly zooming into the right region of the distribution using the notion of relative flatness is crucial for getting tight bounds. \paragraph{Related Work} The work that is closest to ours is the sample complexity of single buyer, single item revenue maximization by Huang et al.~\cite{HMR18}. Surprisingly Huang et al.~\cite{HMR18} show that the number of samples required to estimate the monopoly price to obtain a $1-\epsilon$ approximation to revenue is even smaller than the number of samples required to estimate the optimal revenue. Our detailed comparison of pricing query complexity with the sample complexity of Huang et al. has already been presented, and, the pricing complexity often matches the already surprisingly small sample complexity. The literature on sample complexity has seen a lot of activity in the past decade. Particularly, in the single-parameter setting, starting with Elkind's work~\cite{Elkind07} on finite support auctions, there has been a lot of progress. Cole and Roughgarden~\cite{CR14} study the sample complexity of revenue maximization in single item settings with independent non-identical distributions, where a ``sample'' is an $n$-tuple when there are $n$ bidders in the auction. They give sample complexity as a polynomial in $n$ and $1/\epsilon$ when seeking to obtain a $1-\epsilon$ approximation to the optimal revenue. With this definition, in many settings the number of samples is not even a function of $n$. When one seeks a $1/4$ approximation, based on a generalization of Bulow and Klemperer's result~\cite{BK96} by Hartline and Roughgarden~\cite{HR09}, just a single sample would do. Fu et al.~\cite{fu2015randomization} shows that the revenue guarantees can be improved with randomization. When the distributions of the $n$ bidders are i.i.d., Dhangwatnotai et al.~\cite{DRY15} showed that poly($\epsilon$) samples are enough to get a $1-\epsilon$ approximation, and so is it in the case of unlimited supply (digital goods) setting as that can be boiled down to a single agent setting. Devanur et al.~\cite{DHP16} consider the single parameter setting where the buyer distributions are not in discrete categories, but in a continuum, represented as a signal in the hands of the auctioneer. The line of literature for single-parameter settings culminates with the work of Guo et al.~\cite{guo2019settling} which provides tight sample complexity for buyers with regular, MHR, or bounded values. \cite{hu2021targeting} further studies a targeting sample complexity model where for each buyer distribution, it is allowed to specify a fixed size of quantile range to sample from. Sample complexity results in multi-parameter settings are comparatively fewer. Morgenstern and Roughgarden~\cite{MR16} and Vasilis Syrgkanis~\cite{syrgkanis2017sample} study the sample complexity of learning simple auctions (item pricing, bundle pricing etc.) in multi-parameter settings via pseudo-dimension. Gonczarowski and Weinberg \cite{gonczarowski2018sample} obtains a polynomial sample complexity for up to $\epsilon$-optimal multi-item auctions for additive buyers with independent item values. Brustle et al. \cite{brustle2020multi} further extends the result to buyers with some specific types of correlated item values. Sample complexity of revenue-optimal item pricings was explored earlier by Balcan et al.~\cite{BBHM08}. Sample complexity of welfare-optimal item pricings was explored by Feldman et al.~\cite{FGL15} and Hsu et al.~\cite{HMRRV16}. Finally, we also note that pricing query complexity is different from sample complexity in PAC learning using threshold concepts i.e, the literature following the work of~\cite{valiant}, despite the resemblance in definitions. In PAC learning, the same concept may be used as a test on different samples. However, this is not the case in pricing complexity, here we never explicitly observe any sample. This means that the techniques and bounds for PAC learning are going to be closer to usual sample complexity results than to pricing complexity, as is borne out from the lower bounds. \section{Warmup: Estimating the Median and the Mean}\label{sec:gaussian} Before going to the technically more involved Section~\ref{sec:monopoly}, we begin with the estimation of the median and mean of distributions as a warmup. While the results in Section~\ref{sec:monopoly} are our main results, there are some nuances in this Section~\ref{sec:gaussian} as well, including the removal of log factor in Theorem~\ref{lm:norm}. \subsection{Median of a General Distribution} \label{sec:median-general} We start with one of the most basic problems in statistics: estimating the median of a distribution. Let $C$ be the class of all distributions with finite variance and median in $[0,1]$. When we are estimating the median of a distribution $\mathcal{D}$ with cdf $F$, a natural loss function is $\L(\theta,\hat\theta)=|F(\theta)-F(\hat\theta)|$. Then we can bound the pricing query complexity as follows: \begin{theorem}\label{thm:medianub} Let $\mathcal{C}$ be a class of distributions over $\mathbb{R}$ with median in $[0,1]$. Define: $$a_F:=\sup_{F\in\mathcal{C}}\log{\textstyle|F^{-1}(\frac{1}{2}+\frac{\epsilon}{3})-F^{-1}(\frac{1}{2}-\frac{\epsilon}{3})|^{-1}}.$$ We have \[\textsc{PriceCplx}_{\mathcal{C},\theta}(\epsilon) \leq \tilde{O}(1/\epsilon^2)a_F\log a_F.\] \end{theorem} Observe that the bound depends on a parameter $a_F$ which measures how concentrated the function is around the median. For example, if there is an $O(\epsilon)$ probability mass exactly at the median then $a_F = \infty$. In such case, in order to obtain $\L(\theta,\hat\theta)\leq O(\epsilon)$ we would need to find the the median \emph{exactly} which is impossible only using pricing queries. Thus the dependence on $a_F$.\\ The bound in Theorem \ref{thm:medianub} is achieved by a combination of binary search and the UCB algorithm, described in Algorithm \ref{alg:binary_ucb}. The algorithm starts with a range $[0,1]$ of the potential median, and repeatedly prices at the middle point $p$ of the range. Since the algorithm obtains only binary feedback, it needs to keep sending pricing queries at this point until it has enough information to decide with high probability whether $Q(p) = 1- F(p) < 1/2$ or $Q(p) > 1/2$. To do that we keep an estimate of the quantile $Q(p)$ based on the binary feedback together with a confidence interval for this estimate. Once $1/2$ leaves this confidence interval we know with high probability on which side of $p$ the median is, and we can do a binary search step. After the binary search step, we restart the UCB step. \begin{algorithm}[htb] \caption{Binary search algorithm that returns $p^*$ with $|Q(p^*)-\frac{1}{2}|\leq\epsilon$ with prob $1-\delta$ } \label{alg:binary_ucb} {Initialize $\ell =0$, $r=1$, $p=1/2$; $n=0$, $k=0$, $p^* =1/2$, $\epsilon^* = 1$\; \For {t=1,2,3... (each new arriving query)} { Increment number of samples $n = n+1$ \; Price at $p$, if sold, increment $k= k+1$ \; If $\epsilon_p = 18\sqrt{\log(t/\delta)/ n} < \epsilon^*$ update $p^* = p, \epsilon^* = \epsilon_p$ \; \If {$\abs{1/2 - k/n} > 12\sqrt{\log(t/\delta)/ n}$ (i.e. $1/2$ is outside the confidence bound)} { If $k/n < 1/2$, update $r = p$. Otherwise, $\ell=p$\; Update $k=n = 0$ (reset the counters) and set $p =(\ell+r)/2$\; } \textrm{Return} $p^*$ if $\epsilon^*\leq\epsilon$\; } } \end{algorithm} One important feature of our algorithm is that it uses no information about $\epsilon$ other than as a stopping condition. In fact, one can think of the algorithm in the \emph{streaming model}: it processes a stream of `pricing opportunities' and updates a constant-size set of parameters in each step. At each point in time, the algorithm keeps an estimate $p^*$ together with a confidence bound $\epsilon^*$, that keeps getting better as the algorithm receives more data. The analysis of the pricing complexity is deferred to Section~\ref{sec:proof-median-general}. \subsection{Mean of a Normal Distribution} \label{sec:mean-normal} We now apply this idea to estimate the mean of a normal distribution using pricing queries. The idea can be extended to other families of parametric distributions, but we focus here on normals to allow a crisp comparison with sample complexity. Our main result is the following price complexity upper bound, which exactly matches the well known sample complexity lower bound of $\Omega(\sigma^2/\epsilon^2)$: \begin{theorem}\label{lm:norm} Let $\mathcal{C}_{\sigma} = \left\{ \mathcal{N}(\mu, \sigma) \text{ s.t. } \mu \in [0,1]\right\}$ be the class of normal distributions with variance $\sigma^2$ with the loss $\L(\theta, \hat \theta) = \abs{\theta - \hat \theta}$. Then the pricing complexity of computing the mean is: $$\textsc{PriceCplx}_{\mathcal{C}_{\sigma},\mu}(\epsilon)= O(\sigma^2/\epsilon^2).$$ \end{theorem} \begin{proof} A direct application of Theorem \ref{thm:medianub} leads to an algorithm with $\tilde{O}(\sigma^2/\epsilon^2)$ pricing query complexity. To estimate a point $\hat \theta$ such that $\abs{\hat \theta - \mu} \leq \epsilon$ for a distribution with mean $\mu$, it is enough to find a point $\hat\theta$ such that $\abs{F(\hat\theta) - F(\mu)} \leq \epsilon/\sigma$. For a normal distribution the parameter $a_F$ in Theorem \ref{thm:medianub} is $a_F = O(\log 1/(\epsilon \cdot \sigma))$. If $\sigma \geq \epsilon$, the statement of the theorem directly yields a $\tilde{O}(\sigma^2/\epsilon^2)$. If $\sigma < \epsilon$ on the other hand, all the points $p \notin [\mu-\epsilon, \mu+\epsilon]$ are such that $\abs{Q(p) - 1/2} = \Omega(1)$ and hence the UCB step in Algorithm \ref{alg:binary_ucb} takes a constant number of queries at each of those points. Hence in $O(\log (1/\epsilon))$ we query a point that is $\epsilon$-close to the mean. This algorithm is robust in the sense that it doesn't require us to know the variance as it is only used in the analysis.\\ Assume for now that we know exactly what the variance $\sigma^2$ is. If we allow the algorithm to use the exact value of the variance $\sigma^2$, we can improve the guarantee from $\tilde{O}(\sigma^2/\epsilon^2)$ to $O(\sigma^2/\epsilon^2)$. We can apply the following procedure: \begin{itemize} \item Use Algorithm \ref{alg:binary_ucb} with $\epsilon = 1/4$ to find a point $p$ with quantile $Q_{\mu, \sigma}(p) \in [1/4, 3/4]$. \item Using $O(\sigma^2/\epsilon^2)$ pricing queries, find an estimate $\hat q$ such that $\abs{\hat q - Q_{\mu,\sigma}(p)} \leq \epsilon/\sigma$. \item Solve the equation $\hat q = Q_{\hat \mu, \sigma}(p)$ to find an estimate $\hat \mu$ for the mean. \end{itemize} Note that since $Q_{\hat \mu, \sigma}(p) = Q_{0,1}(\frac{p-\mu}{\sigma})$ where $Q_{0,1}$ is the quantile function for the standard Gaussian, the solution to the equation in last step is: $$\hat{\mu} = p - \sigma \cdot Q_{0,1}^{-1}(\hat q)$$ Since the derivatives of $Q_{0,1}^{-1}$ are bounded in $[1/4, 3/4]$ an error of $\epsilon/\sigma$ in the estimation $\hat{q}$ leads to an error of $O(\epsilon/\sigma)$ in $Q_{0,1}^{-1}(\hat q)$. Hence $\abs{\mu - \hat \mu} \leq O(\epsilon)$.\\ \end{proof} We can relax the assumption that we know $\sigma$ exactly and assume we only know an upper bound $\bar \sigma$. The proof is deferred to Section~\ref{sec:proof-mean-normal}. \begin{corollary}\label{cor:median-ub} Let $\bar\mathcal{C}_{\bar\sigma} = \left\{ \mathcal{N}(\mu, \sigma) \text{ s.t. } \mu \in [0,1],\ \sigma\leq\bar\sigma\right\}$ be the class of normal distributions with variance at most $\bar\sigma^2$ with the loss $\L(\theta, \hat \theta) = \abs{\theta - \hat \theta}$. Then the pricing complexity of computing the mean is: $$\textsc{PriceCplx}_{\bar\mathcal{C}_{\bar\sigma},\mu}(\epsilon)= O(\bar\sigma^2/\epsilon^2).$$ \end{corollary} \section{Estimating the Monopoly Price} \label{sec:monopoly} In this section, we focus on estimating the monopoly price (i.e., the revenue optimal price or the Myerson price) and measure our loss via the natural metric of the revenue gap between the true revenue and that obtained by our estimated price: $\L(\theta; \hat \theta) = \abs{\textsc{Rev}_\mathcal{D}(\theta) - \textsc{Rev}_\mathcal{D}(\hat \theta)}, \text{ where } \textsc{Rev}_\mathcal{D}(p) := \mathbb{E}_{v \sim \mathcal{D}} [p \cdot \mathbf{1}\{v \geq p\}]$, where $\theta$ and $\hat \theta$ are the true and estimated monopoly prices. An important tool in this section is the following lemma, which shows that to estimate the quantile $Q(p)=1-F(p)$ of price $p$ with additive error $\epsilon$, it suffices to use $\tilde{O}(\frac{1}{\epsilon^2})$ pricing queries on $p$. The proof is relatively standard, and is deferred to Section~\ref{sec:proof-monopoly}. \begin{lemma}\label{lem:repeatprice} For any value distribution $F$ supported in $[0,1]$ and value $p$, there is an algorithm $\textsf{EQ}_F(p,\epsilon,\delta)$ that makes $m=\tilde{O}(\frac{1}{\epsilon^2}\log\frac{1}{\delta})$ pricing queries and with probability $>1-\delta$ returns an estimate $\hat{q}$ for the quantile $Q(p)=1-F(p)$ such that $\abs{\hat q - Q(p)} < \epsilon$. \end{lemma} \subsection{Regular Distributions}\label{sec:regular} Firstly we study the class of regular distributions $\mathcal{C}_{\textsc{REG}}$, supported on $[0,1]$. Regular distributions are the class of distributions for which the revenue curve in quantile space $\hat R(q) = q \cdot F^{-1}(1-q)$ is concave. This in particular implies that the revenue curve in the space of values/prices $\textsc{Rev}(p)=p(1-F(p))$ is single-peaked. This class includes many important distributions such as uniform, exponential and all log-concave distributions.\\ In the heart of our algorithm will be the following lemma on regular distributions: \begin{lemma}[Relative Flatness of Regular Distributions]\label{lem:myerson-average} Let $\textsc{Rev}$ be the revenue curve of a regular distribution. Consider four equidistant\footnote{In the sense that $p_i = (p_4i + p_1(3-i))/3$ for $i=2,3$.} values $p_1<p_2<p_3<p_4=cp_1$ in $[0,1]$ and let $\textsc{Rev}_{\max}$ and $\textsc{Rev}_{\min}$ be the maximum and minimum value of the revenue curve at those four points. Then if $\textsc{Rev}_{\min} \geq \textsc{Rev}_{\max}-\epsilon$, for some $\epsilon>0$, then for any $p\in[p_1,p_4]$, $\textsc{Rev}(p)\leq \textsc{Rev}_{\max}+O(c\epsilon)$. \end{lemma} The geometric intuition is that is the curve is reasonably flat at four equidistant points, then it should be reasonably flat within most of that interval. Note that this is not generally true for any single-peaked function, as the peak could be easily hiding between any of those points. See Figure \ref{fig:flatness}. The proof (deferred to Section~\ref{sec:proof-regular}) will strongly use the fact that the revenue curve is concave when looked at in the quantile space. From this point on, the only two facts we will use about regular distributions is the fact it is single-peaked and the relative flatness lemma. \begin{figure}[h] \centering \begin{tikzpicture}[scale=1] \draw (0,0) -- (5,0); \node[circle,fill,inner sep=1pt] at (1,.45) {}; \node[circle,fill,inner sep=1pt] at (2,.48) {}; \node[circle,fill,inner sep=1pt] at (3,.5) {}; \node[circle,fill,inner sep=1pt] at (4,.5) {}; \draw (1,-.1)--(1,.1); \draw (2,-.1)--(2,.1); \draw (3,-.1)--(3,.1); \draw (4,-.1)--(4,.1); \draw [line width=1pt, color=blue] plot [smooth] coordinates { (0,.2) (1,.45) (2,.48) (2.2,1) (2.5,2) (2.8,1) (3,.5) (4,.5) (5,.2)}; \end{tikzpicture} \caption{The relative flatness lemma shows that the revenue curve of a regular distribution can't hide a very high revenue point in a region that appears flat when measured with respect to $4$ equidistant points. For example, the curve in the figure can't be the revenue curve of a regular distribution in the value space.} \label{fig:flatness} \end{figure} With that we can prove our main result: \begin{theorem}\label{thm:regular} Let $\mathcal{C}_{\textsc{REG}}$ be the class of regular distributions supported in $[0,1]$ and let $\theta$ be the monopoly price. Then, $$\textsc{PriceCplx}_{\mathcal{C}_{\textsc{REG}},\theta}(\epsilon) = \tilde{O}(1/\epsilon^2).$$ \end{theorem} In the next section we will show this is tight even for the subclass of MHR distributions.\\ Now we describe the algorithm achieving that bound. The main data structure the algorithm will keep is a list $L$ which will contain intervals with disjoint interiors in the revenue curve that still need to be explored. For each of the endpoints of those intervals, we will keep an $\pm \epsilon$-estimate $\hat{q}(p)$ of its quantile $Q(p) = 1-F(p)$ obtained by the algorithm in Lemma \ref{lem:repeatprice} with success probability $\delta=\epsilon^2$ together with a revenue estimate: $$\widetilde{\rev}(p) = p \cdot \hat{q}(p).$$ In the algorithm, we will show that we only price at $\tilde{O}(1)$ different prices, thus by union bound the overall success probability is at least $\frac{2}{3}$ for small $\epsilon$. We initialize the algorithm with $L = \{[0,1]\}$. While the list is non-empty, we will process it by removing an interval from it and analyzing it. In the process of analyzing it, we will query some of its points. Depending on the the outcome of those queries, we may decide to add subintervals of $L$ back to the list for further analysis. We stop whenever the list is empty. At that point, we return the point queried in the process with largest estimated revenue. We now describe how to process each interval. At every round, we remove the second leftmost interval $[\ell, r]$ from the list whenever the list has more than one interval. If not, we remove the only interval from the list. We process this interval by dividing it in $4$ pieces of the same length and querying the breakpoints $p_i = (i \ell + (4-i) r)/4$ for $i = 1,2,3$ for the approximate quantile and construct a revenue estimate $\widetilde{\rev}$ for each. We define the following quantities for the interval: $$\textsc{Rev}_{\max} = \max_{p \in \{\ell, p_1, p_2, p_3, r\}} \textsc{Rev}(p), \qquad \widetilde{\rev}_{\max} = \max_{p \in \{\ell, p_1, p_2, p_3, r\}} \widetilde{\rev}(p) $$ Now we proceed according to one of seven cases:\\ \noindent\emph{Case 1:} If $r - \ell < \epsilon$ we discard the interval. In that case, we don't need to further analyze the interval since no point $p\in[\ell,r]$ can generate much better revenue than just pricing at $\ell$ since: \[\textsc{Rev}(\ell)=\ell Q(\ell)\geq \ell Q(p)\geq (p-\epsilon)Q(p)\geq pQ(p)-\epsilon=\textsc{Rev}(p)-\epsilon.\] \noindent\emph{Case 2:} If $\min_{p \in \{\ell, p_1, p_2, p_3, r\}} \widetilde{\rev}(p) \geq \widetilde{\rev}_{\max} - 2\epsilon$. In that case, we add $[\ell,p_1]$ to the list. At this point, since $r\leq 4p_1$, the relative flatness lemma guarantees us that no point in $[p_1, \ell]$ can be much better than the points that were already queried.\\ \noindent\emph{Case 3:} If $\min_{p \in \{p_1, p_2, p_3, r\}} \widetilde{\rev}(p) \geq \widetilde{\rev}_{\max} - 2\epsilon$ but $\widetilde{\rev}(\ell) < \widetilde{\rev}_{\max} - 2\epsilon$ we remove all intervals to the left of $\ell$ from the list and add $[\ell, p_1]$ and $[p_1,r]$. In this case, we know that: $$\textsc{Rev}(\ell) \leq \widetilde{\rev}(\ell) + \epsilon < \widetilde{\rev}_{\max}-\epsilon \leq \textsc{Rev}_{\max}$$ and hence the revenue in $\ell$ is suboptimal and the optimal point $p^*$ is to the right of $\ell$. Here we are only using the fact that the revenue function is single-peaked.\\ All the remaining cases follow from similar arguments based on the single-peakedness of the revenue function:\\ \noindent\emph{Case 4:} If $\min_{p \in \{\ell, p_1, p_2, p_3\}} \widetilde{\rev}(p) \geq \widetilde{\rev}_{\max} - 2\epsilon$ but $\widetilde{\rev}(r) < \widetilde{\rev}_{\max} - 2\epsilon$ we remove all intervals to the right of $r$ from the list and add $[\ell, p_3]$ and $[p_3,r]$. \\ \noindent\emph{Case 5:} If $\min_{p \in \{p_1, p_2, p_3\}} \widetilde{\rev}(p) \geq \widetilde{\rev}_{\max} - 2\epsilon$ but $\widetilde{\rev}(\ell), \widetilde{\rev}(r) < \widetilde{\rev}_{\max} - 2\epsilon$ then remove all intervals from the list and add back $[\ell, p_1]$, $[p_1, p_3]$ and $[p_3, r]$. \\ \noindent\emph{Case 6:} If $\widetilde{\rev}(\ell), \widetilde{\rev}(p_1)< \widetilde{\rev}_{\max} - 2\epsilon$ we remove all intervals to the left of $\ell$ from the list and add $[p_1,r]$ to the list. \\ \noindent\emph{Case 7:} If $\widetilde{\rev}(r), \widetilde{\rev}(p_3) <\widetilde{\rev}_{\max} - 2\epsilon$ we remove all intervals to the right of $r$ from the list and add $[\ell,p_3]$ to the list.\\ Observe that by single-peakedness those are the only possible cases. The algorithm always finishes since it replaces intervals by other intervals that are smaller by at least a constant factor and once intervals become of size $\epsilon$, they are discarded. What remains to be done is to analyze the query complexity of the algorithm: \begin{proof}[Proof of Theorem \ref{thm:regular}] Now we argue the algorithm described performs at most $\tilde{O}(1/\epsilon^2)$ queries. To see that, we first claim that there are at most three intervals in the candidate list at any given time. We prove this claim by induction over the number of iterations. Suppose that after the $t$-th iteration there are $k\leq 3$ intervals in $list$. We argue that after the $(t+1)$-th iteration, there are still at most $3$ intervals in the list. Observe that in Case 1, 2, 6, 7, the number of intervals does not increase. In Case 5, the number of intervals become 3 no matter how many intervals were in the list. In Case 3 or 4, the number of intervals increase by at most 1, so the number of intervals in the list becomes at most $3$ if $k\leq 2$. The only remaining case is that the algorithm runs through Case 3 or 4, with $list$ containing $k=3$ intervals at the beginning of the iteration. Since the algorithm picks the second leftmost interval from $list$, the algorithm picks the middle one of the intervals (sorted according to the left boundary). Notice that in Case 3, the leftmost interval is also removed in this iteration; in Case 4, the rightmost interval is also removed in this iteration. Thus after the algorithm runs through Case 3 and Case 4, no matter how many intervals are in the list at the beginning of the iteration, at most 3 intervals remain in the list after the iteration. This finishes the proof of the claim. After each iteration, either one of the interval of length $d$ splits to multiple intervals of length at most $\frac{3}{4}d$ each, with some other intervals getting removed; or one of the interval of length $d$ shrinks to a new interval of length at most $\frac{3}{4}d$ (recall that our five prices $\ell,p_1,p_2,p_3,r$ chosen in the algorithm are equidistant). Therefore if we record the lengths of the three intervals to be $d_1\geq d_2\geq d_3$, then either $d_1$ decreases to a fraction of at most $\frac{\sqrt{3}}{2}$; or $d_1$ does not increase, and $d_2$ decreases to a fraction of at most $\frac{\sqrt{3}}{2}$; or $d_1,d_2$ do not increase, and $d_3$ decreases to a fraction of at most $\frac{3}{4}$. For $i=1,2,3$, let $a_{i}=0$ if $d_i=0$, and $a_{i}=\lceil\log_{2/\sqrt{3}}\frac{d_i}{\epsilon}\rceil$ if $d_i>0$. Then at each step, either $a_1$ decreases by at least 1; or $a_2$ decreases by at least 1 while $a_1$ does not increase; or $a_3$ decreases by at least 1. Let $n=1+\lceil\log_{2/\sqrt{3}}\frac{1}{\epsilon}\rceil$, and denote a potential function $\phi(d_1,d_2,d_3)=n^2a_1+na_2+a_3$. Then at each step, since $a_i\leq n-1$, $\phi$ decreases by at least 1. As at the beginning of the algorithm $\phi(d_1,d_2,d_3)=\phi(1,1,1)\leq n^3$, we have the total number of iterations is at most $n^3=O(\log^3\frac{1}{\epsilon})=\tilde{O}(1)$. Since in each iteration the query complexity is $\tilde{O}(\frac{1}{\epsilon^2})$, the total query complexity of the algorithm is $\tilde{O}(\frac{1}{\epsilon^2})$. \end{proof} \subsection{MHR Distributions}\label{sec:mhr} We complement the above result by providing a lower bound on the pricing complexity for estimating the monopoly price for MHR distributions. \begin{theorem}\label{thm:mhrlb} Let $\mathcal{C}_{\textsc{MHR}}$ be the class of Monotone Hazard Rate distributions supported in $[0,1]$ and let $\theta$ be the monopoly price. Then $$\textsc{PriceCplx}_{\mathcal{C}_{\textsc{MHR}},\theta}(\epsilon) = \Omega(1/\epsilon^2).$$ \end{theorem} To prove lower bound results for the pricing complexity for estimating the monopoly price, a key observation is that for two distributions with almost identical cumulative density functions, it's very hard to distinguish them with pricing queries. \begin{lemma}\label{lem:query-complexity} For two value distributions $D$ and $D'$, if $\frac{1}{1+\epsilon}\leq\frac{Q_D(v)}{Q_{D'}(v)},\frac{F_D(v)}{F_{D'}(v)} \leq (1+\epsilon)$ for every $v\in[0,1]$, then $\Omega(\frac{1}{\epsilon^2})$ pricing queries are needed to distinguish the two distributions with probability $>1-\delta$. \end{lemma} The proof of the lemma is technically involved, and is deferred to Section~\ref{sec:proof-mhr}. We first show that the two distributions have small KL-divergence, then use Pinsker's inequality from information theory to bound the pricing complexity. A similar approach was also used in the literature \cite{HMR18}. Thus to prove the lower bound on the pricing complexity of estimating the monopoly price for MHR distributions, we only need to find two MHR distributions with close cumulative density functions satisfying the above lemma. Such distributions indeed exist, and we defer the construction to Section~\ref{sec:proof-mhr}. \subsection{General Distributions}\label{sec:general-distribution} We now provide the pricing complexity for the class of general distributions. \begin{theorem}\label{thm:general-distribution} Let $\mathcal{C}_{\textsc{ALL}}$ be the class of all value distributions on $[0,1]$ and $\theta$ be the monopoly. Then $$\textsc{PriceCplx}_{\mathcal{C}_{\textsc{ALL}},\theta}(\epsilon)= \tilde{\Theta}(1/\epsilon^3).$$ \end{theorem} The proof idea is as follows. On one hand, we can price at all multiples of $\epsilon$ to get an estimated revenue for each price. We can use $\tilde{O}(\epsilon^{-2})$ pricing queries to get an $\epsilon$ accuracy at each price, thus $\tilde{O}(\epsilon^{-3})$ queries can guarantee us a price that estimates the optimal revenue with error $O(\epsilon)$. On the other hand, for a distribution with the same revenue on all but one multiples of $\epsilon$, suppose that pricing at $i\epsilon$ gives a higher revenue than any $j\epsilon$ with $j\neq i$. Any pricing algorithm needs to price at every multiple of $\epsilon$ to determine the exact value of $i$, while $\Omega(\epsilon^{-2})$ queries are needed for accuracy. Thus $\Omega(\epsilon^{-3})$ queries are necessary for the general class of distributions. The detailed proof is deferred to Section~\ref{sec:proof-general}. \subsection{Discussion on Learning the Entire Regular Distribution} The algorithms with optimal sample complexity designed by Huang, Mansour and Roughgarden \cite{HMR18} work by using the samples to build an empirical distribution and then choosing the optimal reserve price with respect to the empirical distribution. We know by the DKW inequality that after $\tilde{O}(1/\epsilon^2)$ samples, the empirical distribution will be $\epsilon$-close to the real distribution in Kolmogorov distance with high enough probability. Hence for a bounded distribution, there is no asymptotic gap between the sample complexity of learning the monopoly price and learning the entire CDF. Is there a similar phenomenon for pricing queries? In Section~\ref{sec:regular}, we discussed how to \textit{directly} learn the optimal monopoly prices with $\epsilon$ error for regular distributions using $\tilde{O}(1/\epsilon^2)$ pricing queries. Using these many pricing queries, we may wonder if we can get a full picture of the distribution: is it possible to learn a distribution within a small distance to the true distribution? There are multiple metrics measuring the distance of two distributions. Metrics that are measured by the pointwise difference in cumulative density functions like Kolmogorov distance\footnote{Two distributions with cumulative density functions $F$ and $G$ are within $\epsilon$ Kolmogorov distance, if $F(x)-\epsilon\leq G(x)\leq F(x)+\epsilon$ for every $x\in\mathbb{R}$.} are inappropriate when we only have pricing access to the distribution. For example, if a distribution is defined by a deterministic value in $[0,1]$, pricing queries cannot determine that specific value. Instead, we measure the distance of two distributions by Levy distance\footnote{Two distributions with cumulative density functions $F$ and $G$ are within $\epsilon$ Levy distance, if $F(x-\epsilon)-\epsilon\leq G(x)\leq F(x+\epsilon)+\epsilon$ for every $x\in\mathbb{R}$.}. Observe that if two distributions $F$ and $G$ are within $\epsilon$ Levy distance, then for any price $p\in[0,1]$, $\textsc{Rev}_F(p-\epsilon)\geq \textsc{Rev}_G(p)-O(\epsilon)$. This means that if $p_F$ is the optimal monopoly price for $F$, then $p_F-\epsilon$ is a good price for $G$ that achieves near-optimal revenue (with $O(\epsilon)$ revenue loss). Thus, learning a distribution within a small Levy distance is a harder problem than learning the optimal monopoly price. For a general distribution in $[0,1]$, the pricing query complexity for learning an approximate distribution is $\tilde{\Theta}(\epsilon^{-3})$, which is the same as the complexity for learning the optimal monopoly price, as we can estimate the quantile of each multiple of $\epsilon$ using $\tilde{O}(\epsilon^{-2})$ pricing queries. What about regular distributions? Can we also find a regular distribution within $O(\epsilon)$ Levy distance using only $\tilde{O}(1/\epsilon^2)$ pricing queries? We answer the question negatively by showing that $\Omega(1/\epsilon^{2.5})$ pricing queries are required. This in particular shows that our zooming procedure based on the relative flatness lemma is necessary to obtain optimal pricing query complexity bounds. This also provides another scenario (other than learning the monopoly price for an MHR distribution) where there is an asymptotic gap between the pricing query complexity and the sample complexity (which is $O(1/\epsilon^2)$ by DKW inequality). \begin{theorem}\label{thm:regular-levy-pricing} Let $\mathcal{C}_{\textsc{REG}}$ be the class of regular distributions supported in $[0,1]$ and let $\theta$ be the true distribution\footnote{The distance metric $|\theta-\theta'|$ of two distributions $\theta$ and $\theta'$ is measured by Levy distance.}. Then $$\textsc{PriceCplx}_{\mathcal{C}_{\textsc{REG}},\theta}(\epsilon) = \Omega(1/\epsilon^{2.5}).$$ \end{theorem} \begin{proof} Let $D^*$ be the uniform distribution on $[0,1]$. In other words, the density function $f$ of $D^*$ satisfies $f(v)=1$ for every $v\in[0,1]$. For any $x\in[0.1,0.9]$, let $D_x$ be the distribution with the following density function $f_x$: \begin{equation*} f_x(v) = \left\{\begin{array}{lr} 1, & \text{if } v\in[0,x)\cup(x+4\sqrt{\epsilon},1];\\ v-x+1, & \text{if } v\in[x,x+\sqrt{\epsilon}];\\ -v+x+1+2\sqrt{\epsilon}, & \text{if } v\in(x+\sqrt{\epsilon},x+3\sqrt{\epsilon});\\ v-x-4\sqrt{\epsilon}+1, & \text{if } v\in[x+3\sqrt{\epsilon},x+4\sqrt{\epsilon}].\\ \end{array}\right. \end{equation*} Intuitively, $D_x$ is obtained by perturbing the uniform distribution $D^*$ in a small interval $[x,x+4\sqrt{\epsilon}]$. In that interval, $f_x(v)$ linearly increases from $1$ to $1+\sqrt{\epsilon}$, then decreases gradually to $1-\sqrt{\epsilon}$, finally back to $1$. Observe that distribution $D_x$ is regular since Myerson's virtual value $\phi_x(v)=v-\frac{1-F_x(v)}{f_x(v)}$ is increasing even when $f_x(v)$ decreases. Note: the derivative of $\phi_x$ is $\phi_x’(v)=2+\frac{(1-F_x(v))f_x’(v)}{f_x^2(v)}$. The density of $D_x$ satisfies $1-\sqrt{\epsilon}\leq f_x(v)\leq 1+\sqrt{\epsilon}$ and $-1\leq f_x’(v)\leq 1$, thus $\phi_x’(v)>0$ when $\epsilon$ is small enough, which means $\phi_x(v)$ is monotone increasing. Now we analyze the number of pricing queries needed for distinguishing $D^*$ and $D_x$. The cumulative density function of $D_x$ is \begin{equation*} F_x(v) = \left\{\begin{array}{lr} v, & \text{if } v\in[0,x)\cup(x+4\sqrt{\epsilon},1];\\ v+\frac{(v-x)^2}{2}, & \text{if } v\in[x,x+\sqrt{\epsilon}];\\ v+\epsilon-\frac{(x+2\sqrt{\epsilon}-v)^2}{2}, & \text{if } v\in(x+\sqrt{\epsilon},x+2\sqrt{\epsilon});\\ v+\epsilon-\frac{(v-x-2\sqrt{\epsilon})^2}{2}, & \text{if } v\in[x+2\sqrt{\epsilon},x+3\sqrt{\epsilon});\\ F(v)=v+\frac{(x+4\sqrt{\epsilon}-v)^2}{2}, & \text{if } v\in[x+3\sqrt{\epsilon},x+4\sqrt{\epsilon}].\\ \end{array}\right. \end{equation*} Observe that for any $v\in[x,x+4\sqrt{\epsilon}]$, $v\leq F_x(v)\leq v+\epsilon$; for any $v\in[0,x)\cup(x+4\sqrt{\epsilon},1]$, $F_x(v)=v$. This means that the cdf $F_{x}$ of distribution $D_x$ differs from the cdf $F^*$ of uniform distribution $D^*$ by at most an additive $\epsilon$ in value range $[x,x+4\sqrt{\epsilon}]$; for $v$ being out of the range, $F_{x}(v)=F^*(v)=v$. Thus for $x\in[0.1,0.9]$, $\frac{F_{x}(v)}{F^*(v)}=1+O(\epsilon)$ for every $v\in[0,1]$. For quantile functions $Q_x(v)=1-F_x(v)$ and $Q^*(v)=1-F^*(v)$, similar results hold: $\frac{Q_{x}(v)}{Q^*(v)}=1-O(\epsilon)$ for every $v\in[0,1]$. Thus $\Omega(\epsilon^{-2})$ pricing queries are necessary due to Lemma~\ref{lem:query-complexity}. Furthermore, the queries must be in $[x,x+4\sqrt{\epsilon}]$, as $Q_{D_x}$ and $Q_{D^*}$ are identical outside of $[x,x+4\sqrt{\epsilon}]$, which means querying outside of $[x,x+4\sqrt{\epsilon}]$ gives no information. For any $x\in[0.1,0.9]$, to distinguish $D_x$ and $D^*$, $\Omega(\epsilon^{-2})$ pricing queries in $[x,x+4\sqrt{\epsilon}]$ are necessary due to Lemma~\ref{lem:query-complexity}. Now consider the following $\Omega(\epsilon^{-0.5})$ distributions: $D^*$, $D_{0.1}$, $D_{0.1+4\sqrt{\epsilon}}$, $D_{0.1+8\sqrt{\epsilon}}$, $\cdots$, $D_{0.9-8\sqrt{\epsilon}}$, $D_{0.9-4\sqrt{\epsilon}}$. To distinguish all these distributions, $\Omega(\epsilon^{-2})$ queries are necessary in every interval $[x,x+4\sqrt{\epsilon}]$, thus $\Omega(\epsilon^{-2.5})$ queries in total are necessary. Notice that any two distributions $D_x$ and $D^*$ are at least $\frac{\epsilon}{2}$-far apart in Levy distance because, $F_x(x+2\sqrt{\epsilon})=x+2\sqrt{\epsilon}+\epsilon=F^*(x+2\sqrt{\epsilon}+\epsilon/2)+\epsilon/2$. To learn a distribution that is within $\frac{\epsilon}{4}$ Levy distance from the true distribution, we need to be able to distinguish all those distributions. To summarize, even in the class of regular distributions, $\Omega(\epsilon^{-2.5})$ pricing queries are necessary for learning a distribution within $\frac{\epsilon}{4}$ Levy distance (thus also $\epsilon$ Levy distance). \end{proof}
{'timestamp': '2021-11-09T02:30:01', 'yymm': '2111', 'arxiv_id': '2111.03158', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03158'}
arxiv
\section{COVID-19 datasets}\label{sec:data} According to the aim of this paper, we used the screening data of daily new cases and the number of the total amount of positive cases of SARS CoV-2 according to three countries in different phases of an epidemic outbreak. For each country, we considered the data in a time window that starts about 15 days before the adoption of restrictive measures and the sources of the data are described in the Appendix. At the time of writing, the United States of America (US) was in the growing phase of the epidemic outbreak with an increasing trend of new cases. In the US every single state could decide the need to adopt stay at home measures. In those states that adopted restrictions, we registered different starting dates: the earliest state was Puerto Rico (March 15, 2020), followed by California (March 19, 2020) and New York (March 20, 2020) where the highest increase of new cases was subsequently recorded. Every single state could adopt a different and inhomogeneous panel of restrictive measures and in some States, as Arkansas, Iowa, Nebraska, and North Dakota, the local government never issued stay-at-home orders \citep{Lyu:2020}. Data were analyzed from March 4, 2020, to April 27, 2020, for a total of 55 days of observation. At the end of the considered period, we reported 820,514 current positive cases, 56,259 deaths, and a total of 988,197 confirmed cases nationwide. Italy was a country in the middle phase where a first stabilization of the SARS-CoV-2 incidence was reported after the restriction measure, and, at the time of writing, we observed the beginning of a decreasing trend. The Italian Government adopted a national home lockdown restriction on March 9, 2020, for all the population followed by more severe measures on March 11, and ordered all nonessential businesses to close on March 22. Data were analysed from February 23, 2020, to April 28, 2020, for a total of 66 daily observations. At the end of the considered period, we reported 105,813 current positive cases, 26,977 deaths, and a total of 199,414 confirmed cases. Finally, Iceland was a country in the ending phase, where after a stabilization, the incidence of new cases was going down, and the current epidemic outbreak was probably going to the end. The Iceland government adopted stricter measures to slow down the spread of SARS-CoV-2 on March 16, 2020, with an active searching strategy of new cases that lead to perform oropharyngeal swabs to about 10\% of the entire population. We considered data from February 29, 2020, to April 27, 2020, for a total of 59 days of observation. At the end of the considered period, we reported 158 current positive cases, 10 deaths, and a total of 1,792 confirmed cases. \section{Discussion}\label{sec:discussion} International health organizations recommend to implement public health and social measures to slow or stop the spread of SARS-CoV-2, reaching the full engagement of all members of society \citep{who2020}. Countries have adopted different public health and social measures depending on the local specific historical evolution of the SARS-CoV-2 pandemic and on their health system capacity. Our analysis considers data of three countries, the US, Italy and Iceland which have, on one side, different geographic and demographic characteristics and, on the other one, as many dissimilar approaches in terms of public health policies and restrictive measures concerning the on-going epidemic. Our proposal allows us to estimate an epidemiological SEIR model with a time-varying transmission rate ($\beta(t)$) with the scope to assess the timeline and the strength of the effects produced by the adopted restrictive measures. The removal rate $\gamma$ was estimated, considering both two different time series (daily new and current positive cases). We avoided considering estimates of clinical SARS-CoV-2 recovery rate and specific mortality rate calculated by others, with the scope to comment on the knowledge provided by the analysed data on the removal rate estimated by our model. In the US, the transmission rate of SARS-CoV-2 was very high at the beginning of the considered temporal window, and its reduction appears to be later and slower in comparison with those observed in Italy and even more in Iceland. This difference may be viewed as a result of the approach adopted by the US in the epidemic onset based only on a limited and non-homogeneous containment measures \citep{parodi2020}. The adoption of this strategy in the US was a decision of particular importance since the COVID-19 onset began a few days later than Italy, where, on March 9, 2020, the Italian Government set Europe's first nationwide restriction on movement due to the incoming SARS-CoV-2 epidemic. The estimates on the Italian transmission rate confirm the control of the epidemic wave after approximately 20 days of home restrictions, but with a high mortality toll in comparison with the preceding Chinese epidemic \citep{rubino2020}. A social distancing and passive testing of symptomatic cases was the Italian strategy to contain the epidemic. Positive cases with few symptoms were confined in home isolation. However, there was a consistent amount of asymptomatic, which remained undetected, contributing to spread the epidemic \citep{lavezzo2020, flaxman2020}. Iceland has the advantage that the epidemic outbreak started later than Italy; we observed that the Icelandic transmission rate quickly moved to values close to 0 after only 15 days of the restrictive measures \citep{gudbjartsson2020}. These results were mainly attributable to an active searching strategy of asymptomatic positive cases organized by the national health service, which lead to be tested about 6\% of the Iceland population at the date of April 2, 2020. However, the presence of a free voluntary private screening program estimated that the fraction of undetected infections by the Icelandic health service ranged from 88.7\% to 93.6\% \citep{stock2020}. The comparison between the US, Italy, and Iceland was certainly affected by a regional/state variation to COVID-19 response. However this administrative-level granularity plays a role in the diffuseness of non-pharmacological health measures in the first phase of an epidemic outbreak. A faster and more aggressive response of each local administrative unit helps to contain the contagious spread and to achieve a relative control of the disease \citep{Lancet:2020}. Despite fears of the negative consequences on their economy, Italy and Iceland experienced a contagion control in a relative short period. With a rapid and structured stay-at-home order and an assertive infection control measures Iceland reduced the required time to flatten the curve. The estimated values for $\gamma$ reflects both the locally adopted swab policy and the specific phase of the epidemic wave: in fact, the active monitoring in Iceland provide a reliable value for the removal rate that is of about 12 days in line with that measured in China (14 days, \citep{wang2020}). In Italy, the controlling strategy implies that after a first positive swab test, a control swab will be repeated after a period of home isolation and this fact implies a longer time to obtain the healing confirmation. In the US the low number of removed subject in comparison with the high increase in the incidence makes challenging a reliable estimation of the removal rate. The proposed model has become a standard approach to estimate the transmission rate in a dynamic context \citep{hong2020,petropoulos2020,piccolomini2020,wu2020,zhang2020,Godio:2020}. The model has the double scope of having a real-time monitoring and of supplying possible evolution scenarios. The estimated fluctuations of $\beta(t)$ were driven by gradual changes in the behaviour of the population at risk as a consequence of the adopted restrictions. Respect to other specifications, our approach has the advantage of employing a basis of splines that allow us a high grade of flexibility for the estimation. We estimated the parameters for $\beta (t)$ and $\gamma$ through a composite likelihood considering the information provided by both the occurrence of new SARS-CoV-2 cases and the current positive cases; in order to cope with the possible presence of heteroscedasticity and autocorrelation in the data, we estimated consistent standard errors combining a sandwich variance estimator and a HAC correction. Even though the model formulation has some ancestors, our proposal differs in two aspects from the aforementioned literature: we allow the data to indicate the shape of the function $\beta(t)$ using a semiparametric approach. This feature could help to identify the best health intervention policy in a country; HAC variance estimators permits to reduce the bias allows to correct the underestimation of the variance of the estimator and therefore to produce future scenarios with a more appropriate margin of uncertainty. There are several other limitations to our analysis. We used plausible biological SARS-CoV-2 parameters for the SEIR model based on updated numbers (i.e., $\sigma$), but these values may be refined as more comprehensive data become available. The predicted values for $\beta(t)$ are valid only in the absence of future changes to the restrictions, which is not likely to happen if an intermittent social distancing measures will be adopted \citep{ferguson2020}. Our results point out that the transmission rate in the US, Italy, and Iceland showed a decline after the introduction of restriction measures. Despite this common trend, some differences in terms of timeline and impact are present. In particular, US experts argue that more helpful tools are needed in order to reach the control of the epidemic wave \citep{parmet2020}. The adoption of restrictive measures results in flatten epidemic curves and thus the distribution of the SARS-CoV-2 cases in a more extended period, respect to an uncontrolled epidemic outbreak. In the absence of a specific vaccine, the high number of susceptibles and the relaxation of restrictions taken represent a cause of future outbreaks. \newpage \section*{Appendix} \subsection*{Data sources accessed on April 28, 2020.} \begin{description} \item[Iceland:] John Hopkins University (\texttt{github.com/datasets/covid-19}), \citet{csse2020}. \item[Italy:] Italian Civil Protection, (\texttt{github.com/pcm-dpc/COVID-19}), \citet{morettini2020}. \item[US:] John Hopkins University (\texttt{github.com/datasets/covid-19}), \citet{csse2020}. \end{description} \subsection*{Software} The statistical analysis was carried using the R software \citep{R2019} and some its package: the minimization of the previous quantity was performed by means of a non-linear minimization process using the function \texttt{nlm}; package \texttt{deSolve} to resolve the standard ODE and package \texttt{ggplot2} to enhance the quality of the figures. Results and figures can be reproduced using the companion code in \texttt{github.com/Paolin83/SARS-CoV-2\_SEIR\_TV\_model}. \section{} \label{} \section{Introduction}\label{sec:introduction} The use of epidemic models permits to simulate disease transmission dynamics to detect emerging outbreaks and to assess public health interventions \citep{unkel2012,boily2007}. With the scope to describe the dynamics of epidemics, standard methods, such as the SIR model \citep{anderson1992}, divide the population into portions of subjects on the basis of their relation concerning the epidemic vector. Here the focus is on the dynamic such as the depletion of the susceptible portion to the infected one or the possible evolution of the rate of immunization. However, the standard SIR model, and other extensions as the SEIR model, do not take into account the time-varying nature of epidemics and several attempts were made to overcome this limitation \citep{Dureau:2013,boatto2018,kucharski2020}. In particular, most extensions were proposed for adapting the SIR model to specific case studies \citep{liu2012,peng2020} or to include time-varying coefficients with the scope to estimate epidemic dynamics \citep{hooker2011,chavez2017,fang2020}. This paper considers a flexible extension of the SEIR model, which incorporates the temporal dynamic connected to the transmission rate parameter, which is one of the most critical indicators for epidemiologists and at the basis of the basic reproduction number $R_O$. Also, this method allows us to make considerations about both the trend and the prediction of the number of infected cases to evaluate how any possible influencing factors like as the presence of a vaccine or restriction measures taken by the central authorities can affect an epidemic outbreak \citep{haas2020}. The proposed method is applied to the 2019–20 coronavirus pandemic, the COronaVIrus Disease 2019 (COVID-19), caused by a Severe Acute Respiratory Syndrome CoronaVirus 2 named SARS‑CoV‑2 \citep{who2020}. The World Health Organization declared the outbreak to be a Public Health Emergency of International Concern on January 30, 2020 and recognized it as a pandemic on March 11, 2020 \citep{eurosurveillance2020}. It is worth to mention, several studies are known in the literature concerning SEIR models with different time-varying parameter specifications \citep{hong2020,petropoulos2020,piccolomini2020,wu2020,zhang2020}. Our proposal differs in a statistical model consistent with counting data, a semiparametric (and therefore more flexible) specification of the time-varying parameters. We also pay more attention to assessing the uncertainty of estimates. To study how country-based mitigation measures influence the course of the SARS-CoV-2 epidemic \citep{anderson2020will}, we have looked to the on-going epidemic in the three countries (Italy, Iceland and the United States of America) where the adopted mitigation measures have been different \citep{remuzzi2020, gudbjartsson2020,dong2020}. The reference datasets are presented in Section \ref{sec:data}, while the proposed model and the statistical inference are illustrated in Section \ref{sec:methods} and Section \ref{sec:statinf}. In Section \ref{sec:results}, we collect our results for the different countries with a proposal for the forecast. We end the paper with a brief discussion in Section \ref{sec:discussion}. \section{SEIR model with time-varying coefficients}\label{sec:methods} \textbf{\subsection{SEIR model}} We start introducing the SEIR model, which is one the most used extensions of the standard SIR model, an Ordinary Differential Equation (ODE) based epidemiological model \citep{kermack1927}. Traditionally the SEIR model divides a population of hosts into four classes: Susceptible (S), Exposed (E), Infected (I) and Recovered (R). However in our framework, the last class should collect all the subjects which move outside the (I) status, i.e. recovered and deceased; for this reason, hereafter we denote (R) as Removed status. The model describes how the different portions of the population change over time $t$. In the standard SEIR model, deaths are modelled as flows from the $S$, $E$, $I$, or $R$ compartment to outside, because natural deaths are normally not monitored. If $S$, $E$, $I$, and $R$ refer to the numbers of individuals in each compartment, then these ``state variables'' change according to the following system of differential equations: \begin{subequations}\label{eq:SEIR} \begin{align} \frac{d}{dt}S(t) &= \mu (N-S(t))-\beta \frac{S(t) I(t) }{N}\\ \frac{d}{dt}E(t) &= \beta \frac{S(t) I(t)}{N}-(\mu+\sigma) E(t) \\ \frac{d}{dt}I(t) &=\sigma E(t)- (\mu+\gamma)I(t) \\ \frac{d}{dt}R(t) &= \gamma\,I(t)-\mu\,R(t) \end{align} \end{subequations} In the equations \eqref{eq:SEIR} $N$ is the total population, $\mu$ is the mortality rate, $\beta$ is the transmission rate, $\sigma$ is the exposed to infectious rate, and $\gamma$ is the removal rate that can broadly assumed to be the sum of $\gamma_R +\gamma_D$, where $\gamma_R$ and $\gamma_D$ are the recovery and the mortality rate, respectively. In general, $\beta$ is called transmission rate that is the number of people that a positive case infects each day; in our settings, $\beta$ is defined as equal to $a b$, where $a$ is the contact rate that is the average number of contacts per person in a day while $b$ is the probability of disease transmission in a single contact. However, $a$ and $b$ cannot be identified on the basis of the current information. The ratio ${S(t)}/{N}$ permits to adjust $\beta$ taking to account people who cannot infect each other. The parameters $\sigma$ and $\gamma$ are strictly dependent on the specific disease causing the epidemic and on the fraction of susceptible population. The parameter $\sigma$ is set equal to $\eta^{-1}$ where $\eta$ is the incubation period which may be higher for asymptomatic subjects; $\gamma$ is the recovery rate calculated as $\gamma=\rho^{-1}$ where $\rho$ is the average duration of the disease in days. Moreover, unlike the full specification, we do not consider the effect of births in model \eqref{eq:SEIR} and, therefore, $\sigma E (t) $ represents the number of new infected. Based on this parametrization we can define the reproduction number, $R_O$, as $$R_O=\frac{\beta \sigma}{(\gamma+\mu)(\sigma+\mu)}.$$ The index conveys the strength of contagious in an epidemic outbreak. In the case of both $\sigma$ and $\gamma \gg \mu$, $R_O$ can be approximated by ${\beta}/{\gamma}$. \subsection{Time-varying parameter specification} The standard SEIR model does that the parameters $\mu, \beta, \sigma$, and $\gamma$ are time-invariant. However, the characteristics of an epidemic suggest us that these parameters can vary. In particular, the overall mortality rate $\mu$ may increase if the number of deaths in a population directly or indirectly attributable to the disease (i.e., the insufficient capacity of health services) rises. The $\beta$ rate may also vary according to social distancing policies or, even, the isolation of infected people. We aim to evaluate as the actions taken by the governments, and how a different degree of travel restrictions, social distancing or limitation of the people movement can affect the epidemic curve of the infectious population. Our working hypothesis is that if there is an effect of the actions, they only affect the transmission rate of the epidemic, $\beta$. For this reason, we propose to modify this parameter over time, namely \begin{subequations}\label{eq:SEIRvar} \begin{align} \frac{d}{dt}S(t) &= \mu (N-S(t))-\beta(t) \frac{S(t) I(t) }{N}\\ \frac{d}{dt}E(t) &= \beta(t) \frac{S(t) I(t)}{N}-(\mu+\sigma) E(t) \\ \frac{d}{dt}I(t) &=\sigma E(t)- (\mu+\gamma)I(t) \\ \frac{d}{dt}R(t) &= \gamma\,I(t)-\mu\,R(t) \end{align} \end{subequations} Since the function $\beta(t)$ takes positive values, in the estimation step we consider the following log-linear specification \begin{equation}\label{eq:splines} \log(\beta(t))=\sum_{k=1}^K \psi_{k} N_k(t), \end{equation} where $N_k(t)$, $k=1,\ldots,K$, are $K$ natural cubic spline basis functions evaluated at $K-2$ equally spaced knots in addition to the boundary knots. The representation in \eqref{eq:splines} has the advantage that the estimation of $\beta(t)$ reduces to the estimation of the coefficients $\psi_k$. We refer to the next subsection for a short discussion about the number of knots and their positions. The time-dependent transmission rate $\beta(t)$ allows us to define a time dependent version $R_O$ (the basic reproduction number) as follows $$R_O(t)=\frac{\beta (t) }{\gamma}.$$ This index permits to evaluate the strength of contagious over a temporal window comparing $\beta (t)$ with the removal rate $\gamma$. In order to constraint $\gamma$ between 0 and 1, in the estimation process we reparametrize $\gamma$ as $\gamma$=$\frac{exp(\gamma^*)}{1+exp(\gamma^*)}$. The system \eqref{eq:SEIRvar} is a system of nonlinear ODEs, which must be solved numerically. In this paper we use the ODE solver lsode \citep{Hindmarsh:1983} as it has implemented in the R package \texttt{deSolve}. If we suppose that $\mu$ and $\sigma$ are known parameters, the (numerical) solutions $S(t;\theta)$, $E(t;\theta)$, $I(t;\theta)$, an $R(t;\theta)$ depend on the (vector of) parameters $\theta=(\psi_1,\ldots,\psi_K,\gamma^*)$. \section{Statistical inference}\label{sec:statinf} Different agencies in the world that daily update and publish datasets of epidemic data that contain at least three time series: the total number of infected, the number of dead, the number of recovered (see section \ref{sec:data} for more details). We derive from these time series the daily number of current positive cases $Y(t)$ and the daily number of new positive cases $Z(t)$, recorded at day $t$, $t=1,\ldots,T$. Usually, the time series are supposed to be realizations of a stochastic version of the compartmental models. The different versions can be broadly classified into continuous models and discrete models. In the first group fall the continuous-time Markov chains (CTMCs) and the stochastic differential equations (SDEs) \citep{allen:2008}. In the second group a discrete-time approximation to the stochastic continuous-time model is considered \citep{Lekone:Finkenstadt}. There exists an extensive literature on calibrating the stochastic models against time-series with different inferential approaches \citep{Finkesdadt:Grenfell:2000,Ionides:2006,hooker2011,andersson2012stochastic,Dureau:2013}. Instead in this paper we follow the simplest idea that the solutions of the system \eqref{eq:SEIRvar} are actually the expectations at days $t=1,\ldots,T$ of as many counting random variables. More precisely we model the observed counts $\{Y(t),Z(t)\}$, as \begin{subequations}\label{eq:poisson} \begin{align} Y(t) \sim &\operatorname{Poisson} (I(t;\theta))\\ Z(t) \sim &\operatorname{Poisson}(\sigma E(t;\theta)).\qquad \end{align} \end{subequations} Then the estimate of the parameter $\theta$ already defined are obtained by maximizing the independence log-likelihood \citep{Chandler:Bate:2007} \begin{eqnarray}\label{eq:cl} cl(\theta) &=& \sum_{t=1}^T Y(t)\log I(t;\theta) -I(t;\theta)+ Z(t)\log (\sigma E(t;\theta)) -\sigma E(t;\theta)\\ &=&\sum_{t=1}^T cl(\theta;t).\nonumber \end{eqnarray} Note that $CL(\theta)$ is not a `true' log-likelihood but an instance of a composite likelihood \citep{Lindsay:1988} since it does not seem reasonable to assume that $Y(t)$ and $Z(t)$ are mutually and temporally independent. However, even though the model is not correctly specified, the maximum composite likelihood estimator, $\widehat{\theta}$, is still a consistent and asymptotically Gaussian estimator with asymptotic variance $V({\theta})$ under mild conditions \citep{Chandler:Bate:2007,Jacod:Sorensen:2018}. The variance $V(\theta)$ can be estimated by the sandwich estimator $ \hat{V}=\widehat{B}^{-1} \widehat{M}\widehat{B}^{-1'} $. The `bread' matrix is given by $\widehat{B}={T^{-1}}\sum_{t=1}^T\nabla u(\hat\theta;t)$ with $u(\hat\theta;t)=\nabla cl(\hat\theta;t)$. In the presence of time-dependence the `meat' matrix $\hat{M}$ is given by the heteroskedasticity and autocorrelation consistent (HAC) estimator $$ \hat{M}=T^{-1}\sum_{t=1}^T\sum_{s=1}^Tw_{|t-s|}\nabla u(\hat\theta;t)\nabla u(\hat\theta;t)^\top $$ where $w = (w_0 , \ldots , w_{T-1})$ is a vector of weights \citep{Andrews:1991}. With the aim of forecasting the spread of the epidemic outside the observed period, the number and the positions of knots in \eqref{eq:splines} play a crucial role. The higher the number of nodes, the less smooth the function $\beta(t)$. In this way, however, there is a risk of over-fitting the data. On the other hand, the trend of the $\beta(t)$ outside the observation time interval is mainly determined by the basis functions corresponding to the boundary knots. We select the number of knots by maximizing the Composite Likelihood Information Criterion (CLIC) \citep{varin2005} $ CLIC(\widehat{\theta})=cl(\hat\theta)+\operatorname{tr}( \widehat{B}^{-1} \widehat{M}). $$ The criterion has a strong analogy with the Akaike Information Criterion (AIC). In fact $cl(\hat\theta)$ measures the goodness-of-fit similarly to the log-likelihood and the penalty tr($\widehat{B}^{-1} \widehat{M}$) reduces to $-(K+1)$ if the model \eqref{eq:poisson} is correctly specified, i.e. if equation \eqref{eq:cl} is the `true' log-likelihood. We could locate the internal knots to reflect policy interventions. However, it is very difficult to hypothesize the immediate effects of these policies and a simpler choice has been to place temporally equally spaced nodes. As for the boundary knots, it was chosen to place them at the beginning of the period and one week after the last observation available to obtain more stable estimates in the forecast period. \section{Results}\label{sec:results} The epidemic outbreak showed different patterns in the selected time window: the reported SARS-CoV-2 cases in the US were rapidly increasing, reaching a peak and subsequent stabilization of the number of daily new cases with an incidence of about 10 cases x100.000 inhabitants; in Italy, a drop up to 2.5 daily new SARS-CoV-2 cases x100.000 was reported, after an initial growth which reached a peak of incidence of about 10 cases x100.000 people similar to the US; in Iceland, the incidence of new SARS-CoV-2 cases knew a huge peak ($\approx$ 25 cases x100.000 people), then a decreasing trend and finally a limited number of new cases in the last considered day (Figure \ref{fig:Figure1}). A the end of the temporal window prevalence of the disease was quite different among the three considered countries: we registered 250, 180, and 45 current SARS-CoV-2 cases x100.000 people in the US, Italy, and Iceland, respectively. \begin{figure}[!ht] \begin{center} \includegraphics[width=\linewidth]{Figure1_rev2.pdf} \end{center} \caption{Daily new (solid black line) and current (dashed red line) cases of SARS-CoV-2 in (a) the US, (b) Italy and (c) Iceland.}\label{fig:Figure1} \end{figure} In the literature the incubation duration of the SARS-CoV-2 was estimated as $ { \eta}={5.2} $ \citep{wang2020} and therefore we set the specific parameter $\sigma=1/\eta=0.192$. The overall mortality rate $\mu$ was calculated as ${1}/{(\mbox{lifespan})}={1}/(365.25 \times\mbox{LE})$ where the Life Expectancy (LE) is 78.5 years in the US, 83.2 years in Italy and 82.2 years in Iceland, respectively. The total population (N) in 2020 was is 329.23 (US), 60.32 (Italy) and 0.36 (Iceland) million of inhabitants. The starting values $S(0)$, $E(0)$, $I(0)$ and $R(0)$ for the numerical resolution of the system \eqref{eq:SEIRvar} were set as follows \begin{itemize} \item $I(0)=Y(1)$ i.e. the number of currently infected on the first day of the dataset (US: 142, Italy: 155, Iceland: 1); \item $R(0)$ equal to the number of currently recovered on the first day of the dataset (US: 7, Italy: 0, Iceland: 0); \item $E(0)= Z(1)/{\sigma}$ where $Z(1)$ is the number of new infected on the first day of the dataset (US: 68, Italy: 66, Iceland: 2); \item $S(0)=N-E(0)-I(0)-R(0)$. \end{itemize} We have tried several values for the number of basis function $K$, i.e. from 3 to 8, and we found that $K=5$ and $K=3$ minimize the value of CLIC for Italy/US and Iceland, respectively. \begin{figure}[!ht] \begin{center} \includegraphics[width=\linewidth]{Figure2_rev2.pdf} \end{center} \caption{The estimate of $\beta(t)$ curves and 95\% confidence bands (in grey colour) for the US, Italy and Iceland. The dashed line represents the 30-day predicted evolution.}\label{fig:Figure2} \end{figure} The estimate of $\beta(t)$ (see Figure $\ref{fig:Figure2}$) showed an overall decreasing pattern of the transmission rate across the selected countries. In particular, in the US the estimate of ${\beta(t)}$ reached a peak close to $0.8$ after about ten days by the beginning of the epidemic outbreak, denoting an uncontrolled situation, moving to values of approximately $0.1$ after about $45$ days of the epidemic, with a predicted scenario of a slightly decreasing trend and a great amount of uncertainty. In Italy, the estimate of ${\beta(t)}$ was moving from initial values of $0.75$ to value close to $0.05$ after about 50 days of observations. The estimate of $\beta(t)$ were lower than those reported for the US. The estimate of $\beta(t)$ in Iceland showed a fast decreasing trend from values a bit over $1.0$ to about 0 at day 40. The 30-days prediction for $\beta(t)$ is pratically zero, denoting the end of the current phase of the epidemic. \begin{table} \centering \begin{tabular}{lcc} \hline Country & $\gamma$ & (95\% CI) \\ \hline US & 0.012 & [0.009-0.015]\\ Italy & 0.025 & [0.023-0.027]\\ Iceland & 0.080 & [0.063-0.101] \\ \hline \end{tabular} \caption{Estimated values of the $\gamma$ parameter and its relative 95\% Confidence Interval.} \label{tab:table1} \end{table} The estimates of $\gamma$ ranged from a low rate in the US and Italy, $0.012$ and $0.025$ respectively, to a higher rate in Iceland, $0.080$. Then the removal duration, i.e. the reciprocal of $\gamma$, was estimated at 85.0 days (95\% CI: 65.5-110.5) for the US, at 40.2 days (95\% CI: 37.6-43.1) for Italy and at 12.5 days (95\% CI: 9.9-15.9) for Iceland. \begin{figure}[!ht] \begin{center} \includegraphics[width=\linewidth]{Figure3_rev2.pdf} \end{center} \caption{The expected number of Exposed, Infected and Recovered subjects for the US, Italy and Iceland, based on the model parameter estimates. The dotted points indicate the observed number of infected cases. }\label{fig:Figure3} \end{figure} \begin{figure}[!ht] \begin{center} \includegraphics[width=\linewidth]{Figure4_rev2.pdf} \end{center} \caption{The expected number of new infected cases for the US, Italy and Iceland, based on the model parameter estimates. The dotted points indicate the observed number of new infected cases. The dashed line indicates the last day observed. }\label{fig:Figure4} \end{figure} The model fitting was deemed satisfactory (Figure $\ref{fig:Figure3}$ and Figure $\ref{fig:Figure4}$) both with respect to the number of new cases and to the cumulative positive cases. Our major findings were: in the US, the current positive cases were going to increase, reaching a probable maximum after the window of the next 30 days. In Italy, the epidemic outbreak had known its maximum in the number of positive cases around April 20th, and the tendency was for a slight decline. In Iceland, the peak of positive cases was registered on April 10th, associated with a rapid decreasing phase and a low number of new cases in the last observed days; in this case, the SARS-CoV-2 epidemic was going to be overcome approximately at the end of May. \begin{figure}[!ht] \begin{center} \begin{tabular}{c} \includegraphics[width=\linewidth]{Figure5_rev2.pdf} \end{tabular} \end{center} \caption{Estimated $R_O(t)$ values for the US, Italy, and Iceland and predicted evolution. The Y-axis is in the log-scale. The dashed lines indicate $R_O=1$ and the last day observed, respectively.}\label{fig:Figure5} \end{figure} The estimated trend for $R_O(t)$ appears quite different among the selected countries (see Figure \ref{fig:Figure5}). The value $R_O(t)=1$ was reached on different dates in Iceland (March 28th) and in Italy (April 16th), while in the US is expected to be achieved only in the end of May.
{'timestamp': '2021-11-08T02:04:48', 'yymm': '2111', 'arxiv_id': '2111.03157', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03157'}
arxiv
\section{Introduction}\label{sec:intro} The success of deep neural networks (DNNs) across different domains has created the desire to apply them in safety-critical applications such as autonomous vehicles~\citep{kendall2019learning,lechner2020neural} and healthcare systems~\citep{shen2017deep}. The fundamental challenge for the deployment of DNNs in these domains is certifying their safety~\citep{amodei2016concrete}. Thus, formal safety verification of DNNs in isolation and closed control loops~\citep{KatzBDJK17,HenzingerLZ21,GehrMDTCV18,TjengXT19,DuttaCS19} has become an active research topic. Bayesian neural networks (BNNs) are a family of neural networks that place distributions over their weights~\citep{neal2012bayesian}. This allows learning uncertainty in the data and the network's prediction, while preserving the strong modelling capabilities of DNNs~\citep{MacKay92a}. In particular, BNNs can learn arbitrary data distributions from much simpler (e.g.~Gaussian) weight distributions. This makes BNNs very appealing for robotic and medical applications~\citep{mcallister2017concrete} where uncertainty is a central component of data. Despite the large body of literature on verifying safety of DNNs, the formal safety verification of BNNs has received less attention. Notably, \citep{CardelliKLPPW19,WickerLPK20,MichelmoreWLCGK20} have proposed sampling-based techniques for obtaining probabilistic guarantees about BNNs. Although these approaches provide some insight into BNN safety, they suffer from two key limitations. First, sampling provides only bounds on the probability of the BNN's safety which is insufficient for systems with critical safety implications. For instance, having an autonomous vehicle with a $99.9\%$ safety guarantee is still insufficient for deployment if millions of vehicles are deployed. Second, samples can only simulate the system for a finite time, making it impossible to reason about the system's safety over an unbounded time horizon. \begin{wrapfigure}{R}{7cm} \centering \includegraphics[width=7cm]{standalone.pdf} \caption{BNNs are typically unsafe by default. Top figure: The posterior of a typical BNN has unbounded support, resulting in a non-zero probability of producing an unsafe action. Bottom figure: Restricting the support of the weight distributions via rejection sampling ensures BNN safety.} \label{fig:intro} \end{wrapfigure} In this work, we study the safety verification problem for BNN policies in safety-critical systems over the infinite time horizon. Formally, we consider discrete-time closed-loop systems defined by a dynamical system and a BNN policy. Given a set of initial states and a set of unsafe (or bad) states, the goal of the safety verification problem is to verify that no system execution starting in an initial state can reach an unsafe state. Unlike existing literature which considers probability of safety, we verify {\em sure safety}, i.e.~safety of every system execution of the system. In particular, we present a method for computing {\em safe weight sets} for which every system execution is safe as long as the BNN samples its weights from this set. Our approach to restrict the support of the weight distribution is necessary as BNNs with Gaussian weight priors typically produce output posteriors with unbounded support. Consequently, there is a low but non-zero probability for the output variable to lie in an unsafe region, see Figure \ref{fig:intro}. This implies that BNNs are usually unsafe by default. We therefore consider the more general problem of computing safe weight sets. Verifying that a weight set is safe allows re-calibrating the BNN policy by rejecting unsafe weight samples in order to guarantee safety. As most BNNs employ uni-modal weight priors, e.g. Gaussians, we naturally adopt weight sets in the form of products of intervals centered at the means of the BNN's weight distributions. To verify safety of a weight set, we search for a safety certificate in the form of a {\em safe positive invariant} (also known as {\em safe inductive invariant}). A safe positive invariant is a set of system states that contains all initial states, is closed under the system dynamics and does not contain any unsafe state. The key advantage of using safe positive invariants is that their existence implies the {\em infinite time horizon safety}. We parametrize safe positive invariant candidates by (deterministic) neural networks that classify system states for determining set inclusion. Moreover, we phrase the search for an invariant as a learning problem. A separated verifier module then checks if a candidate is indeed a safe positive invariant by checking the required properties via constraint solving. In case the verifier finds a counterexample demonstrating that the candidate violates the safe positive invariant condition, we re-train the candidate on the found counterexample. We repeat this procedure until the verifier concludes that the candidate is a safe positive invariant ensuring that the system is safe. The safe weight set obtained by our method can be used for safe exploration reinforcement learning. In particular, generating rollouts during learning by sampling from the safe weight set allows an exploration of the environment while ensuring safety. Moreover, projecting the (mean) weights onto the safe weight set after each gradient update further ensures that the improved policy stays safe. \textbf{Contributions} Our contributions can be summarized as follows: \begin{compactenum} \item We define a safety verification problem for BNN policies which overcomes the unbounded posterior issue by computing and verifying safe weight sets. The problem generalizes the sure safety verification of BNNs and solving it allows re-calibrating BNN policies via rejection sampling to guarantee safety. \item We introduce a method for computing safe weight sets in BNN policies in the form of products of intervals around the BNN weights' means. To verify safety of a weight set, our novel algorithm learns a safe positive invariant in the form of a deterministic neural network. \item We evaluate our methodology on a series of benchmark applications, including non-linear systems and non-Lyapunovian safety specifications. \end{compactenum} \section{Related work}\label{sec:relatedwork} \textbf{Verification of feed-forward NN} Verification of robustness and safety properties in feed-forward DNNs has received much attention but remains an active research topic~\citep{KatzBDJK17,HenzingerLZ21,GehrMDTCV18,RuanHK18,BunelTTKM18,TjengXT19}. As the majority of verification techniques were designed for deterministic NNs, they cannot be readily applied to BNNs. The safety verification of feed-forward BNNs has been considered in \citep{CardelliKLPPW19} by using samples to obtain statistical guarantees on the safety probability. The work of~\citep{WickerLPK20} also presents a sampling-based approach, however it provides certified lower bounds on the safety probability. The literature discussed above considers NNs in isolation, which can provide input-output guarantees on a NN but are unable to reason holistically about the safety of the system that the NN is applied in. Verification methods that concern the safety of NNs interlinked with a system require different approaches than standalone NN verification, which we will discuss in the rest of this section. \textbf{Finite time horizon safety of BNN policies} The work in~\citep{MichelmoreWLCGK20} extends the method of~\citep{CardelliKLPPW19} to verifying safety in closed-loop systems with BNN policies. However, similar to the standalone setting of \cite{CardelliKLPPW19}, their method obtains only statistical guarantees on the safety probability and for the system's execution over a finite time horizon. \textbf{Safe RL} Safe reinforcement learning has been primarily studied in the form of constrained Markov decision processes (CMDPs) \citep{altman1999constrained,Geibel06}. Compared to standard MDPs, an agent acting in a CMDP must satisfy an expected auxiliary cost term aggregated over an episode. The CMDP framework has been the base of several RL algorithms~\citep{uchibe2007constrained}, notably the Constrained Policy Optimization (CPO)~\citep{achiam2017constrained}. Despite these algorithms providing a decent performance, the key limitation of CMDPs is that the constraint is satisfied in expectation, which makes violations unlikely but nonetheless possible. Consequently, the CMDP framework is unsuited for systems where constraint violations are critical. \textbf{Lyapunov-based stability} Safety in the context of ''stability'', i.e.~always returning to a ground state, can be proved by Lyapunov functions~\citep{BerkenkampTS017}. Lyapunov functions have originally been considered to study stability of dynamical systems~\citep{khalil2002nonlinear}. Intuitively, a Lyapunov function assigns a non-negative value to each state, and is required to decrease with respect to the system's dynamics at any state outside of the stable set. A Lyapunov-based method is proposed in~\citep{ChowNDG18} to ensure safety in CMDPs during training. Recently, the work of~\citep{ChangRG19} presented a method for learning a policy as well as a neural network Lyapunov function which guarantees the stability of the policy. Similarly to our work, their learning procedure is counterexample-based. However, unlike \citep{ChangRG19}, our work considers BNN policies and safety definitions that do not require returning to a set of ground states. \textbf{Barrier functions for dynamical systems} Barrier functions can be used to prove infinite time horizon safety in dynamical systems~\citep{PrajnaJ04,PrajnaJP07}. Recent works have considered learning neural network barrier functions~\citep{ZhaoZC020}, and a counterexample-based learning procedure is presented in~\cite{PeruffoAA21}. \textbf{Finite time horizon safety of NN policies} Safety verification of continuous-time closed-loop systems with deterministic NN policies has been considered in~\citep{IvanovWAPL19,gruenbacher2020lagrangian}, which reduces safety verification to the reachability analysis in hybrid systems~\citep{ChenAS13}. The work of~\citep{DuttaCS19} presents a method which computes a polynomial approximation of the NN policy to allow an efficient approximation of the reachable state set. Both works consider finite time horizon systems. Our safety certificate most closely resembles inductive invariants for safety analysis in programs~\citep{Floyd1967} and positive invariants for dynamical systems~\citep{blanchini2008set}. \section{Preliminaries and problem statement}\label{sec:prelims} We consider a discrete-time dynamical system \[ \mathbf{x}_{t+1} = f(\mathbf{x}_t,\mathbf{u}_t),\, \mathbf{x}_0\in\mathcal{X}_0. \] The dynamics are defined by the function $f:\mathcal{X}\times \mathcal{U}\rightarrow \mathcal{X}$ where $\mathcal{X}\subseteq \mathbb{R}^m$ is the state space and $\mathcal{U}\subseteq \mathbb{R}^n$ is the control action space, $\mathcal{X}_0\subseteq \mathcal{X}$ is the set of initial states and $t\in\mathbb{N}_{\geq 0}$ denotes a discretized time. At each time step $t$, the action is defined by the (possibly probabilistic) positional policy $\pi:\mathcal{X}\rightarrow\mathcal{D}(\mathcal{U})$, which maps the current state $\mathbf{x}_t$ to a distribution $\pi(\mathbf{x}_t)\in\mathcal{D}(U)$ over the set of actions. We use $\mathcal{D}(U)$ to denote the set of all probability distributions over $U$. The next action is then sampled according to $\mathbf{u}_t\sim \pi(\mathbf{x}_t)$, and together with the current state $\mathbf{x}_t$ of the system gives rise to the next state $\mathbf{x}_{t+1}$ of the system according to the dynamics $f$. Thus, the dynamics $f$ together with the policy $\pi$ form a closed-loop system (or a feedback loop system). The aim of the policy is to maximize the expected cumulative reward (possibly discounted) from each starting state. Given a set of initial states $\mathcal{X}_0$ of the system, we say that a sequence of state-action pairs $(\mathbf{x}_t,\mathbf{u}_t)_{t=0}^{\infty}$ is a trajectory if $\mathbf{x}_0\in \mathcal{X}_0$ and we have $\mathbf{u}_t\in\mathsf{supp}(\pi(\mathbf{x}_t))$ and $\mathbf{x}_{t+1} = f(\mathbf{x}_t,\mathbf{u}_t)$ for each $t\in\mathbb{N}_{\geq 0}$. A neural network (NN) is a function $\pi:\mathbb{R}^m\rightarrow \mathbb{R}^n$ that consists of several sequentially composed layers $\pi=l_1\circ\dots\circ l_k$. Formally, a NN policy maps each system state to a Dirac-delta distribution which picks a single action with probability $1$. Each layer $l_i$ is parametrized by learned weight values of the appropriate dimensions and an activation function $a$, \[ l_i(\mathbf{x}) = a(\mathbf{W}_i\mathbf{x}+\mathbf{b}_i), \mathbf{W}_i\in \mathbb{R}^{n_i\times m_i}, \mathbf{b}_i\in \mathbb{R}^{n_i}. \] In this work, we consider ReLU activation functions $a(\mathbf{x})=\textrm{ReLU}(\mathbf{x})=\max\{\mathbf{x},\mathbf{0}\}$, although other piecewise linear activation such as the leaky-ReLU \citep{JarrettKRL09} and PReLU \citep{HeZRS15} are applicable as well. In Bayesian neural networks (BNNs), weights are random variables and their values are sampled, each according to some distribution. Then each vector of sampled weights gives rise to a (deterministic) neural network. Given a training set $\mathcal{D}$, in order to train the BNN we assume a prior distribution $p(\mathbf{w},\mathbf{b})$ over the weights. The learning then amounts to computing the posterior distribution $p(\mathbf{w},\mathbf{b}\mid \mathcal{D})$ via the application of the Bayes rule. As analytical inference of the posterior is in general infeasible due to non-linearity introduced by the BNN architecture~\citep{MacKay92a}, practical training algorithms rely on approximate inference, e.g.~Hamiltonian Monte Carlo~\citep{neal2012bayesian}, variational inference~\citep{blundell2015weight} or dropout~\citep{GalG16}. When the policy in a dynamical system is a BNN, the policy maps each system state $\mathbf{x}_t$ to a probability distribution $\pi(\mathbf{x}_t)$ over the action space. Informally, this distribution is defined as follows. First, BNN weights $\mathbf{w}$, $\mathbf{b}$ are sampled according to the posterior BNN weight distribution, and the sampled weights give rise to a deterministic NN policy $\pi_{\mathbf{w},\mathbf{b}}$. The action of the system is then defined as $\mathbf{u}_t=\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}_t)$. Formal definition of the distribution $\pi(\mathbf{x}_t)$ is straightforward and proceeds by considering the product measure of distributions of all weights. \textbf{Problem statement} We now define the two safety problems that we consider in this work. The first problem considers feed-forward BNNs, and the second problem considers closed-loop systems with BNN policies. While our solution to the first problem will be a subprocedure in our solution to the second problem, the reason why we state it as a separate problem is that we believe that our solution to the first problem is also of independent interest for the safety analysis of feed-forward BNNs. Let $\pi$ be a BNN. Suppose that the vector $(\mathbf{w},\mathbf{b})$ of BNN weights in $\pi$ has dimension $p+q$, where $p$ is the dimension of $\mathbf{w}$ and $q$ is the dimension of $\mathbf{b}$. For each $1\leq i\leq p$, let $\mu_i$ denote the mean of the random variable $w_i$. Similarly, for each $1\leq i\leq q$, let $\mu_{p+i}$ denote the mean of the random variable $b_i$. Then, for each $\epsilon\in [0,\infty]$, we define the set $W^{\pi}_{\epsilon}$ of weight vectors via \[ W^{\pi}_{\epsilon} = \prod_{i=1}^{p+q}[\mu_i-\epsilon,\mu_i+\epsilon] \subseteq \mathbb{R}^{p+q}. \] We now proceed to defining our safety problem for feed-forward BNNs. Suppose that we are given a feed-forward BNN $\pi$, a set $\mathcal{X}_0\subseteq \mathbb{R}^m$ of input points and a set $\mathcal{X}_u\subseteq \mathbb{R}^n$ of unsafe (or bad) output points. For a concrete vector $(\mathbf{w},\mathbf{b})$ of weight values, let $\pi_{\mathbf{w},\mathbf{b}}$ to be the (deterministic) NN defined by these weight values. We say that $\pi_{\mathbf{w},\mathbf{b}}$ is safe if for each $\mathbf{x}\in\mathcal{X}_0$ we have $\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x})\not\in\mathcal{X}_u$, i.e.~if evaluating $\pi_{\mathbf{w},\mathbf{b}}$ on all input points does not lead to an unsafe output. \begin{adjustwidth}{1cm}{} \begin{problem}[Feed-forward BNNs]\label{problem1} Let $\pi$ be a feed-forward BNN, $\mathcal{X}_0\subseteq \mathbb{R}^m$ a set of input points and $\mathcal{X}_u\subseteq \mathbb{R}^n$ a set of unsafe output points. Let $\epsilon\in [0,\infty]$. Determine whether each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe. \end{problem} \end{adjustwidth} Next, we define our safety problem for closed-loop systems with BNN policies. Consider a closed-loop system defined by a dynamics function $f$, a BNN policy $\pi$ and an initial set of states $\mathcal{X}_0$. Let $\mathcal{X}_u\subseteq\mathcal{X}$ be a set of unsafe (or bad) states. We say that a trajectory $(\mathbf{x}_t,\mathbf{u}_t)_{t=0}^{\infty}$ is safe if $\mathbf{x}_t\not\in \mathcal{X}_u$ for all $t\in\mathbb{N}_0$, hence if it does not reach any unsafe states. Note that this definition implies infinite time horizon safety of the trajectory. Given $\epsilon\in[0,\infty]$, define the set $\mathsf{Traj}^{f,\pi}_{\epsilon}$ to be the set of all system trajectories in which each sampled weight vector belongs to $W^{\pi}_{\epsilon}$. \begin{adjustwidth}{1cm}{} \begin{problem}[Closed-loop systems with BNN policies]\label{problem2} Consider a closed-loop system defined by a dynamics function $f$, a BNN policy $\pi$ and a set of initial states $\mathcal{X}_0$. Let $\mathcal{X}_u$ be a set of unsafe states. Let $\epsilon\in [0,\infty]$. Determine whether each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{problem} \end{adjustwidth} Note that the question of whether the BNN policy $\pi$ is safe (i.e.~whether each trajectory of the system is safe) is a special case of the above problem which corresponds to $\epsilon=\infty$. \section{Experiments}\label{sec:exp} We perform an experimental evaluation of our proposed method for learning positive invariant neural networks that prove infinite time horizon safety. Our evaluation consists of an ablation study where we disable different core components of Algorithm~\ref{algorithm:ce} and measure their effects on the obtained safety bounds and the algorithm's runtime. First, we run the algorithm without any re-training on the counterexamples. In the second step, we run Algorithm~\ref{algorithm:ce} by initializing $D_{\textrm{spec}}$ with samples from $\mathcal{X}_0$ and $\mathcal{X}_u$ only. Finally, we bootstrap the positive invariant network by initializing $D_{\textrm{spec}}$ with random samples from the state space labeled with Monte-Carlo estimates of reaching the unsafe states. We consider environments with a piecewise linear dynamic function, initial and unsafe state sets so that the verification steps of our algorithm can be reduced to MILP-solving using Gurobi \cite{gurobi}. Details on our evaluation are in the Supplementary Material. Code is publicly available \footnote{\url{https://github.com/mlech26l/bayesian_nn_safety}}. We conduct our evaluation on three benchmark environments that differ in terms of complexity and safety specifications. We train two BNN policies for each benchmark-ablation pair, one with Bayesian weights from the second layer on (with $\mathcal{N}(0,0.1)$ prior) and one with Bayesian weights in all layers (with $\mathcal{N}(0,0.05)$ prior). Recall, in our BNN encoding in Section~\ref{sec:feedforward}, we showed that encoding of the BNN input layer requires additional constraints and extra care, since we do not know the signs of input neuron values. Hence, we consider two BNN policies in our evaluation in order to study how the encoding of the input layer affects the safe weight set computation. Our first benchmark represents an unstable linear dynamical system of the form $x_{t+1} = Ax_t + Bu_t$. A BNN policy stabilizes the system towards the point $(0,0)$. Consequently, the set of unsafe states is defined as $\{x\in\mathbb{R}^2\mid|x|_{\infty}\geq 1.2\}$, and the initial states as $\{x\in\mathbb{R}^2\mid |x|_{\infty}\leq 0.6\}$. Our second benchmark is the inverted pendulum task, which is a classical non-linear control problem. The two state variables $a$ and $b$ represent the angle and angular velocity of a pendulum that must be controlled in an upward direction. The actions produced by the policy correspond to a torque applied to the anchor point. Our benchmark concerns a variant of the original problem where the non-linearity in $f$ is expressed by piecewise linear functions. The resulting system, even with a trained policy, is highly unstable, as shown in Figure~\ref{fig:pend}. The set of initial states corresponds to pendulum states in an almost upright position and with small angular velocity. The set of unsafe states represents the pendulum falling down. Figure~\ref{fig:pend} visualizes the system and the learned invariant's decision boundary for the inverted pendulum task. \begin{figure} \centering \subcaptionbox{Vector field of the system when controlled by the posterior's mean. Green/red arrows indicate empirical safe/unsafe estimates.}% [.31\linewidth]{\includegraphics[width=0.25\textwidth]{plots/vector_field.png}} \hfill \subcaptionbox{First guess of $g^{\mathsf{Inv}}$. Green area shows $g^{\mathsf{Inv}}>0$, orange area $g^{\mathsf{Inv}}<0$. Red markers show the found counterexample.}% [.31\linewidth]{\includegraphics[width=0.25\textwidth]{plots/step0.png}} \hfill \subcaptionbox{Final $g^{\mathsf{Inv}}$ proving the safety of the system. Previous counterexamples marked in red.}% [.31\linewidth]{\includegraphics[width=0.25\textwidth]{plots/step2.png}} \caption{Invariant learning shown on the inverted pendulum benchmark.} \label{fig:pend} \end{figure} \begin{table}[] \centering \caption{Results of our benchmark evaluation. The epsilon values are multiples of the weight's standard deviation $\sigma$. We evaluated several epsilon values, and the table shows the largest that could be proven safe. A dash ''-'' indicates an unsuccessful invariant search. Runtime in seconds.} \begin{tabular}{l|rr|rr|rr}\toprule \multirow{2}{*}{Environment} & \multicolumn{2}{c|}{No re-training} & \multicolumn{2}{c|}{Init $D_{spec}$ with $\mathcal{X}_0$ and $\mathcal{X}_u$} & \multicolumn{2}{c}{Bootstrapping $D_{spec}$} \\ & Verified & Runtime & Verified & Runtime & Verified & Runtime \\\cmidrule(r){1-7} Unstable LDS & - & 3 & $1.5\sigma$ & 569 & $2\sigma$ & 760 \\ Unstable LDS (all) & $0.2\sigma$ & 3 & $0.5\sigma$ & 6 & $0.5\sigma$ & 96 \\ Pendulum & - & 2 & $2\sigma$ & 220 & $2\sigma$ & 40 \\ Pendulum (all) & - & 2 & $0.2\sigma$ & 1729 & $1.5\sigma$ & 877 \\ Collision avoid. & - & 2 & - & - & $2\sigma$ & 154 \\ Collision avoid. (all) & - & 2 & - & - & $1.5\sigma$ & 225 \\\bottomrule \end{tabular} \label{tab:results} \end{table} While the previous two benchmarks concern stability specifications, we evaluate our method on a non-Lyapunovian safety specification in our third benchmark. In particular, our third benchmark is a collision avoidance task, where the system does not stabilize to the same set of terminal states in every execution. The system is described by three variables. The first variable specifies the agent's own vertical location, while the other two variables specify an intruder's vertical and horizontal position. The objective is to avoid colliding with the intruder who is moving toward the agent by lateral movement commands as the policy's actions. The initial states represent far-away intruders, and crashes with the intruder define the unsafe states. Table \ref{tab:results} shows the results of our evaluation. Our results demonstrate that re-training with the counterexamples is the key component that determines our algorithm's success. In all cases, except for the linear dynamical system, the initial guess of the invariant candidate violates the invariant condition. Moreover, boostrapping $D_{\textrm{spec}}$ with random points labeled by empirical estimates of reaching the unsafe states improves the search process significantly. \section{Main results} In this section we present our method for solving the safety problems defined in the previous section, with Section~\ref{sec:feedforward} considering Problem~\ref{problem1} and Section~\ref{sec:loopcertificate} considering Problem~\ref{problem2}. Both problems consider safety verification with respect to a given value of $\epsilon\in[0,\infty]$, so in Section~\ref{sec:epscompute} we present our method for computing the value of $\epsilon$ for which our solutions to Problem~1 and Problem~2 may be used to verify safety. We then show in Section~\ref{sec:safeexploration} how our new methodology can be adapted to the safe exploration RL setting. \subsection{Safe weight sets for feed-forward BNNs}\label{sec:feedforward} Consider a feed-forward BNN $\pi$, a set $\mathcal{X}_0\subseteq\mathbb{R}^m$ of inputs and a set $\mathcal{X}_u\subseteq\mathbb{R}^n$ of unsafe output of the BNN. Fix $\epsilon\in[0,\infty]$. To solve Problem~\ref{problem1}, we show that the decision problem of whether each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe can be encoded as a system of constraints and reduced to constraint solving. Suppose that $\pi=l_1\circ\dots\circ l_k$ consists of $k$ layers, with each $l_i(\mathbf{x}) = \textrm{ReLU}(\mathbf{W}_i\mathbf{x}+\mathbf{b}_i)$. Denote by $\mathbf{M}_i$ the matrix of the same dimension as $\mathbf{W}_i$, with each entry equal to the mean of the corresponding random variable weight in $\mathbf{W}_i$. Similarly, define the vector $\mathbf{m}_i$ of means of random variables in $\mathbf{b}_i$. The real variables of our system of constraints are as follows, each of appropriate dimension: \begin{compactitem} \item $\mathbf{x}_0$ encodes the BNN inputs, $\mathbf{x}_l$ encodes the BNN outputs; \item $\mathbf{x}_1^{\textrm{in}}$, \dots, $\mathbf{x}_{l-1}^{\textrm{in}}$ encode vectors of input values of each neuron in the hidden layers; \item $\mathbf{x}_1^{\textrm{out}}$, \dots, $\mathbf{x}_{l-1}^{\textrm{out}}$ encode vectors of output values of each neuron in the hidden layers; \item $\mathbf{x}_{0,\textrm{pos}}$ and $\mathbf{x}_{0,\textrm{neg}}$ are dummy variable vectors of the same dimension as $\mathbf{x}_0$ and which will be used to distinguish between positive and negative NN inputs in $\mathbf{x}_0$, respectively. \end{compactitem} We use $\mathbf{1}$ to denote the vector/matrix whose all entries are equal to $1$, of appropriate dimensions defined by the formula in which it appears. Our system of constraints is as follows: \begin{equation}\label{eq:inputoutput}\tag{Input-output conditions} \mathbf{x}_0 \in \mathcal{X}_0, \hspace{0.5cm} \mathbf{x}_l \in \mathcal{X}_u \end{equation} \begin{equation}\label{eq:relu}\tag{ReLU encoding} \mathbf{x}_i^{\textrm{out}} = \textrm{ReLU}(\mathbf{x}_i^{\textrm{in}}), \text{ for each } 1\leq i\leq l-1 \end{equation} \begin{equation}\label{eq:weights}\tag{BNN hidden layers} \begin{split} &(\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_{i+1}^{\textrm{in}}, \text{ for each } 1\leq i\leq l-1 \\ &\mathbf{x}_{i+1}^{\textrm{in}} \leq (\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i+\epsilon\cdot\mathbf{1}), \text{ for each } 1\leq i\leq l-1 \end{split} \end{equation} \begin{equation}\label{eq:weights}\tag{BNN input layer} \begin{split} &\mathbf{x}_{0,\textrm{pos}} = \textrm{ReLU}(\mathbf{x}_0), \hspace{0.5cm} \mathbf{x}_{0,\textrm{neg}} = -\textrm{ReLU}(-\mathbf{x}_0) \\ &(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_1^{\textrm{in}} \\ &\mathbf{x}_1^{\textrm{in}} \leq (\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_0^{\textrm{out}}+(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0+\epsilon\cdot\mathbf{1}) \end{split} \end{equation} Denote by $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ the system of constraints defined above. The proof of Theorem~\ref{thm:constraints} shows that it encodes that $\mathbf{x}_0\in\mathcal{X}_0$ is an input point for which the corresponding output point of $\pi$ is unsafe, i.e.~$\mathbf{x}_l=\pi(\mathbf{x}_0)\in\mathcal{X}_u$. The first equation encodes the input and output conditions. The second equation encodes the ReLU input-output relation for each hidden layer neuron. The remaining equations encode the relation between neuron values in successive layers of the BNN as well as that the sampled BNN weight vector is in $W^{\pi}_{\epsilon}$. For hidden layers, we know that the output value of each neuron is nonnegative, i.e.$~\mathbf{x}_i^{\textrm{out}}\geq\mathbf{0}$ for the $i$-th hidden layer where $1\leq i\leq l-1$, and so \[ (\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}} \leq (\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}. \] Hence, the BNN weight relation with neurons in the successive layer as well as the fact that the sampled weights are in $W^{\pi}_{\epsilon }$ is encoded as in equations 3-4 above. For the input layer, however, we do not know the signs of the input neuron values $\mathbf{x}_0$ and so we introduce dummy variables $\mathbf{x}_{0,\textrm{pos}}=\textrm{ReLU}(\mathbf{x}_0)$ and $\mathbf{x}_{0,\textrm{neg}}=-\textrm{ReLU}(-\mathbf{x}_0)$ in equation 5. This allows encoding the BNN weight relations between the input layer and the first hidden layer as well as the fact that the sampled weight vector is in $W^{\pi}_{\epsilon}$, as in equations 6-7. Theorem~\ref{thm:constraints} shows that Problem~\ref{problem1} is equivalent to solving the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Its proof can be found in the Supplementary Material. \begin{theorem}\label{thm:constraints} Let $\epsilon\in[0,\infty]$. Then each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe if and only if the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is not satisfiable. \end{theorem} \textbf{Solving the constraints} Observe that $\epsilon$, $\mathbf{M}_i$ and $\mathbf{m}_i$, $1\leq i\leq l-1$, are constant values that are known at the time of constraint encoding. Thus, in $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$, only the ReLU constraints and possibly the input-output conditions are not linear. Depending on the form of $\mathcal{X}_0$ and $\mathcal{X}_u$ and on how we encode the ReLU constraints, we may solve the system $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ in several ways: \begin{compactenum} \item \textbf{MILP.} It is shown in~\citep{lomuscio2017approach,dutta2018output,TjengXT19} that the ReLU relation between two real variables can be encoded via mixed-integer linear constraints (MILP) by introducing 0/1-integer variables to encode whether a given neuron is active or inactive. Hence, if $\mathcal{X}_0$ and $\mathcal{X}_u$ are given by linear constraints, we may solve $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ by a MILP solver. The ReLU encoding requires that each neuron value is bounded, which is ensured if $\mathcal{X}_0$ is a bounded set and if $\epsilon<\infty$. \item \textbf{Reluplex.} In order to allow unbounded $\mathcal{X}_0$ and $\epsilon=\infty$, we may use algorithms based on the Reluplex calculus~\citep{KatzBDJK17,KatzHIJLLSTWZDK19} to solve $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Reluplex is an extension of the standard simplex algorithm for solving systems of linear constraints, designed to allow ReLU constraints as well. While Reluplex does not impose the boundedness condition, it is in general less scalable than MILP-solving. \item \textbf{NRA-SMT.} Alternatively, if $\mathcal{X}_0$ or $\mathcal{X}_u$ are given by non-linear constraints we may solve them by using an NRA-SMT-solver (non-linear real arithmetic satisfiability modulo theory), e.g.~dReal~\citep{gao2012delta}. To use an NRA-SMT-solver, we can replace the integer 0/1-variables of the ReLU neuron relations encoding with real variables that satisfy the constraint $x(x-1)=0$. While NRA-SMT is less scalable compared to MILP, we note that it has been used in previous works on RL stability verification \cite{ChangRG19}. \end{compactenum} \textbf{Safety via rejection sampling} As discussed in Section~\ref{sec:intro}, once the safety of NNs in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ has been verified, we can ``re-calibrate'' the BNN to reject sampled weights which are not in $W^{\pi}_{\epsilon}$. Hence, rejection sampling gives rise to a safe BNN. \subsection{Safe weight sets for closed-loop systems with BNN Policies}\label{sec:loopcertificate} Now consider a closed-loop system with a dynamics function $f:\mathcal{X}\times\mathcal{U}\rightarrow\mathcal{X}$ with $\mathcal{X}\subseteq\mathbb{R}^m$ and $\mathcal{U}\subseteq\mathbb{R}^n$, a BNN policy $\pi$, an initial state set $\mathcal{X}_0\subseteq\mathcal{X}$ and an unsafe state set $\mathcal{X}_u\subseteq\mathcal{X}$. Fix $\epsilon\in[0,\infty]$. In order to solve Problem~\ref{problem2} and verify safety of each trajectory contained in $\mathsf{Traj}^{f,\pi}_{\epsilon}$, our method searches for a positive invariant-like safety certificate that we define below. \textbf{Positive invariants for safety} A positive invariant in a dynamical system is a set of states which contains all initial states and which is closed under the system dynamics. These conditions ensure that states of all system trajectories are contained in the positive invariant. Hence, a positive invariant which does not contain any unsafe states can be used to certify safety of every trajectory over infinite time horizon. In this work, however, we are not trying to prove safety of every trajectory, but only of those trajectories contained in $\mathsf{Traj}^{f,\pi}_{\epsilon}$. To that end, we define $W^{\pi}_{\epsilon}$-safe positive invariants. Intuitively, a $W^{\pi}_{\epsilon}$-safe positive invariant is required to contain all initial states, to be closed under the dynamics $f$ and the BNN policy $\pi$ when the sampled weight vector is in $W^{\pi}_{\epsilon}$, and not to contain any unsafe state. \begin{definition}[$W^{\pi}_{\epsilon}$-safe positive invariants]\label{def:inv} A set $\mathsf{Inv}\subseteq\mathcal{X}$ is said to be a {\em $W^{\pi}_{\epsilon}$-positive invariant} if $\mathcal{X}_0\subseteq\mathsf{Inv}$, for each $\mathbf{x}\in\mathsf{Inv}$ and $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ we have that $f(\mathbf{x},\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}))\in\mathsf{Inv}$, and $\mathsf{Inv}\cap\mathcal{X}_u=\emptyset$. \end{definition} Theorem~\ref{thm:posinv} shows that $W^{\pi}_{\epsilon}$-safe positive invariants can be used to verify safety of all trajectories in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ in Problem~\ref{problem2}. The proof is straightforward and is deferred to the Supplementary Material. \begin{theorem}\label{thm:posinv} If there exists a $W^{\pi}_{\epsilon}$-safe positive invariant, then each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{theorem} \begin{algorithm}[t] \caption{Learning algorithm for $W^{\pi}_{\epsilon}$-safe positive invariants} \label{algorithm:ce} \begin{algorithmic} \STATE \textbf{Input} Dynamics function $f$, BNN policy $\pi$, Initial state set $\mathcal{X}_0$, Unsafe state set $\mathcal{X}_u$, $\epsilon \in [0,\infty]$ \STATE $\tilde{\mathcal{X}_0}, \tilde{\mathcal{X}_u} \leftarrow $ random samples of $\mathcal{X}_0,\mathcal{X}_u$ \STATE $D_{\textrm{spec}} \leftarrow \tilde{\mathcal{X}_u} \times \{0\} \cup \tilde{\mathcal{X}_0} \times \{1\}$, $D_{\textrm{ce}} \leftarrow \{\}$ \STATE Optional (bootstrapping): $S_{\textrm{bootstrap}} \leftarrow $ sample finite trajectories with initial state sampled from $\mathcal{X}$ \STATE \qquad\qquad\qquad $D_{\textrm{spec}} \leftarrow D_{\textrm{spec}} \cup \{(\mathbf{x},0)| \,\exists s\in S_{\textrm{bootstrap}} \text{ that starts in } \mathbf{x}\in \mathcal{X} \text{ and reaches } \mathcal{X}_u \}$ \STATE \qquad\qquad\qquad\qquad\qquad $\cup\, \{(\mathbf{x},1)| \,\exists s\in S_{\textrm{bootstrap}} \text{ that starts in } \mathbf{x}\in \mathcal{X} \text{ and does not reach } \mathcal{X}_u \}$ \STATE Pre-train neural network $g^{\mathsf{Inv}}$ on datasets $D_{\textrm{spec}}$ and $D_{\textrm{ce}}$ with loss function $\mathcal{L}$ \WHILE{timeout not reached} \IF{$\exists (\mathbf{x},\mathbf{x}',\mathbf{u},\mathbf{w},\mathbf{b})$ s.t. $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$, $g^{\mathsf{Inv}}(\mathbf{x}')<0$, $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$, $\mathbf{u}=\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x})$, $\mathbf{x}'=f(\mathbf{x},\mathbf{u})$} \STATE $D_{\textrm{ce}} \leftarrow D_{\textrm{ce}} \cup \{(\mathbf{x},\mathbf{x}')\}$ \ELSIF{$\exists (\mathbf{x})$ s.t. $\mathbf{x}\in\mathcal{X}_0$, $g^{\mathsf{Inv}}(\mathbf{x})< 0$} \STATE $D_{\textrm{spec}} \leftarrow D_{\textrm{spec}} \cup \{(\mathbf{x},1)\}$ \ELSIF{$\exists (\mathbf{x})$ s.t. $\mathbf{x}\in\mathcal{X}_u$, $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$} \STATE $D_{\textrm{spec}} \leftarrow D_{\textrm{spec}} \cup \{(\mathbf{x},0)\}$ \ELSE \STATE \textbf{Return} Safe \ENDIF \STATE {Train neural network $g^{\mathsf{Inv}}$ on datasets $D_{\textrm{spec}}$ and $D_{\textrm{ce}}$ with loss function $\mathcal{L}$} \ENDWHILE \STATE \textbf{Return} Unsafe \end{algorithmic} \end{algorithm} \textbf{Learning positive invariants} We now present a learning algorithm for a $W^{\pi}_{\epsilon}$-safe positive invariant. It learns a neural network $g^{\mathsf{Inv}}:\mathbb{R}^m\rightarrow\mathbb{R}$, where the positive invariant is then defined as the set $\mathsf{Inv} = \{\mathbf{x}\in\mathcal{X}\mid g^{\mathsf{Inv}}(\mathbf{x})\geq 0\}$. The pseudocode is given in Algorithm~\ref{algorithm:ce}. The algorithm first samples $\tilde{\mathcal{X}_0}$ from $\mathcal{X}_0$ and $\tilde{\mathcal{X}_u}$ from $\mathcal{X}_u$ and initializes the specification set $D_{\textrm{spec}}$ to $\tilde{\mathcal{X}_u} \times \{0\} \cup \tilde{\mathcal{X}_0} \times \{1\}$ and the counterexample set $D_{\textrm{ce}}$ to an empty set. Optionally, the algorithm also bootstraps the positive invariant network by initializing $D_{\textrm{spec}}$ with random samples from the state space $\mathcal{X}$ labeled with Monte-Carlo estimates of reaching the unsafe states. The rest of the algorithm consists of two modules which are composed into a loop: the {\em learner} and the {\em verifier}. In each loop iteration, the learner first learns a $W^{\pi}_{\epsilon}$-safe positive invariant candidate which takes the form of a neural network $g^{\mathsf{Inv}}$. This is done by minimizing the loss function $\mathcal{L}$ that depends on $D_{\textrm{spec}}$ and $D_{\textrm{ce}}$: \begin{equation}\label{eq:totalloss} \mathcal{L}(g^{\mathsf{Inv}}) = \frac{1}{|D_{\textrm{spec}}|}\sum_{(\mathbf{x},y)\in D_{\textrm{spec}}}^{}\mathcal{L}_{\textrm{cls}}\big(g^\mathsf{Inv}(\mathbf{x}),y\big) +\lambda \frac{1}{|D_{\textrm{ce}}|}\sum_{(\mathbf{x},\mathbf{x}')\in D_{\textrm{ce}}}^{}\mathcal{L}_{\textrm{ce}}\big(g^\mathsf{Inv}(\mathbf{x}),g^\mathsf{Inv}(\mathbf{x}')\big), \end{equation} where $\lambda$ is a tuning parameter and $\mathcal{L}_{\textrm{cls}}$ a binary classification loss function, e.g.~the 0/1-loss $\mathcal{L}_{\textrm{0/1}}(z,y) = \mathds{1}[\mathds{1}[z\geq0]\neq y]$ or the logistic loss $\mathcal{L}_{\textrm{log}}(z,y)= z - z \cdot y + \log(1 + \exp(-z))$ as its differentiable alternative. The term $\mathcal{L}_{\textrm{ce}}$ is the counterexample loss which we define via \begin{equation}\label{eq:loss} \mathcal{L}_{\textrm{ce}}(z,z') = \mathds{1}\big[z>0\big]\mathds{1}\big[z'<0\big] \mathcal{L}_{\textrm{cls}}\big(z,0\big) \mathcal{L}_{\textrm{cls}}\big(z',1\big). \end{equation} Intuitively, the first sum in eq.~\eqref{eq:totalloss} forces $g^{\mathsf{Inv}}$ to be nonnegative at initial states and negative at unsafe states contained in $D_{\textrm{spec}}$, and the second term forces each counterexample in $D_{\textrm{ce}}$ not to destroy the closedness of $\mathsf{Inv}$ under the system dynamics. Once $g^{\mathsf{Inv}}$ is learned, the verifier checks whether $\mathsf{Inv}$ is indeed a $W^{\pi}_{\epsilon}$-safe positive invariant. To do this, the verifier needs to check the three defining properties of $W^{\pi}_{\epsilon}$-safe positive invariants: \begin{compactenum} \item {\em Closedness of $\mathsf{Inv}$ under system dynamics.} The verifier checks if there exist states $\mathbf{x}\in\mathsf{Inv}$, $\mathbf{x'}\not\in\mathsf{Inv}$ and a BNN weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ such that $f(\mathbf{x},\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}))=\mathbf{x}'$. To do this, it introduces real variables $\mathbf{x},\mathbf{x}'\in\mathbb{R}^m$, $\mathbf{u}\in\mathbb{R}^n$ and $y,y'\in\mathbb{R}$, and solves: \begin{equation*} \begin{split} &\textrm{maximize } y - y' \textrm{ subject to} \\ &y\geq 0, y'<0, y=g^{\mathsf{Inv}}(\mathbf{x}), y'=g^{\mathsf{Inv}}(\mathbf{x'}) \\ &\mathbf{x'} = f(\mathbf{x},\mathbf{u}) \\ &\mathbf{u} \text{ is an output of } \pi \text{ on input } \mathbf{x} \textrm{ and weights } (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon} \end{split} \end{equation*} The conditions $y=g^{\mathsf{Inv}}(\mathbf{x})$ and $y'=g^{\mathsf{Inv}}(\mathbf{x'})$ are encoded by using the existing techniques for encoding deterministic NNs as systems of MILP/Reluplex/NRA-SMT constraints. The condition in the third equation is encoded simply by plugging variable vectors $\mathbf{x}$ and $\mathbf{u}$ into the equation for $f$. Finally, for condition in the fourth equation we use our encoding from Section~\ref{sec:feedforward} where we only need to omit the Input-output condition. The optimization objective is added in order to search for the ``worst'' counterexample. We note that MILP~\citep{gurobi} and SMT~\citep{gao2012delta} solvers allow optimizing linear objectives, and recently Reluplex algorithm~\citep{KatzBDJK17} has also been extended to allow solving optimization problems~\citep{strong2020global}. If a counterexample $(\mathbf{x},\mathbf{x}')$ is found, it is added to $D_{\textrm{ce}}$ and the learner tries to learn a new candidate. If the system of constraints is unsatisfiable, the verifier proceeds to the second check. \item {\em Non-negativity on $\mathcal{X}_0$.} The verifier checks if there exists $\mathbf{x}\in\mathcal{X}_0$ for which $g^{\mathsf{Inv}}(\mathbf{x})< 0$. If such $\mathbf{x}$ is found, $(\mathbf{x},1)$ is added to $D_{\textrm{spec}}$ and the learner then tries to learn a new candidate. If the system of constraints is unsatisfiable, the verifier proceeds to the third check. \item {\em Negativity on $\mathcal{X}_u$.} The verifier checks if there exists $\mathbf{x}\in\mathcal{X}_u$ with $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$. If such $\mathbf{x}$ is found, $(\mathbf{x},0)$ is added to $D_{\textrm{spec}}$ and the learner then tries to learn a new candidate. If the system of constraints is unsatisfiable, the veririfer concludes that $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-positive invariant which does not contain any unsafe state and so each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{compactenum} Theorem~\ref{thm:loss} shows that neural networks $f^{\mathsf{Inv}}$ for which $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariants are global minimizers of the loss function $\mathcal{L}$ with the 0/1-classification loss. Theorem~\ref{thm:correctness} establishes the correctness of our algorithm. Proofs can be found in the Supplementary Material. \begin{theorem}\label{thm:loss} The loss function $\mathcal{L}$ is nonnegative for any neural network $g$, i.e.~$\mathcal{L}(g)\geq 0$. Moreover, if $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant and $\mathcal{L}_{\textrm{cls}}$ the 0/1-loss, then $\mathcal{L}(g^{\mathsf{Inv}})=0$. Hence, neural networks $g^{\mathsf{Inv}}$ for which $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant are global minimizers of the loss function $\mathcal{L}$ when $\mathcal{L}_{\textrm{cls}}$ is the 0/1-loss. \end{theorem} \begin{theorem}\label{thm:correctness} If the verifier in Algorithm~\ref{algorithm:ce} shows that constraints in three checks are unsatisfiable, then the computed $\mathsf{Inv}$ is indeed a $W^{\pi}_{\epsilon}$-safe positive invariant. Hence, Algorithm~\ref{algorithm:ce} is correct. \end{theorem} \textbf{Safety via rejection sampling} As discussed in Section~\ref{sec:intro}, once the safety of all trajectories in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ has been verified, we can ``re-calibrate'' the BNN policy to reject sampled weights which are not in $W^{\pi}_{\epsilon}$. Hence, rejection sampling gives rise to a safe BNN policy. \subsection{Computation of safe weight sets and the value of $\epsilon$}\label{sec:epscompute} Problems~\ref{problem1} and~\ref{problem2} assume a given value of $\epsilon$ for which safety needs to be verified. In order to compute the largest value of $\epsilon$ for which our approach can verify safety, we start with a small value of $\epsilon$ and iteratively increase it until we reach a value that cannot be certified or until the timeout is reached, in order to compute as large safe weight set as possible. In each iteration, our Algorithm \ref{algorithm:ce} does not start from scratch but is initialized with the $g^{\mathsf{Inv}}$ and $D_{\textrm{spec}}$ from the previous successful iteration, i.e.~attempting to enlarge the current safe weight set. Our iterative process significantly speeds up the search process compared to naively restarting our algorithm in every iteration. \subsection{Safe exploration reinforcement learning}\label{sec:safeexploration} Given a safe but non-optimal initial policy $\pi_{0}$, safe exploration reinforcement learning (SERL) concerns the problem of improving the expected return of $\pi_{0}$ while ensuring safety when collecting samples of the environment \citep{uchibe2007constrained,achiam2017constrained,nakka2020chance}. Our method from Section~\ref{sec:loopcertificate} for computing safe weight sets can be adapted to this setting with minimal effort. In particular, the safety bound $\epsilon$ for the intervals centered at the weight means can be used in combination with the rejection sampling to generate safe but randomized rollouts on the environment. Moreover, $\epsilon$ provides bounds on the gradient updates when optimizing the policy using Deep Q-learning or policy gradient methods, i.e., performing \emph{projected gradient descent}. We sketch an algorithm for SERL in the Supplementary Material. \section{Conclusion}\label{sec:conclusion} In this work we formulated the safety verification problem for BNN policies in infinite time horizon systems, that asks to compute safe BNN weight sets for which every system execution is safe as long as the BNN samples its weights from this set. Solving this problem allows re-calibrating the BNN policy to reject unsafe weight samples in order to guarantee system safety. We then introduced a methodology for computing safe weight sets in BNN policies in the form of products of intervals around the BNN weight's means, and a method for verifying their safety by learning a positive invariant-like safety certificate. We believe that our results present an important first step in guaranteeing safety of BNNs for deployment in safety-critical scenarios. While adopting products of intervals around the BNN's weight means is a natural choice given that BNN priors are typically unimodal distributions, this is still a somewhat restrictive shape for safe weight sets. Thus, an interesting direction of future work would be to study more general forms of safe weight sets that could be used for re-calibration of BNN posteriors and their safety verification. Another interesting problem would be to design an approach for refuting a weight set as unsafe which would complement our method, or to consider closed-loop systems with stochastic environment dynamics. Any verification method for neural networks, even more so for neural networks in feedback loops, suffers from scalability limitations due to the underlying complexity class \cite{KatzBDJK17,IvanovWAPL19}. Promising research directions on improving the scalability of our approach by potentially speeding up the constraint solving step are gradient based optimization techniques \cite{HenriksenL20} and to incorporate the constraint solving step already in the training procedure \cite{ZhangCXGSLBH20}. Since the aim of AI safety is to ensure that systems do not behave in undesirable ways and that safety violating events are avoided, we are not aware of any potential negative societal impacts. \section*{Acknowledgments} This research was supported in part by the Austrian Science Fund (FWF) under grant Z211-N23 (Wittgenstein Award), ERC CoG 863818 (FoRM-SMArt), and the European Union’s Horizon 2020 research and innovation programme under the Marie Skłodowska-Curie Grant Agreement No. 665385. \bibliographystyle{plainnat} \section{Submission of papers to NeurIPS 2021} Please read the instructions below carefully and follow them faithfully. \subsection{Style} Papers to be submitted to NeurIPS 2021 must be prepared according to the instructions presented here. Papers may only be up to {\bf nine} pages long, including figures. Additional pages \emph{containing only acknowledgments and references} are allowed. Papers that exceed the page limit will not be reviewed, or in any other way considered for presentation at the conference. The margins in 2021 are the same as those in 2007, which allow for $\sim$$15\%$ more words in the paper compared to earlier years. Authors are required to use the NeurIPS \LaTeX{} style files obtainable at the NeurIPS website as indicated below. Please make sure you use the current files and not previous versions. Tweaking the style files may be grounds for rejection. \subsection{Retrieval of style files} The style files for NeurIPS and other conference information are available on the World Wide Web at \begin{center} \url{http://www.neurips.cc/} \end{center} The file \verb+neurips_2021.pdf+ contains these instructions and illustrates the various formatting requirements your NeurIPS paper must satisfy. The only supported style file for NeurIPS 2021 is \verb+neurips_2021.sty+, rewritten for \LaTeXe{}. \textbf{Previous style files for \LaTeX{} 2.09, Microsoft Word, and RTF are no longer supported!} The \LaTeX{} style file contains three optional arguments: \verb+final+, which creates a camera-ready copy, \verb+preprint+, which creates a preprint for submission to, e.g., arXiv, and \verb+nonatbib+, which will not load the \verb+natbib+ package for you in case of package clash. \paragraph{Preprint option} If you wish to post a preprint of your work online, e.g., on arXiv, using the NeurIPS style, please use the \verb+preprint+ option. This will create a nonanonymized version of your work with the text ``Preprint. Work in progress.'' in the footer. This version may be distributed as you see fit. Please \textbf{do not} use the \verb+final+ option, which should \textbf{only} be used for papers accepted to NeurIPS. At submission time, please omit the \verb+final+ and \verb+preprint+ options. This will anonymize your submission and add line numbers to aid review. Please do \emph{not} refer to these line numbers in your paper as they will be removed during generation of camera-ready copies. The file \verb+neurips_2021.tex+ may be used as a ``shell'' for writing your paper. All you have to do is replace the author, title, abstract, and text of the paper with your own. The formatting instructions contained in these style files are summarized in Sections \ref{gen_inst}, \ref{headings}, and \ref{others} below. \section{General formatting instructions} \label{gen_inst} The text must be confined within a rectangle 5.5~inches (33~picas) wide and 9~inches (54~picas) long. The left margin is 1.5~inch (9~picas). Use 10~point type with a vertical spacing (leading) of 11~points. Times New Roman is the preferred typeface throughout, and will be selected for you by default. Paragraphs are separated by \nicefrac{1}{2}~line space (5.5 points), with no indentation. The paper title should be 17~point, initial caps/lower case, bold, centered between two horizontal rules. The top rule should be 4~points thick and the bottom rule should be 1~point thick. Allow \nicefrac{1}{4}~inch space above and below the title to rules. All pages should start at 1~inch (6~picas) from the top of the page. For the final version, authors' names are set in boldface, and each name is centered above the corresponding address. The lead author's name is to be listed first (left-most), and the co-authors' names (if different address) are set to follow. If there is only one co-author, list both author and co-author side by side. Please pay special attention to the instructions in Section \ref{others} regarding figures, tables, acknowledgments, and references. \section{Headings: first level} \label{headings} All headings should be lower case (except for first word and proper nouns), flush left, and bold. First-level headings should be in 12-point type. \subsection{Headings: second level} Second-level headings should be in 10-point type. \subsubsection{Headings: third level} Third-level headings should be in 10-point type. \paragraph{Paragraphs} There is also a \verb+\paragraph+ command available, which sets the heading in bold, flush left, and inline with the text, with the heading followed by 1\,em of space. \section{Citations, figures, tables, references} \label{others} These instructions apply to everyone. \subsection{Citations within the text} The \verb+natbib+ package will be loaded for you by default. Citations may be author/year or numeric, as long as you maintain internal consistency. As to the format of the references themselves, any style is acceptable as long as it is used consistently. The documentation for \verb+natbib+ may be found at \begin{center} \url{http://mirrors.ctan.org/macros/latex/contrib/natbib/natnotes.pdf} \end{center} Of note is the command \verb+\citet+, which produces citations appropriate for use in inline text. For example, \begin{verbatim} \citet{hasselmo} investigated\dots \end{verbatim} produces \begin{quote} Hasselmo, et al.\ (1995) investigated\dots \end{quote} If you wish to load the \verb+natbib+ package with options, you may add the following before loading the \verb+neurips_2021+ package: \begin{verbatim} \PassOptionsToPackage{options}{natbib} \end{verbatim} If \verb+natbib+ clashes with another package you load, you can add the optional argument \verb+nonatbib+ when loading the style file: \begin{verbatim} \usepackage[nonatbib]{neurips_2021} \end{verbatim} As submission is double blind, refer to your own published work in the third person. That is, use ``In the previous work of Jones et al.\ [4],'' not ``In our previous work [4].'' If you cite your other papers that are not widely available (e.g., a journal paper under review), use anonymous author names in the citation, e.g., an author of the form ``A.\ Anonymous.'' \subsection{Footnotes} Footnotes should be used sparingly. If you do require a footnote, indicate footnotes with a number\footnote{Sample of the first footnote.} in the text. Place the footnotes at the bottom of the page on which they appear. Precede the footnote with a horizontal rule of 2~inches (12~picas). Note that footnotes are properly typeset \emph{after} punctuation marks.\footnote{As in this example.} \subsection{Figures} \begin{figure} \centering \fbox{\rule[-.5cm]{0cm}{4cm} \rule[-.5cm]{4cm}{0cm}} \caption{Sample figure caption.} \end{figure} All artwork must be neat, clean, and legible. Lines should be dark enough for purposes of reproduction. The figure number and caption always appear after the figure. Place one line space before the figure caption and one line space after the figure. The figure caption should be lower case (except for first word and proper nouns); figures are numbered consecutively. You may use color figures. However, it is best for the figure captions and the paper body to be legible if the paper is printed in either black/white or in color. \subsection{Tables} All tables must be centered, neat, clean and legible. The table number and title always appear before the table. See Table~\ref{sample-table}. Place one line space before the table title, one line space after the table title, and one line space after the table. The table title must be lower case (except for first word and proper nouns); tables are numbered consecutively. Note that publication-quality tables \emph{do not contain vertical rules.} We strongly suggest the use of the \verb+booktabs+ package, which allows for typesetting high-quality, professional tables: \begin{center} \url{https://www.ctan.org/pkg/booktabs} \end{center} This package was used to typeset Table~\ref{sample-table}. \begin{table} \caption{Sample table title} \label{sample-table} \centering \begin{tabular}{lll} \toprule \multicolumn{2}{c}{Part} \\ \cmidrule(r){1-2} Name & Description & Size ($\mu$m) \\ \midrule Dendrite & Input terminal & $\sim$100 \\ Axon & Output terminal & $\sim$10 \\ Soma & Cell body & up to $10^6$ \\ \bottomrule \end{tabular} \end{table} \section{Final instructions} Do not change any aspects of the formatting parameters in the style files. In particular, do not modify the width or length of the rectangle the text should fit into, and do not change font sizes (except perhaps in the \textbf{References} section; see below). Please note that pages should be numbered. \section{Preparing PDF files} Please prepare submission files with paper size ``US Letter,'' and not, for example, ``A4.'' Fonts were the main cause of problems in the past years. Your PDF file must only contain Type 1 or Embedded TrueType fonts. Here are a few instructions to achieve this. \begin{itemize} \item You should directly generate PDF files using \verb+pdflatex+. \item You can check which fonts a PDF files uses. In Acrobat Reader, select the menu Files$>$Document Properties$>$Fonts and select Show All Fonts. You can also use the program \verb+pdffonts+ which comes with \verb+xpdf+ and is available out-of-the-box on most Linux machines. \item The IEEE has recommendations for generating PDF files whose fonts are also acceptable for NeurIPS. Please see \url{http://www.emfield.org/icuwb2010/downloads/IEEE-PDF-SpecV32.pdf} \item \verb+xfig+ "patterned" shapes are implemented with bitmap fonts. Use "solid" shapes instead. \item The \verb+\bbold+ package almost always uses bitmap fonts. You should use the equivalent AMS Fonts: \begin{verbatim} \usepackage{amsfonts} \end{verbatim} followed by, e.g., \verb+\mathbb{R}+, \verb+\mathbb{N}+, or \verb+\mathbb{C}+ for $\mathbb{R}$, $\mathbb{N}$ or $\mathbb{C}$. You can also use the following workaround for reals, natural and complex: \begin{verbatim} \newcommand{\RR}{I\!\!R} \newcommand{\Nat}{I\!\!N} \newcommand{\CC}{I\!\!\!\!C} \end{verbatim} Note that \verb+amsfonts+ is automatically loaded by the \verb+amssymb+ package. \end{itemize} If your file contains type 3 fonts or non embedded TrueType fonts, we will ask you to fix it. \subsection{Margins in \LaTeX{}} Most of the margin problems come from figures positioned by hand using \verb+\special+ or other commands. We suggest using the command \verb+\includegraphics+ from the \verb+graphicx+ package. Always specify the figure width as a multiple of the line width as in the example below: \begin{verbatim} \usepackage[pdftex]{graphicx} ... \includegraphics[width=0.8\linewidth]{myfile.pdf} \end{verbatim} See Section 4.4 in the graphics bundle documentation (\url{http://mirrors.ctan.org/macros/latex/required/graphics/grfguide.pdf}) A number of width problems arise when \LaTeX{} cannot properly hyphenate a line. Please give LaTeX hyphenation hints using the \verb+\-+ command when necessary. \begin{ack} Use unnumbered first level headings for the acknowledgments. All acknowledgments go at the end of the paper before the list of references. Moreover, you are required to declare funding (financial activities supporting the submitted work) and competing interests (related financial activities outside the submitted work). More information about this disclosure can be found at: \url{https://neurips.cc/Conferences/2021/PaperInformation/FundingDisclosure}. Do {\bf not} include this section in the anonymized submission, only in the final paper. You can use the \texttt{ack} environment provided in the style file to autmoatically hide this section in the anonymized submission. \end{ack} \section*{References} References follow the acknowledgments. Use unnumbered first-level heading for the references. Any choice of citation style is acceptable as long as you are consistent. It is permissible to reduce the font size to \verb+small+ (9 point) when listing the references. Note that the Reference section does not count towards the page limit. \medskip { \small [1] Alexander, J.A.\ \& Mozer, M.C.\ (1995) Template-based algorithms for connectionist rule extraction. In G.\ Tesauro, D.S.\ Touretzky and T.K.\ Leen (eds.), {\it Advances in Neural Information Processing Systems 7}, pp.\ 609--616. Cambridge, MA: MIT Press. [2] Bower, J.M.\ \& Beeman, D.\ (1995) {\it The Book of GENESIS: Exploring Realistic Neural Models with the GEneral NEural SImulation System.} New York: TELOS/Springer--Verlag. [3] Hasselmo, M.E., Schnell, E.\ \& Barkai, E.\ (1995) Dynamics of learning and recall at excitatory recurrent synapses and cholinergic modulation in rat hippocampal region CA3. {\it Journal of Neuroscience} {\bf 15}(7):5249-5262. } \section*{Checklist} The checklist follows the references. Please read the checklist guidelines carefully for information on how to answer these questions. For each question, change the default \answerTODO{} to \answerYes{}, \answerNo{}, or \answerNA{}. You are strongly encouraged to include a {\bf justification to your answer}, either by referencing the appropriate section of your paper or providing a brief inline description. For example: \begin{itemize} \item Did you include the license to the code and datasets? \answerYes{See Section~\ref{gen_inst}.} \item Did you include the license to the code and datasets? \answerNo{The code and the data are proprietary.} \item Did you include the license to the code and datasets? \answerNA{} \end{itemize} Please do not modify the questions and only use the provided macros for your answers. Note that the Checklist section does not count towards the page limit. In your paper, please delete this instructions block and only keep the Checklist section heading above along with the questions/answers below. \begin{enumerate} \item For all authors... \begin{enumerate} \item Do the main claims made in the abstract and introduction accurately reflect the paper's contributions and scope? \answerTODO{} \item Did you describe the limitations of your work? \answerTODO{} \item Did you discuss any potential negative societal impacts of your work? \answerTODO{} \item Have you read the ethics review guidelines and ensured that your paper conforms to them? \answerTODO{} \end{enumerate} \item If you are including theoretical results... \begin{enumerate} \item Did you state the full set of assumptions of all theoretical results? \answerTODO{} \item Did you include complete proofs of all theoretical results? \answerTODO{} \end{enumerate} \item If you ran experiments... \begin{enumerate} \item Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? \answerTODO{} \item Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? \answerTODO{} \item Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? \answerTODO{} \item Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? \answerTODO{} \end{enumerate} \item If you are using existing assets (e.g., code, data, models) or curating/releasing new assets... \begin{enumerate} \item If your work uses existing assets, did you cite the creators? \answerTODO{} \item Did you mention the license of the assets? \answerTODO{} \item Did you include any new assets either in the supplemental material or as a URL? \answerTODO{} \item Did you discuss whether and how consent was obtained from people whose data you're using/curating? \answerTODO{} \item Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? \answerTODO{} \end{enumerate} \item If you used crowdsourcing or conducted research with human subjects... \begin{enumerate} \item Did you include the full text of instructions given to participants and screenshots, if applicable? \answerTODO{} \item Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? \answerTODO{} \item Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? \answerTODO{} \end{enumerate} \end{enumerate} \section{Proofs} \begin{manualtheorem}{1} Let $\epsilon\in[0,\infty]$. Then each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe if and only if the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is not satisfiable. \end{manualtheorem} \begin{proof} We prove the equivalent claim that there exists a weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ for which $\pi_{\mathbf{w},\mathbf{b}}$ is unsafe if and only if $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is satisfiable. \medskip First, suppose that there exists a weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ for which $\pi_{\mathbf{w},\mathbf{b}}$ is unsafe and we want to show that $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is satisfiable. This direction of the proof is straightforward since values of the network's neurons on the unsafe input give rise to a solution of $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Indeed, by assumption there exists a vector of input neuron values $\mathbf{x}_0\in\mathcal{X}_0$ for which the corresponding vector of output neuron values $\mathbf{x}_l=\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}_0)$ is unsafe, i.e.~$\mathbf{x}_l\in\mathcal{X}_u$. By defining $\mathbf{x}_i^{\textrm{in}}$, $\mathbf{x}_i^{\textrm{out}}$ to be the vectors of the corresponding input and output neuron values for the $i$-th hidden layer for each $1\leq i\leq l-1$ and by setting $\mathbf{x}_{0,\textrm{pos}}=\textrm{ReLU}(\mathbf{x_0})$ and $\mathbf{x}_{0,\textrm{neg}}=-\textrm{ReLU}(-\mathbf{x}_0)$, we easily see that these variable values satisfy the Input-output conditions, the ReLU encoding conditions and the BNN input and hidden layer conditions, therefore we get a solution to the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. \medskip We now proceed to the more involved direction of this proof and show that any solution to the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ gives rise to weights $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ for which $\pi_{\mathbf{w},\mathbf{b}}$ is unsafe. Let $\mathbf{x}_0$, $\mathbf{x}_l$, $\mathbf{x}_{0,\textrm{pos}}$, $\mathbf{x}_{0,\textrm{neg}}$ and $\mathbf{x}_i^{\textrm{in}}$, $\mathbf{x}_i^{\textrm{out}}$ for $1\leq i\leq l-1$, be real vectors that satisfy the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Fix $1\leq i\leq l-1$. From the BNN hidden layers constraint for layer i, we have \begin{equation}\label{eq:1} (\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_{i+1}^{\textrm{in}} \leq (\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i+\epsilon\cdot\mathbf{1}). \end{equation} We show that there exist values $\mathbf{W}_i^{\ast},\mathbf{b}_i^{\ast}$ of BNN weights between layers $i$ and $i+1$ such that each weight value is at most $\epsilon$ apart from its mean, and such that $\mathbf{x}_{i+1}^{\textrm{in}}=\mathbf{W}_i^{\ast}\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i^{\ast}$. Indeed, to formally show this, we define $W^{\pi}_{\epsilon}[i]$ to be the set of all weight vectors between layers $i$ and $i+1$ such that each weight value is distant from its mean by at most $\epsilon$ (hence, $W^{\pi}_{\epsilon}[i]$ is a projection of $W^{\pi}_{\epsilon}$ onto dimensions that correspond to the weights between layers $i$ and $i+1$). We then consider a continuous function $h_i:W^{\pi}_{\epsilon}[i]\rightarrow \mathbb{R}$ defined via \begin{equation*} h_i(\mathbf{W}_i,\mathbf{b}_i) = \mathbf{W}_i\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i. \end{equation*} Since $W^{\pi}_{\epsilon}[i]\subseteq\mathbb{R}^{m_i\times n_i}\times\mathbb{R}^{n_i}$ is a product of intervals and therefore a connected set w.r.t.~the Euclidean metric and since $h_i$ is continuous, the image of $W^{\pi}_{\epsilon}[i]$ under $h_i$ is also connected in $\mathbb{R}$. But note that \[ h_i(\mathbf{M}_i-\epsilon\cdot\mathbf{1},\mathbf{m}_i-\epsilon\cdot\mathbf{1})=(\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i-\epsilon\cdot\mathbf{1}) \] and \[ h_i(\mathbf{M}_i+\epsilon\cdot\mathbf{1},\mathbf{m}_i+\epsilon\cdot\mathbf{1})=(\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i+\epsilon\cdot\mathbf{1}), \] with $(\mathbf{M}_i-\epsilon\cdot\mathbf{1},\mathbf{m}_i-\epsilon\cdot\mathbf{1}),(\mathbf{M}_i+\epsilon\cdot\mathbf{1},\mathbf{m}_i+\epsilon\cdot\mathbf{1})\in W^{\pi}_{\epsilon}[i]$. Thus, for the two points to be connected, the image set must also contain $\mathbf{x}_{i+1}^{\textrm{in}}$ which lies in between by eq.~\eqref{eq:1}. Thus, there exists $(\mathbf{W}_i^{\ast},\mathbf{b}_i^{\ast})\in W^{\pi}_{\epsilon}[i]$ with $\mathbf{x}_{i+1}^{\textrm{in}}=\mathbf{W}_i^{\ast}\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i^{\ast}$, as desired. \medskip For the input and the first hidden layer, from the BNN input layer constraint we know that \begin{equation*} (\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_1^{\textrm{in}} \leq (\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0+\epsilon\cdot\mathbf{1}). \end{equation*} Again, define $W^{\pi}_{\epsilon}[0]$ to be the set of all weight vectors between the input and the first hidden layer such that each weight value is distant from its mean by at most $\epsilon$. Consider a continuous function $h_0:W^{\pi}_{\epsilon}[0]\rightarrow \mathbb{R}$ defined via \begin{equation*} h_0(\mathbf{W}_0,\mathbf{b}_0) = \mathbf{W}_0\mathbf{x}_0+\mathbf{b}_0. \end{equation*} Let $\textrm{Msign}(\mathbf{x}_0)$ be a matrix of the same dimension as $\mathbf{M}_0$, with each column consisting of $1$'s if the corresponding component of $\mathbf{x}_0$ is nonnegative, and of $-1$'s if it is negative. Then note that \[ h_0(\mathbf{M}_0-\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0-\epsilon\cdot\mathbf{1})=(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0-\epsilon\cdot\mathbf{1}) \] and \[ h_0(\mathbf{M}_0+\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0+\epsilon\cdot\mathbf{1})=(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0+\epsilon\cdot\mathbf{1}). \] Since $(\mathbf{M}_0-\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0-\epsilon\cdot\mathbf{1}),(\mathbf{M}_0+\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0+\epsilon\cdot\mathbf{1})\in W^{\pi}_{\epsilon}[0]$, analogous image connectedness argument as the one above shows that there exist values $\mathbf{W}_0^{\ast},\mathbf{b}_0^{\ast}$ of BNN weights such tha $(\mathbf{W}_0^{\ast},\mathbf{b}_0^{\ast})\in W^{\pi}_{\epsilon}[0]$, and such that $\mathbf{x}_{1}^{\textrm{in}}=\mathbf{W}_0^{\ast}\mathbf{x}_0+\mathbf{b}_0^{\ast}$. \medskip But now, collecting $\mathbf{W}_0^{\ast},\mathbf{b}_0^{\ast}$ and $\mathbf{W}_i^{\ast},\mathbf{b}_i^{\ast}$ for $1\leq i\leq l-1$ gives rise to a BNN weight vector $(\mathbf{W}^{\ast},\mathbf{b}^{\ast})$ which is contained in $W^{\pi}_{\epsilon}$. Furthermore, combining what we showed above with the constraints in $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$, we get that: \begin{compactitem} \item $\mathbf{x}_0\in \mathcal{X}_0$, $\mathbf{x}_l\in\mathcal{X}_u$, from the Input-output condition in $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$; \item $\mathbf{x}_i^{\textrm{out}} = \textrm{ReLU}(\mathbf{x}_i^{\textrm{in}})$ for each $1\leq i\leq l-1$, from the ReLU-encoding; \item $\mathbf{x}_{1}^{\textrm{in}}=\mathbf{W}_0^{\ast}\mathbf{x}_0+\mathbf{b}_0^{\ast}$ and $\mathbf{x}_{i+1}^{\textrm{in}}=\mathbf{W}_i^{\ast}\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i^{\ast}$ for each $1\leq i\leq l-1$, as shown above. \end{compactitem} Hence, $\mathbf{x}_l\in\mathcal{X}_u$ is the vector of neuron output values of $\pi_{\mathbf{W}^{\ast},\mathbf{b}^{\ast}}$ on the input neuron values $\mathbf{x}_0\in\mathcal{X}_0$, so as $(\mathbf{W}^{\ast},\mathbf{b}^{\ast})\in W^{\pi}_{\epsilon}$ we conclude that there exists a deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ which is not safe. This concludes the proof. \end{proof} \begin{manualtheorem}{2} If there exists a $W^{\pi}_{\epsilon}$-safe positive invariant, then each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{manualtheorem} \begin{proof} Let $\mathsf{Inv}$ be a $W^{\pi}_{\epsilon}$-safe positive invariant. Given a trajectory $(\mathbf{x}_t,\mathbf{u}_t)_{t=0}^{\infty}$ in $\mathsf{Traj}^{f,\pi}_{\epsilon}$, we need to show that $\mathbf{x}_t\not\in\mathcal{X}_u$ for each $t\in\mathbb{N}_{\geq 0}$. Since $\mathsf{Inv}\cap\mathcal{X}_u=\emptyset$, it suffices to show that $\mathbf{x}_t\in\mathsf{Inv}$ for each $t\in\mathbb{N}_{\geq 0}$. We prove this by induction on $t$. The base case $\mathbf{x}_0\in\mathsf{Inv}$ follows since $\mathbf{x}_0\in\mathcal{X}_0\subseteq \mathsf{Inv}$. As an inductive hypothesis, suppose now that $\mathbf{x}_t\in\mathsf{Inv}$ for some $t\in\mathbb{N}_{\geq 0}$. We need to show that $\mathbf{x}_{t+1}\in\mathsf{Inv}$. Since the trajectory is in $\mathsf{Traj}^{f,\pi}_{\epsilon}$, we know that the BNN weight vector $(\mathbf{w}_t,\mathbf{b}_t)$ sampled at the time-step $t$ belongs to $W^{\pi}_{\epsilon}$, i.e.~$(\mathbf{w}_t,\mathbf{b}_t)\in W^{\pi}_{\epsilon}$. Thus, since $\mathbf{x}_t\in\mathsf{Inv}$ by the induction hypothesis and since $\mathsf{Inv}$ is closed under the system dynamics when the sampled weight vector is in $W^{\pi}_{\epsilon}$, it follows that $\mathbf{x}_{t+1}=f(\mathbf{x}_t,\mathbf{u}_t)=f(\mathbf{x}_t,\pi_{\mathbf{w}_t,\mathbf{b}_t}(\mathbf{x}_t))\in \mathsf{Inv}$. This concludes the proof by induction. \end{proof} \begin{manualtheorem}{3} The loss function $\mathcal{L}$ is nonnegative for any neural network $g$, i.e.~$\mathcal{L}(g)\geq 0$. Moreover, if $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant and $\mathcal{L}_{\textrm{cls}}$ the 0/1-loss, then $\mathcal{L}(g^{\mathsf{Inv}})=0$. Hence, neural networks $g^{\mathsf{Inv}}$ for which $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant are global minimizers of the loss function $\mathcal{L}$ when $\mathcal{L}_{\textrm{cls}}$ is the 0/1-loss. \end{manualtheorem} \begin{proof} Recall, the loss function $\mathcal{L}$ for a neural network $g$ is defined via \begin{equation}\label{eq:totallossupmat} \mathcal{L}(g) = \frac{1}{|D_{\textrm{spec}}|}\sum_{(\mathbf{x},y)\in D_{\textrm{spec}}}^{}\mathcal{L}_{\textrm{cls}}\big(g(\mathbf{x}),y\big) +\lambda \frac{1}{|D_{\textrm{ce}}|}\sum_{(\mathbf{x},\mathbf{x}')\in D_{\textrm{ce}}}^{}\mathcal{L}_{\textrm{ce}}\big(g(\mathbf{x}),g(\mathbf{x}')\big), \end{equation} where $\lambda$ is a tuning parameter and $\mathcal{L}_{\textrm{cls}}$ a binary classification loss function, e.g.~the 0/1-loss $\mathcal{L}_{\textrm{0/1}}(z,y) = \mathds{1}[\mathds{1}[z\geq0]\neq y]$ or the logistic loss $\mathcal{L}_{\textrm{log}}(z,y)= z - z \cdot y + \log(1 + \exp(-z))$ as its differentiable alternative. The term $\mathcal{L}_{\textrm{ce}}$ is the counterexample loss which we define via \begin{equation}\label{eq:losssupmat} \mathcal{L}_{\textrm{ce}}(z,z') = \mathds{1}\big[z>0\big]\mathds{1}\big[z'<0\big] \mathcal{L}_{\textrm{cls}}\big(z,0\big) \mathcal{L}_{\textrm{cls}}\big(z',1\big). \end{equation} The fact that $\mathcal{L}(g)\geq 0$ for each neural network $g$ follows immediately from the fact that summands in the first sum in eq.~\eqref{eq:totallossupmat} are loss functions which are nonnegative, and summands in the second sum are products of indicator and nonnegative loss functions and therefore also nonnegative. We now show that, if $\mathcal{L}_{\textrm{cls}}$ is the 0/1-loss, $\mathcal{L}(g^{\mathsf{Inv}})=0$ whenever $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant, which implies the global minimization claim in the theorem. This follows from the following two items: \begin{compactitem} \item For each $(\mathbf{x},y)\in D_{\textrm{spec}}$, we have $\mathcal{L}_{\textrm{cls}}\big(g^{\mathsf{Inv}}(\mathbf{x}),y\big)=0$. Indeed, for $(\mathbf{x},y)$ to be added to $D_{\textrm{spec}}$ in Algorithm~1, we must have that either $\mathbf{x}\in\mathcal{X}_0$ and $y=1$, or that $\mathbf{x}\in\mathcal{X}_u$ and $y=0$. Thus, since $\mathsf{Inv}$ is assumed to be a $W^{\pi}_{\epsilon}$-safe positive invariant, $g^{\mathsf{Inv}}$ correctly classifies $(\mathbf{x},y)$ and the corresponding loss is $0$. \item For each $(\mathbf{x},\mathbf{x}')\in D_{\textrm{ce}}$ we have $\mathcal{L}_{\textrm{ce}}\big(g^{\mathsf{Inv}}(\mathbf{x}),g^{\mathsf{Inv}}(\mathbf{x}')\big)=0$. Indeed, since \[ \mathcal{L}_{\textrm{ce}}(g^{\mathsf{Inv}}(\mathbf{x}),g^{\mathsf{Inv}}(\mathbf{x}')) = \mathds{1}\big[g^{\mathsf{Inv}}(\mathbf{x})>0\big]\mathds{1}\big[g^{\mathsf{Inv}}(\mathbf{x}')<0\big] \mathcal{L}_{\textrm{cls}}\big(g^{\mathsf{Inv}}(\mathbf{x}),0\big) \mathcal{L}_{\textrm{cls}}\big(g^{\mathsf{Inv}}(\mathbf{x}'),1\big), \] for the loss to be non-zero we must have that $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and $g^{\mathsf{Inv}}(\mathbf{x})<0$. But this is impossible since $\mathsf{Inv}$ is assumed to be a $W^{\pi}_{\epsilon}$-safe positive invariant and $(\mathbf{x},\mathbf{x}')$ was added by Algorithm~1 as a counterexample to $D_{\textrm{ce}}$, meaning that $\mathbf{x}'$ can be reached from $\mathbf{x}$ by following the dynamics function and sampling a BNN weight vector in $W^{\pi}_{\epsilon}$. Therefore, by the closedness property of $W^{\pi}_{\epsilon}$-safe positive invariants when the sampled weight vector is in $W^{\pi}_{\epsilon}$, we cannot have both $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and $g^{\mathsf{Inv}}(\mathbf{x})<0$. Hence, the loss must be $0$. \end{compactitem} \end{proof} \begin{manualtheorem}{4} If the verifier in Algorithm~1 shows that constraints in three checks are unsatisfiable, then the computed $\mathsf{Inv}$ is indeed a $W^{\pi}_{\epsilon}$-safe positive invariant. Hence, Algorithm~1 is correct. \end{manualtheorem} \begin{proof} The fact that the first check in Algorithm~1 correctly checks whether there exist $\mathbf{x},\mathbf{x}'\in\mathcal{X}_0$ and a weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ such that $\mathbf{x}'=f(\mathbf{x},\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}))$ with $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and $g^{\mathsf{Inv}}(\mathbf{x}')<0$ follows by the correctness of our encoding in Section~4.1, which was proved in Theorem~1. The fact that checks 2 and 3 correctly check whether for all $\mathbf{x}\in\mathcal{X}_0$ we have $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and for all $\mathbf{x}\in\mathcal{X}_u$ we have $g^{\mathsf{Inv}}(\mathbf{x})<0$, respectively, follows immediately from the conditions they encode. Therefore, the three checks together verify that (1)~$\mathsf{Inv}$ is closed under the system dynamics whenever the sampled weight vector is in $W^{\pi}_{\epsilon}$, (2)~$\mathsf{Inv}$ contains all initial states, and (3)~$\mathsf{Inv}$ contains no unsafe states. As these are the $3$ defining properties of $W^{\pi}_{\epsilon}$-safe positive invariants, Algorithm~1 is correct and the theorem claim follows. \end{proof} \section{Safe exploration reinforcement learning algorithm} Algorithm \ref{algorithm:serl} shows our sketch of how standard RL algorithms, such as policy gradient methods and deep Q-learning, can be adapted to a safe exploration setup by using the safe weight sets computed by our method. \begin{algorithm}[t] \caption{Safe Exploration Reinforcement Learning} \label{algorithm:serl} \begin{algorithmic} \STATE \textbf{Input} Initial policy $\pi_{0}$, learning rate $\alpha$, number of iterations $N$ \FOR{$i \in 1,\dots N$} \STATE $\epsilon \leftarrow$ find safe $\epsilon$ for $\pi_{i-1}$ \STATE collect rollouts of $\pi_{i-1}$ with rejection sampling $\epsilon$ \STATE compute $\nabla \mu_{i-1}$ for parameters $\mu_{i-1}$ of $\pi_{i-1}$ using DQN/policy gradient \STATE $\mu_i \leftarrow \mu_{i-1} - \alpha \nabla \mu_{i-1}$ (gradient descent) \STATE project $\mu_i$ back to interval $[\mu_{i-1}-\epsilon,\mu_{i-1}+\epsilon]$ \ENDFOR \STATE \textbf{Return} $\pi_{N}$ \end{algorithmic} \end{algorithm} \section{Experimental details} In this section, we describe the details of our experimental evaluation setup. The code and pre-trained network parameters are attached in the supplementary materials. Each policy is a ReLU network consisting of three layers. The first layer represents the input variables, the second one is a hidden layer with 16 neurons, and the last layer are the output variables. The size of the first and the last layer is task dependent and is shown in Table \ref{tab:epx}. The $W^{\pi}_{\epsilon}$-safe positive invariant candidate network differs from the policy network in that its weights are deterministic, it has a different number of hidden units and a single output dimension. Particularly, the invariant networks for the linear dynamical system and the inverted pendulum have 12 hidden units, whereas the invariant network for the collision avoidance task has 32 neurons in its hidden layer. The policy networks are trained with a $\mathcal{N}(0,0.1)$ (from second layer on) and $\mathcal{N}(0,0.05)$ (all weights) prior for the Bayesian weights, respectively. MILP solving was performed by Gurobi 9.03 on a 4 vCPU with 32GB virtual machine. \begin{table}[] \centering \begin{tabular}{c|ccc}\toprule Experiment & Input dimension & Hidden size & Output dimension \\\midrule Linear dynamical system & 2 & 16 & 1 \\ Inverted pendulum & 2 & 16 & 1 \\ Collision avoidance & 3 & 16 & 3\\\bottomrule \end{tabular} \caption{Number of dimensions of the policy network for the three experiments.} \label{tab:epx} \end{table} \paragraph{Linear dynamical system} The state of the linear dynamical system consists of two variables $(x,y)$. The update function takes the current state $(x_t,y_t)$ with the current action $u_t$ and outputs the next states $(x_{t+1},y_{t+1})$ governed by the equations \begin{align*} y_{t+1} &= y_t + 0.2\cdot \textrm{clip}_{\pm 1}(u_t)\\ x_{t+1} &= x_t + 0.3 y_{t+1} + 0.05\cdot \textrm{clip}_{\pm 1}(u_t),\\ \end{align*} where the function $\text{clip}_{\pm 1}$ is defined by \begin{equation*} \textrm{clip}_{\pm z}(x) = \begin{cases}-z & \text{ if } x\leq -z\\ z & \text{ if } x\geq z\\ x & \text{ otherwise. }\end{cases} \end{equation*} The set of unsafe states is defined as $\{(x,y)\in\mathbb{R}^2\mid|(x,y)|_{\infty}\geq 1.2\}$, and the initial states as $\{(x,y)\in\mathbb{R}^2\mid |(x,y)|_{\infty}\leq 0.6\}$. \paragraph{Inverted pendulum} The state of the inverted pendulum consists of two variables $(\theta,\dot{\theta})$. The non-linear state transition is defined by \begin{align*} \dot{\theta}_{t+1} &= \textrm{clip}_{\pm 8}\big(\dot{\theta}_t + \frac{-3g\cdot \textrm{angular}(\theta_t + \pi)}{2l} + \delta_t\frac{7.5 \textrm{clip}_{\pm 1}(u_t)}{(m\cdot l^2)}\big)\\ \theta_{t+1} &= \theta_t + \dot{\theta}_{t+1} * \delta_t, \end{align*} where $g=9.81,l=1,\delta_t=0.05$ and $m=0.8$ are constants. The function $\textrm{angular}$ is defined using the piece-wise linear composition \begin{equation*} \textrm{angular}(x) = \begin{cases} \textrm{angular}(x+2\pi) & \text{ if } x \leq \pi / 2\\ \textrm{angular}(x-2\pi) & \text{ if } x > 5 \pi / 2\\ \frac{x - 2\pi}{\pi / 2} & \text{ if } 3 \pi / 2 < x \leq 5 \pi / 2\\ 2 - \frac{x}{\pi / 2} & \text{ if } \pi / 2 < x \leq 3 \pi / 2. \end{cases} \end{equation*} The set of initial states are defined by $\{(\theta,\dot{\theta})\in\mathbb{R}^2\mid |\theta| \leq \pi/6 \text{ and } |\dot{\theta}|\leq0.2 \}$. The set of unsafe states are defined by $\{(\theta,\dot{\theta})\in\mathbb{R}^2\mid |\theta| \geq 0.9 \text{ or } |\dot{\theta}|\geq2 \}$. \paragraph{Collision avoidance} The state of the collision avoidance environment consists of three variables $(p_x,a_x,a_y)$, representing the agent's vertical position and the vertical and the horizontal position of an intruder. The intruder moves toward the agent, while the agent's vertical position must be controlled to avoid colliding with the intruder. The particular state transition is given by \begin{align*} p_{x,t+1} &= p_{x,t} + u_{t}\\ a_{x,t+1} &= a_{x,t}\\ a_{y,t+1} &= a_{y,t} - 1.\\ \end{align*} Admissible actions are defined by $u_t \in \{-1,0,1\}$. The set of initial states are defined as $\{(p_x,a_x,a_y)\in\mathbb{Z}^3\mid |p_x|\leq 2 \text{ and } |a_x|\leq 2 \text{ and } a_y=5\}$. Likewise, the set of unsafe states are given by $\{(p_x,a_x,a_y)\in\mathbb{Z}^3\mid |p_x-a_x|\leq 1 \text{ and } a_y=5\}$. \section{Conclusion}\label{sec:conclusion} In this work we formulated the safety verification problem for BNN policies in infinite time horizon systems, that asks to compute safe BNN weight sets for which every system execution is safe as long as the BNN samples its weights from this set. Solving this problem allows re-calibrating the BNN policy to reject unsafe weight samples in order to guarantee system safety. We then introduced a methodology for computing safe weight sets in BNN policies in the form of products of intervals around the BNN weight's means, and a method for verifying their safety by learning a positive invariant-like safety certificate. We believe that our results present an important first step in guaranteeing safety of BNNs for deployment in safety-critical scenarios. While adopting products of intervals around the BNN's weight means is a natural choice given that BNN priors are typically unimodal distributions, this is still a somewhat restrictive shape for safe weight sets. Thus, an interesting direction of future work would be to study more general forms of safe weight sets that could be used for re-calibration of BNN posteriors and their safety verification. Another interesting problem would be to design an approach for refuting a weight set as unsafe which would complement our method, or to consider closed-loop systems with stochastic environment dynamics. Any verification method for neural networks, even more so for neural networks in feedback loops, suffers from scalability limitations due to the underlying complexity class \cite{KatzBDJK17,IvanovWAPL19}. Promising research directions on improving the scalability of our approach by potentially speeding up the constraint solving step are gradient based optimization techniques \cite{HenriksenL20} and to incorporate the constraint solving step already in the training procedure \cite{ZhangCXGSLBH20}. Since the aim of AI safety is to ensure that systems do not behave in undesirable ways and that safety violating events are avoided, we are not aware of any potential negative societal impacts. \section{Experiments}\label{sec:exp} We perform an experimental evaluation of our proposed method for learning positive invariant neural networks that prove infinite time horizon safety. Our evaluation consists of an ablation study where we disable different core components of Algorithm~\ref{algorithm:ce} and measure their effects on the obtained safety bounds and the algorithm's runtime. First, we run the algorithm without any re-training on the counterexamples. In the second step, we run Algorithm~\ref{algorithm:ce} by initializing $D_{\textrm{spec}}$ with samples from $\mathcal{X}_0$ and $\mathcal{X}_u$ only. Finally, we bootstrap the positive invariant network by initializing $D_{\textrm{spec}}$ with random samples from the state space labeled with Monte-Carlo estimates of reaching the unsafe states. We consider environments with a piecewise linear dynamic function, initial and unsafe state sets so that the verification steps of our algorithm can be reduced to MILP-solving using Gurobi \cite{gurobi}. Details on our evaluation are in the Supplementary Material. Code is publicly available \footnote{\url{https://github.com/mlech26l/bayesian_nn_safety}}. We conduct our evaluation on three benchmark environments that differ in terms of complexity and safety specifications. We train two BNN policies for each benchmark-ablation pair, one with Bayesian weights from the second layer on (with $\mathcal{N}(0,0.1)$ prior) and one with Bayesian weights in all layers (with $\mathcal{N}(0,0.05)$ prior). Recall, in our BNN encoding in Section~\ref{sec:feedforward}, we showed that encoding of the BNN input layer requires additional constraints and extra care, since we do not know the signs of input neuron values. Hence, we consider two BNN policies in our evaluation in order to study how the encoding of the input layer affects the safe weight set computation. Our first benchmark represents an unstable linear dynamical system of the form $x_{t+1} = Ax_t + Bu_t$. A BNN policy stabilizes the system towards the point $(0,0)$. Consequently, the set of unsafe states is defined as $\{x\in\mathbb{R}^2\mid|x|_{\infty}\geq 1.2\}$, and the initial states as $\{x\in\mathbb{R}^2\mid |x|_{\infty}\leq 0.6\}$. Our second benchmark is the inverted pendulum task, which is a classical non-linear control problem. The two state variables $a$ and $b$ represent the angle and angular velocity of a pendulum that must be controlled in an upward direction. The actions produced by the policy correspond to a torque applied to the anchor point. Our benchmark concerns a variant of the original problem where the non-linearity in $f$ is expressed by piecewise linear functions. The resulting system, even with a trained policy, is highly unstable, as shown in Figure~\ref{fig:pend}. The set of initial states corresponds to pendulum states in an almost upright position and with small angular velocity. The set of unsafe states represents the pendulum falling down. Figure~\ref{fig:pend} visualizes the system and the learned invariant's decision boundary for the inverted pendulum task. \begin{figure} \centering \subcaptionbox{Vector field of the system when controlled by the posterior's mean. Green/red arrows indicate empirical safe/unsafe estimates.}% [.31\linewidth]{\includegraphics[width=0.25\textwidth]{plots/vector_field.png}} \hfill \subcaptionbox{First guess of $g^{\mathsf{Inv}}$. Green area shows $g^{\mathsf{Inv}}>0$, orange area $g^{\mathsf{Inv}}<0$. Red markers show the found counterexample.}% [.31\linewidth]{\includegraphics[width=0.25\textwidth]{plots/step0.png}} \hfill \subcaptionbox{Final $g^{\mathsf{Inv}}$ proving the safety of the system. Previous counterexamples marked in red.}% [.31\linewidth]{\includegraphics[width=0.25\textwidth]{plots/step2.png}} \caption{Invariant learning shown on the inverted pendulum benchmark.} \label{fig:pend} \end{figure} \begin{table}[] \centering \caption{Results of our benchmark evaluation. The epsilon values are multiples of the weight's standard deviation $\sigma$. We evaluated several epsilon values, and the table shows the largest that could be proven safe. A dash ''-'' indicates an unsuccessful invariant search. Runtime in seconds.} \begin{tabular}{l|rr|rr|rr}\toprule \multirow{2}{*}{Environment} & \multicolumn{2}{c|}{No re-training} & \multicolumn{2}{c|}{Init $D_{spec}$ with $\mathcal{X}_0$ and $\mathcal{X}_u$} & \multicolumn{2}{c}{Bootstrapping $D_{spec}$} \\ & Verified & Runtime & Verified & Runtime & Verified & Runtime \\\cmidrule(r){1-7} Unstable LDS & - & 3 & $1.5\sigma$ & 569 & $2\sigma$ & 760 \\ Unstable LDS (all) & $0.2\sigma$ & 3 & $0.5\sigma$ & 6 & $0.5\sigma$ & 96 \\ Pendulum & - & 2 & $2\sigma$ & 220 & $2\sigma$ & 40 \\ Pendulum (all) & - & 2 & $0.2\sigma$ & 1729 & $1.5\sigma$ & 877 \\ Collision avoid. & - & 2 & - & - & $2\sigma$ & 154 \\ Collision avoid. (all) & - & 2 & - & - & $1.5\sigma$ & 225 \\\bottomrule \end{tabular} \label{tab:results} \end{table} While the previous two benchmarks concern stability specifications, we evaluate our method on a non-Lyapunovian safety specification in our third benchmark. In particular, our third benchmark is a collision avoidance task, where the system does not stabilize to the same set of terminal states in every execution. The system is described by three variables. The first variable specifies the agent's own vertical location, while the other two variables specify an intruder's vertical and horizontal position. The objective is to avoid colliding with the intruder who is moving toward the agent by lateral movement commands as the policy's actions. The initial states represent far-away intruders, and crashes with the intruder define the unsafe states. Table \ref{tab:results} shows the results of our evaluation. Our results demonstrate that re-training with the counterexamples is the key component that determines our algorithm's success. In all cases, except for the linear dynamical system, the initial guess of the invariant candidate violates the invariant condition. Moreover, boostrapping $D_{\textrm{spec}}$ with random points labeled by empirical estimates of reaching the unsafe states improves the search process significantly. \section{Introduction}\label{sec:intro} The success of deep neural networks (DNNs) across different domains has created the desire to apply them in safety-critical applications such as autonomous vehicles~\citep{kendall2019learning,lechner2020neural} and healthcare systems~\citep{shen2017deep}. The fundamental challenge for the deployment of DNNs in these domains is certifying their safety~\citep{amodei2016concrete}. Thus, formal safety verification of DNNs in isolation and closed control loops~\citep{KatzBDJK17,HenzingerLZ21,GehrMDTCV18,TjengXT19,DuttaCS19} has become an active research topic. Bayesian neural networks (BNNs) are a family of neural networks that place distributions over their weights~\citep{neal2012bayesian}. This allows learning uncertainty in the data and the network's prediction, while preserving the strong modelling capabilities of DNNs~\citep{MacKay92a}. In particular, BNNs can learn arbitrary data distributions from much simpler (e.g.~Gaussian) weight distributions. This makes BNNs very appealing for robotic and medical applications~\citep{mcallister2017concrete} where uncertainty is a central component of data. Despite the large body of literature on verifying safety of DNNs, the formal safety verification of BNNs has received less attention. Notably, \citep{CardelliKLPPW19,WickerLPK20,MichelmoreWLCGK20} have proposed sampling-based techniques for obtaining probabilistic guarantees about BNNs. Although these approaches provide some insight into BNN safety, they suffer from two key limitations. First, sampling provides only bounds on the probability of the BNN's safety which is insufficient for systems with critical safety implications. For instance, having an autonomous vehicle with a $99.9\%$ safety guarantee is still insufficient for deployment if millions of vehicles are deployed. Second, samples can only simulate the system for a finite time, making it impossible to reason about the system's safety over an unbounded time horizon. \begin{wrapfigure}{R}{7cm} \centering \includegraphics[width=7cm]{standalone.pdf} \caption{BNNs are typically unsafe by default. Top figure: The posterior of a typical BNN has unbounded support, resulting in a non-zero probability of producing an unsafe action. Bottom figure: Restricting the support of the weight distributions via rejection sampling ensures BNN safety.} \label{fig:intro} \end{wrapfigure} In this work, we study the safety verification problem for BNN policies in safety-critical systems over the infinite time horizon. Formally, we consider discrete-time closed-loop systems defined by a dynamical system and a BNN policy. Given a set of initial states and a set of unsafe (or bad) states, the goal of the safety verification problem is to verify that no system execution starting in an initial state can reach an unsafe state. Unlike existing literature which considers probability of safety, we verify {\em sure safety}, i.e.~safety of every system execution of the system. In particular, we present a method for computing {\em safe weight sets} for which every system execution is safe as long as the BNN samples its weights from this set. Our approach to restrict the support of the weight distribution is necessary as BNNs with Gaussian weight priors typically produce output posteriors with unbounded support. Consequently, there is a low but non-zero probability for the output variable to lie in an unsafe region, see Figure \ref{fig:intro}. This implies that BNNs are usually unsafe by default. We therefore consider the more general problem of computing safe weight sets. Verifying that a weight set is safe allows re-calibrating the BNN policy by rejecting unsafe weight samples in order to guarantee safety. As most BNNs employ uni-modal weight priors, e.g. Gaussians, we naturally adopt weight sets in the form of products of intervals centered at the means of the BNN's weight distributions. To verify safety of a weight set, we search for a safety certificate in the form of a {\em safe positive invariant} (also known as {\em safe inductive invariant}). A safe positive invariant is a set of system states that contains all initial states, is closed under the system dynamics and does not contain any unsafe state. The key advantage of using safe positive invariants is that their existence implies the {\em infinite time horizon safety}. We parametrize safe positive invariant candidates by (deterministic) neural networks that classify system states for determining set inclusion. Moreover, we phrase the search for an invariant as a learning problem. A separated verifier module then checks if a candidate is indeed a safe positive invariant by checking the required properties via constraint solving. In case the verifier finds a counterexample demonstrating that the candidate violates the safe positive invariant condition, we re-train the candidate on the found counterexample. We repeat this procedure until the verifier concludes that the candidate is a safe positive invariant ensuring that the system is safe. The safe weight set obtained by our method can be used for safe exploration reinforcement learning. In particular, generating rollouts during learning by sampling from the safe weight set allows an exploration of the environment while ensuring safety. Moreover, projecting the (mean) weights onto the safe weight set after each gradient update further ensures that the improved policy stays safe. \textbf{Contributions} Our contributions can be summarized as follows: \begin{compactenum} \item We define a safety verification problem for BNN policies which overcomes the unbounded posterior issue by computing and verifying safe weight sets. The problem generalizes the sure safety verification of BNNs and solving it allows re-calibrating BNN policies via rejection sampling to guarantee safety. \item We introduce a method for computing safe weight sets in BNN policies in the form of products of intervals around the BNN weights' means. To verify safety of a weight set, our novel algorithm learns a safe positive invariant in the form of a deterministic neural network. \item We evaluate our methodology on a series of benchmark applications, including non-linear systems and non-Lyapunovian safety specifications. \end{compactenum} \section{Related work}\label{sec:relatedwork} \textbf{Verification of feed-forward NN} Verification of robustness and safety properties in feed-forward DNNs has received much attention but remains an active research topic~\citep{KatzBDJK17,HenzingerLZ21,GehrMDTCV18,RuanHK18,BunelTTKM18,TjengXT19}. As the majority of verification techniques were designed for deterministic NNs, they cannot be readily applied to BNNs. The safety verification of feed-forward BNNs has been considered in \citep{CardelliKLPPW19} by using samples to obtain statistical guarantees on the safety probability. The work of~\citep{WickerLPK20} also presents a sampling-based approach, however it provides certified lower bounds on the safety probability. The literature discussed above considers NNs in isolation, which can provide input-output guarantees on a NN but are unable to reason holistically about the safety of the system that the NN is applied in. Verification methods that concern the safety of NNs interlinked with a system require different approaches than standalone NN verification, which we will discuss in the rest of this section. \textbf{Finite time horizon safety of BNN policies} The work in~\citep{MichelmoreWLCGK20} extends the method of~\citep{CardelliKLPPW19} to verifying safety in closed-loop systems with BNN policies. However, similar to the standalone setting of \cite{CardelliKLPPW19}, their method obtains only statistical guarantees on the safety probability and for the system's execution over a finite time horizon. \textbf{Safe RL} Safe reinforcement learning has been primarily studied in the form of constrained Markov decision processes (CMDPs) \citep{altman1999constrained,Geibel06}. Compared to standard MDPs, an agent acting in a CMDP must satisfy an expected auxiliary cost term aggregated over an episode. The CMDP framework has been the base of several RL algorithms~\citep{uchibe2007constrained}, notably the Constrained Policy Optimization (CPO)~\citep{achiam2017constrained}. Despite these algorithms providing a decent performance, the key limitation of CMDPs is that the constraint is satisfied in expectation, which makes violations unlikely but nonetheless possible. Consequently, the CMDP framework is unsuited for systems where constraint violations are critical. \textbf{Lyapunov-based stability} Safety in the context of ''stability'', i.e.~always returning to a ground state, can be proved by Lyapunov functions~\citep{BerkenkampTS017}. Lyapunov functions have originally been considered to study stability of dynamical systems~\citep{khalil2002nonlinear}. Intuitively, a Lyapunov function assigns a non-negative value to each state, and is required to decrease with respect to the system's dynamics at any state outside of the stable set. A Lyapunov-based method is proposed in~\citep{ChowNDG18} to ensure safety in CMDPs during training. Recently, the work of~\citep{ChangRG19} presented a method for learning a policy as well as a neural network Lyapunov function which guarantees the stability of the policy. Similarly to our work, their learning procedure is counterexample-based. However, unlike \citep{ChangRG19}, our work considers BNN policies and safety definitions that do not require returning to a set of ground states. \textbf{Barrier functions for dynamical systems} Barrier functions can be used to prove infinite time horizon safety in dynamical systems~\citep{PrajnaJ04,PrajnaJP07}. Recent works have considered learning neural network barrier functions~\citep{ZhaoZC020}, and a counterexample-based learning procedure is presented in~\cite{PeruffoAA21}. \textbf{Finite time horizon safety of NN policies} Safety verification of continuous-time closed-loop systems with deterministic NN policies has been considered in~\citep{IvanovWAPL19,gruenbacher2020lagrangian}, which reduces safety verification to the reachability analysis in hybrid systems~\citep{ChenAS13}. The work of~\citep{DuttaCS19} presents a method which computes a polynomial approximation of the NN policy to allow an efficient approximation of the reachable state set. Both works consider finite time horizon systems. Our safety certificate most closely resembles inductive invariants for safety analysis in programs~\citep{Floyd1967} and positive invariants for dynamical systems~\citep{blanchini2008set}. \section*{Acknowledgments} This research was supported in part by the Austrian Science Fund (FWF) under grant Z211-N23 (Wittgenstein Award), ERC CoG 863818 (FoRM-SMArt), and the European Union’s Horizon 2020 research and innovation programme under the Marie Skłodowska-Curie Grant Agreement No. 665385. \bibliographystyle{plainnat} \section{Main results} In this section we present our method for solving the safety problems defined in the previous section, with Section~\ref{sec:feedforward} considering Problem~\ref{problem1} and Section~\ref{sec:loopcertificate} considering Problem~\ref{problem2}. Both problems consider safety verification with respect to a given value of $\epsilon\in[0,\infty]$, so in Section~\ref{sec:epscompute} we present our method for computing the value of $\epsilon$ for which our solutions to Problem~1 and Problem~2 may be used to verify safety. We then show in Section~\ref{sec:safeexploration} how our new methodology can be adapted to the safe exploration RL setting. \subsection{Safe weight sets for feed-forward BNNs}\label{sec:feedforward} Consider a feed-forward BNN $\pi$, a set $\mathcal{X}_0\subseteq\mathbb{R}^m$ of inputs and a set $\mathcal{X}_u\subseteq\mathbb{R}^n$ of unsafe output of the BNN. Fix $\epsilon\in[0,\infty]$. To solve Problem~\ref{problem1}, we show that the decision problem of whether each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe can be encoded as a system of constraints and reduced to constraint solving. Suppose that $\pi=l_1\circ\dots\circ l_k$ consists of $k$ layers, with each $l_i(\mathbf{x}) = \textrm{ReLU}(\mathbf{W}_i\mathbf{x}+\mathbf{b}_i)$. Denote by $\mathbf{M}_i$ the matrix of the same dimension as $\mathbf{W}_i$, with each entry equal to the mean of the corresponding random variable weight in $\mathbf{W}_i$. Similarly, define the vector $\mathbf{m}_i$ of means of random variables in $\mathbf{b}_i$. The real variables of our system of constraints are as follows, each of appropriate dimension: \begin{compactitem} \item $\mathbf{x}_0$ encodes the BNN inputs, $\mathbf{x}_l$ encodes the BNN outputs; \item $\mathbf{x}_1^{\textrm{in}}$, \dots, $\mathbf{x}_{l-1}^{\textrm{in}}$ encode vectors of input values of each neuron in the hidden layers; \item $\mathbf{x}_1^{\textrm{out}}$, \dots, $\mathbf{x}_{l-1}^{\textrm{out}}$ encode vectors of output values of each neuron in the hidden layers; \item $\mathbf{x}_{0,\textrm{pos}}$ and $\mathbf{x}_{0,\textrm{neg}}$ are dummy variable vectors of the same dimension as $\mathbf{x}_0$ and which will be used to distinguish between positive and negative NN inputs in $\mathbf{x}_0$, respectively. \end{compactitem} We use $\mathbf{1}$ to denote the vector/matrix whose all entries are equal to $1$, of appropriate dimensions defined by the formula in which it appears. Our system of constraints is as follows: \begin{equation}\label{eq:inputoutput}\tag{Input-output conditions} \mathbf{x}_0 \in \mathcal{X}_0, \hspace{0.5cm} \mathbf{x}_l \in \mathcal{X}_u \end{equation} \begin{equation}\label{eq:relu}\tag{ReLU encoding} \mathbf{x}_i^{\textrm{out}} = \textrm{ReLU}(\mathbf{x}_i^{\textrm{in}}), \text{ for each } 1\leq i\leq l-1 \end{equation} \begin{equation}\label{eq:weights}\tag{BNN hidden layers} \begin{split} &(\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_{i+1}^{\textrm{in}}, \text{ for each } 1\leq i\leq l-1 \\ &\mathbf{x}_{i+1}^{\textrm{in}} \leq (\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i+\epsilon\cdot\mathbf{1}), \text{ for each } 1\leq i\leq l-1 \end{split} \end{equation} \begin{equation}\label{eq:weights}\tag{BNN input layer} \begin{split} &\mathbf{x}_{0,\textrm{pos}} = \textrm{ReLU}(\mathbf{x}_0), \hspace{0.5cm} \mathbf{x}_{0,\textrm{neg}} = -\textrm{ReLU}(-\mathbf{x}_0) \\ &(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_1^{\textrm{in}} \\ &\mathbf{x}_1^{\textrm{in}} \leq (\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_0^{\textrm{out}}+(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0+\epsilon\cdot\mathbf{1}) \end{split} \end{equation} Denote by $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ the system of constraints defined above. The proof of Theorem~\ref{thm:constraints} shows that it encodes that $\mathbf{x}_0\in\mathcal{X}_0$ is an input point for which the corresponding output point of $\pi$ is unsafe, i.e.~$\mathbf{x}_l=\pi(\mathbf{x}_0)\in\mathcal{X}_u$. The first equation encodes the input and output conditions. The second equation encodes the ReLU input-output relation for each hidden layer neuron. The remaining equations encode the relation between neuron values in successive layers of the BNN as well as that the sampled BNN weight vector is in $W^{\pi}_{\epsilon}$. For hidden layers, we know that the output value of each neuron is nonnegative, i.e.$~\mathbf{x}_i^{\textrm{out}}\geq\mathbf{0}$ for the $i$-th hidden layer where $1\leq i\leq l-1$, and so \[ (\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}} \leq (\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}. \] Hence, the BNN weight relation with neurons in the successive layer as well as the fact that the sampled weights are in $W^{\pi}_{\epsilon }$ is encoded as in equations 3-4 above. For the input layer, however, we do not know the signs of the input neuron values $\mathbf{x}_0$ and so we introduce dummy variables $\mathbf{x}_{0,\textrm{pos}}=\textrm{ReLU}(\mathbf{x}_0)$ and $\mathbf{x}_{0,\textrm{neg}}=-\textrm{ReLU}(-\mathbf{x}_0)$ in equation 5. This allows encoding the BNN weight relations between the input layer and the first hidden layer as well as the fact that the sampled weight vector is in $W^{\pi}_{\epsilon}$, as in equations 6-7. Theorem~\ref{thm:constraints} shows that Problem~\ref{problem1} is equivalent to solving the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Its proof can be found in the Supplementary Material. \begin{theorem}\label{thm:constraints} Let $\epsilon\in[0,\infty]$. Then each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe if and only if the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is not satisfiable. \end{theorem} \textbf{Solving the constraints} Observe that $\epsilon$, $\mathbf{M}_i$ and $\mathbf{m}_i$, $1\leq i\leq l-1$, are constant values that are known at the time of constraint encoding. Thus, in $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$, only the ReLU constraints and possibly the input-output conditions are not linear. Depending on the form of $\mathcal{X}_0$ and $\mathcal{X}_u$ and on how we encode the ReLU constraints, we may solve the system $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ in several ways: \begin{compactenum} \item \textbf{MILP.} It is shown in~\citep{lomuscio2017approach,dutta2018output,TjengXT19} that the ReLU relation between two real variables can be encoded via mixed-integer linear constraints (MILP) by introducing 0/1-integer variables to encode whether a given neuron is active or inactive. Hence, if $\mathcal{X}_0$ and $\mathcal{X}_u$ are given by linear constraints, we may solve $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ by a MILP solver. The ReLU encoding requires that each neuron value is bounded, which is ensured if $\mathcal{X}_0$ is a bounded set and if $\epsilon<\infty$. \item \textbf{Reluplex.} In order to allow unbounded $\mathcal{X}_0$ and $\epsilon=\infty$, we may use algorithms based on the Reluplex calculus~\citep{KatzBDJK17,KatzHIJLLSTWZDK19} to solve $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Reluplex is an extension of the standard simplex algorithm for solving systems of linear constraints, designed to allow ReLU constraints as well. While Reluplex does not impose the boundedness condition, it is in general less scalable than MILP-solving. \item \textbf{NRA-SMT.} Alternatively, if $\mathcal{X}_0$ or $\mathcal{X}_u$ are given by non-linear constraints we may solve them by using an NRA-SMT-solver (non-linear real arithmetic satisfiability modulo theory), e.g.~dReal~\citep{gao2012delta}. To use an NRA-SMT-solver, we can replace the integer 0/1-variables of the ReLU neuron relations encoding with real variables that satisfy the constraint $x(x-1)=0$. While NRA-SMT is less scalable compared to MILP, we note that it has been used in previous works on RL stability verification \cite{ChangRG19}. \end{compactenum} \textbf{Safety via rejection sampling} As discussed in Section~\ref{sec:intro}, once the safety of NNs in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ has been verified, we can ``re-calibrate'' the BNN to reject sampled weights which are not in $W^{\pi}_{\epsilon}$. Hence, rejection sampling gives rise to a safe BNN. \subsection{Safe weight sets for closed-loop systems with BNN Policies}\label{sec:loopcertificate} Now consider a closed-loop system with a dynamics function $f:\mathcal{X}\times\mathcal{U}\rightarrow\mathcal{X}$ with $\mathcal{X}\subseteq\mathbb{R}^m$ and $\mathcal{U}\subseteq\mathbb{R}^n$, a BNN policy $\pi$, an initial state set $\mathcal{X}_0\subseteq\mathcal{X}$ and an unsafe state set $\mathcal{X}_u\subseteq\mathcal{X}$. Fix $\epsilon\in[0,\infty]$. In order to solve Problem~\ref{problem2} and verify safety of each trajectory contained in $\mathsf{Traj}^{f,\pi}_{\epsilon}$, our method searches for a positive invariant-like safety certificate that we define below. \textbf{Positive invariants for safety} A positive invariant in a dynamical system is a set of states which contains all initial states and which is closed under the system dynamics. These conditions ensure that states of all system trajectories are contained in the positive invariant. Hence, a positive invariant which does not contain any unsafe states can be used to certify safety of every trajectory over infinite time horizon. In this work, however, we are not trying to prove safety of every trajectory, but only of those trajectories contained in $\mathsf{Traj}^{f,\pi}_{\epsilon}$. To that end, we define $W^{\pi}_{\epsilon}$-safe positive invariants. Intuitively, a $W^{\pi}_{\epsilon}$-safe positive invariant is required to contain all initial states, to be closed under the dynamics $f$ and the BNN policy $\pi$ when the sampled weight vector is in $W^{\pi}_{\epsilon}$, and not to contain any unsafe state. \begin{definition}[$W^{\pi}_{\epsilon}$-safe positive invariants]\label{def:inv} A set $\mathsf{Inv}\subseteq\mathcal{X}$ is said to be a {\em $W^{\pi}_{\epsilon}$-positive invariant} if $\mathcal{X}_0\subseteq\mathsf{Inv}$, for each $\mathbf{x}\in\mathsf{Inv}$ and $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ we have that $f(\mathbf{x},\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}))\in\mathsf{Inv}$, and $\mathsf{Inv}\cap\mathcal{X}_u=\emptyset$. \end{definition} Theorem~\ref{thm:posinv} shows that $W^{\pi}_{\epsilon}$-safe positive invariants can be used to verify safety of all trajectories in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ in Problem~\ref{problem2}. The proof is straightforward and is deferred to the Supplementary Material. \begin{theorem}\label{thm:posinv} If there exists a $W^{\pi}_{\epsilon}$-safe positive invariant, then each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{theorem} \begin{algorithm}[t] \caption{Learning algorithm for $W^{\pi}_{\epsilon}$-safe positive invariants} \label{algorithm:ce} \begin{algorithmic} \STATE \textbf{Input} Dynamics function $f$, BNN policy $\pi$, Initial state set $\mathcal{X}_0$, Unsafe state set $\mathcal{X}_u$, $\epsilon \in [0,\infty]$ \STATE $\tilde{\mathcal{X}_0}, \tilde{\mathcal{X}_u} \leftarrow $ random samples of $\mathcal{X}_0,\mathcal{X}_u$ \STATE $D_{\textrm{spec}} \leftarrow \tilde{\mathcal{X}_u} \times \{0\} \cup \tilde{\mathcal{X}_0} \times \{1\}$, $D_{\textrm{ce}} \leftarrow \{\}$ \STATE Optional (bootstrapping): $S_{\textrm{bootstrap}} \leftarrow $ sample finite trajectories with initial state sampled from $\mathcal{X}$ \STATE \qquad\qquad\qquad $D_{\textrm{spec}} \leftarrow D_{\textrm{spec}} \cup \{(\mathbf{x},0)| \,\exists s\in S_{\textrm{bootstrap}} \text{ that starts in } \mathbf{x}\in \mathcal{X} \text{ and reaches } \mathcal{X}_u \}$ \STATE \qquad\qquad\qquad\qquad\qquad $\cup\, \{(\mathbf{x},1)| \,\exists s\in S_{\textrm{bootstrap}} \text{ that starts in } \mathbf{x}\in \mathcal{X} \text{ and does not reach } \mathcal{X}_u \}$ \STATE Pre-train neural network $g^{\mathsf{Inv}}$ on datasets $D_{\textrm{spec}}$ and $D_{\textrm{ce}}$ with loss function $\mathcal{L}$ \WHILE{timeout not reached} \IF{$\exists (\mathbf{x},\mathbf{x}',\mathbf{u},\mathbf{w},\mathbf{b})$ s.t. $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$, $g^{\mathsf{Inv}}(\mathbf{x}')<0$, $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$, $\mathbf{u}=\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x})$, $\mathbf{x}'=f(\mathbf{x},\mathbf{u})$} \STATE $D_{\textrm{ce}} \leftarrow D_{\textrm{ce}} \cup \{(\mathbf{x},\mathbf{x}')\}$ \ELSIF{$\exists (\mathbf{x})$ s.t. $\mathbf{x}\in\mathcal{X}_0$, $g^{\mathsf{Inv}}(\mathbf{x})< 0$} \STATE $D_{\textrm{spec}} \leftarrow D_{\textrm{spec}} \cup \{(\mathbf{x},1)\}$ \ELSIF{$\exists (\mathbf{x})$ s.t. $\mathbf{x}\in\mathcal{X}_u$, $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$} \STATE $D_{\textrm{spec}} \leftarrow D_{\textrm{spec}} \cup \{(\mathbf{x},0)\}$ \ELSE \STATE \textbf{Return} Safe \ENDIF \STATE {Train neural network $g^{\mathsf{Inv}}$ on datasets $D_{\textrm{spec}}$ and $D_{\textrm{ce}}$ with loss function $\mathcal{L}$} \ENDWHILE \STATE \textbf{Return} Unsafe \end{algorithmic} \end{algorithm} \textbf{Learning positive invariants} We now present a learning algorithm for a $W^{\pi}_{\epsilon}$-safe positive invariant. It learns a neural network $g^{\mathsf{Inv}}:\mathbb{R}^m\rightarrow\mathbb{R}$, where the positive invariant is then defined as the set $\mathsf{Inv} = \{\mathbf{x}\in\mathcal{X}\mid g^{\mathsf{Inv}}(\mathbf{x})\geq 0\}$. The pseudocode is given in Algorithm~\ref{algorithm:ce}. The algorithm first samples $\tilde{\mathcal{X}_0}$ from $\mathcal{X}_0$ and $\tilde{\mathcal{X}_u}$ from $\mathcal{X}_u$ and initializes the specification set $D_{\textrm{spec}}$ to $\tilde{\mathcal{X}_u} \times \{0\} \cup \tilde{\mathcal{X}_0} \times \{1\}$ and the counterexample set $D_{\textrm{ce}}$ to an empty set. Optionally, the algorithm also bootstraps the positive invariant network by initializing $D_{\textrm{spec}}$ with random samples from the state space $\mathcal{X}$ labeled with Monte-Carlo estimates of reaching the unsafe states. The rest of the algorithm consists of two modules which are composed into a loop: the {\em learner} and the {\em verifier}. In each loop iteration, the learner first learns a $W^{\pi}_{\epsilon}$-safe positive invariant candidate which takes the form of a neural network $g^{\mathsf{Inv}}$. This is done by minimizing the loss function $\mathcal{L}$ that depends on $D_{\textrm{spec}}$ and $D_{\textrm{ce}}$: \begin{equation}\label{eq:totalloss} \mathcal{L}(g^{\mathsf{Inv}}) = \frac{1}{|D_{\textrm{spec}}|}\sum_{(\mathbf{x},y)\in D_{\textrm{spec}}}^{}\mathcal{L}_{\textrm{cls}}\big(g^\mathsf{Inv}(\mathbf{x}),y\big) +\lambda \frac{1}{|D_{\textrm{ce}}|}\sum_{(\mathbf{x},\mathbf{x}')\in D_{\textrm{ce}}}^{}\mathcal{L}_{\textrm{ce}}\big(g^\mathsf{Inv}(\mathbf{x}),g^\mathsf{Inv}(\mathbf{x}')\big), \end{equation} where $\lambda$ is a tuning parameter and $\mathcal{L}_{\textrm{cls}}$ a binary classification loss function, e.g.~the 0/1-loss $\mathcal{L}_{\textrm{0/1}}(z,y) = \mathds{1}[\mathds{1}[z\geq0]\neq y]$ or the logistic loss $\mathcal{L}_{\textrm{log}}(z,y)= z - z \cdot y + \log(1 + \exp(-z))$ as its differentiable alternative. The term $\mathcal{L}_{\textrm{ce}}$ is the counterexample loss which we define via \begin{equation}\label{eq:loss} \mathcal{L}_{\textrm{ce}}(z,z') = \mathds{1}\big[z>0\big]\mathds{1}\big[z'<0\big] \mathcal{L}_{\textrm{cls}}\big(z,0\big) \mathcal{L}_{\textrm{cls}}\big(z',1\big). \end{equation} Intuitively, the first sum in eq.~\eqref{eq:totalloss} forces $g^{\mathsf{Inv}}$ to be nonnegative at initial states and negative at unsafe states contained in $D_{\textrm{spec}}$, and the second term forces each counterexample in $D_{\textrm{ce}}$ not to destroy the closedness of $\mathsf{Inv}$ under the system dynamics. Once $g^{\mathsf{Inv}}$ is learned, the verifier checks whether $\mathsf{Inv}$ is indeed a $W^{\pi}_{\epsilon}$-safe positive invariant. To do this, the verifier needs to check the three defining properties of $W^{\pi}_{\epsilon}$-safe positive invariants: \begin{compactenum} \item {\em Closedness of $\mathsf{Inv}$ under system dynamics.} The verifier checks if there exist states $\mathbf{x}\in\mathsf{Inv}$, $\mathbf{x'}\not\in\mathsf{Inv}$ and a BNN weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ such that $f(\mathbf{x},\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}))=\mathbf{x}'$. To do this, it introduces real variables $\mathbf{x},\mathbf{x}'\in\mathbb{R}^m$, $\mathbf{u}\in\mathbb{R}^n$ and $y,y'\in\mathbb{R}$, and solves: \begin{equation*} \begin{split} &\textrm{maximize } y - y' \textrm{ subject to} \\ &y\geq 0, y'<0, y=g^{\mathsf{Inv}}(\mathbf{x}), y'=g^{\mathsf{Inv}}(\mathbf{x'}) \\ &\mathbf{x'} = f(\mathbf{x},\mathbf{u}) \\ &\mathbf{u} \text{ is an output of } \pi \text{ on input } \mathbf{x} \textrm{ and weights } (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon} \end{split} \end{equation*} The conditions $y=g^{\mathsf{Inv}}(\mathbf{x})$ and $y'=g^{\mathsf{Inv}}(\mathbf{x'})$ are encoded by using the existing techniques for encoding deterministic NNs as systems of MILP/Reluplex/NRA-SMT constraints. The condition in the third equation is encoded simply by plugging variable vectors $\mathbf{x}$ and $\mathbf{u}$ into the equation for $f$. Finally, for condition in the fourth equation we use our encoding from Section~\ref{sec:feedforward} where we only need to omit the Input-output condition. The optimization objective is added in order to search for the ``worst'' counterexample. We note that MILP~\citep{gurobi} and SMT~\citep{gao2012delta} solvers allow optimizing linear objectives, and recently Reluplex algorithm~\citep{KatzBDJK17} has also been extended to allow solving optimization problems~\citep{strong2020global}. If a counterexample $(\mathbf{x},\mathbf{x}')$ is found, it is added to $D_{\textrm{ce}}$ and the learner tries to learn a new candidate. If the system of constraints is unsatisfiable, the verifier proceeds to the second check. \item {\em Non-negativity on $\mathcal{X}_0$.} The verifier checks if there exists $\mathbf{x}\in\mathcal{X}_0$ for which $g^{\mathsf{Inv}}(\mathbf{x})< 0$. If such $\mathbf{x}$ is found, $(\mathbf{x},1)$ is added to $D_{\textrm{spec}}$ and the learner then tries to learn a new candidate. If the system of constraints is unsatisfiable, the verifier proceeds to the third check. \item {\em Negativity on $\mathcal{X}_u$.} The verifier checks if there exists $\mathbf{x}\in\mathcal{X}_u$ with $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$. If such $\mathbf{x}$ is found, $(\mathbf{x},0)$ is added to $D_{\textrm{spec}}$ and the learner then tries to learn a new candidate. If the system of constraints is unsatisfiable, the veririfer concludes that $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-positive invariant which does not contain any unsafe state and so each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{compactenum} Theorem~\ref{thm:loss} shows that neural networks $f^{\mathsf{Inv}}$ for which $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariants are global minimizers of the loss function $\mathcal{L}$ with the 0/1-classification loss. Theorem~\ref{thm:correctness} establishes the correctness of our algorithm. Proofs can be found in the Supplementary Material. \begin{theorem}\label{thm:loss} The loss function $\mathcal{L}$ is nonnegative for any neural network $g$, i.e.~$\mathcal{L}(g)\geq 0$. Moreover, if $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant and $\mathcal{L}_{\textrm{cls}}$ the 0/1-loss, then $\mathcal{L}(g^{\mathsf{Inv}})=0$. Hence, neural networks $g^{\mathsf{Inv}}$ for which $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant are global minimizers of the loss function $\mathcal{L}$ when $\mathcal{L}_{\textrm{cls}}$ is the 0/1-loss. \end{theorem} \begin{theorem}\label{thm:correctness} If the verifier in Algorithm~\ref{algorithm:ce} shows that constraints in three checks are unsatisfiable, then the computed $\mathsf{Inv}$ is indeed a $W^{\pi}_{\epsilon}$-safe positive invariant. Hence, Algorithm~\ref{algorithm:ce} is correct. \end{theorem} \textbf{Safety via rejection sampling} As discussed in Section~\ref{sec:intro}, once the safety of all trajectories in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ has been verified, we can ``re-calibrate'' the BNN policy to reject sampled weights which are not in $W^{\pi}_{\epsilon}$. Hence, rejection sampling gives rise to a safe BNN policy. \subsection{Computation of safe weight sets and the value of $\epsilon$}\label{sec:epscompute} Problems~\ref{problem1} and~\ref{problem2} assume a given value of $\epsilon$ for which safety needs to be verified. In order to compute the largest value of $\epsilon$ for which our approach can verify safety, we start with a small value of $\epsilon$ and iteratively increase it until we reach a value that cannot be certified or until the timeout is reached, in order to compute as large safe weight set as possible. In each iteration, our Algorithm \ref{algorithm:ce} does not start from scratch but is initialized with the $g^{\mathsf{Inv}}$ and $D_{\textrm{spec}}$ from the previous successful iteration, i.e.~attempting to enlarge the current safe weight set. Our iterative process significantly speeds up the search process compared to naively restarting our algorithm in every iteration. \subsection{Safe exploration reinforcement learning}\label{sec:safeexploration} Given a safe but non-optimal initial policy $\pi_{0}$, safe exploration reinforcement learning (SERL) concerns the problem of improving the expected return of $\pi_{0}$ while ensuring safety when collecting samples of the environment \citep{uchibe2007constrained,achiam2017constrained,nakka2020chance}. Our method from Section~\ref{sec:loopcertificate} for computing safe weight sets can be adapted to this setting with minimal effort. In particular, the safety bound $\epsilon$ for the intervals centered at the weight means can be used in combination with the rejection sampling to generate safe but randomized rollouts on the environment. Moreover, $\epsilon$ provides bounds on the gradient updates when optimizing the policy using Deep Q-learning or policy gradient methods, i.e., performing \emph{projected gradient descent}. We sketch an algorithm for SERL in the Supplementary Material. \section{Submission of papers to NeurIPS 2021} Please read the instructions below carefully and follow them faithfully. \subsection{Style} Papers to be submitted to NeurIPS 2021 must be prepared according to the instructions presented here. Papers may only be up to {\bf nine} pages long, including figures. Additional pages \emph{containing only acknowledgments and references} are allowed. Papers that exceed the page limit will not be reviewed, or in any other way considered for presentation at the conference. The margins in 2021 are the same as those in 2007, which allow for $\sim$$15\%$ more words in the paper compared to earlier years. Authors are required to use the NeurIPS \LaTeX{} style files obtainable at the NeurIPS website as indicated below. Please make sure you use the current files and not previous versions. Tweaking the style files may be grounds for rejection. \subsection{Retrieval of style files} The style files for NeurIPS and other conference information are available on the World Wide Web at \begin{center} \url{http://www.neurips.cc/} \end{center} The file \verb+neurips_2021.pdf+ contains these instructions and illustrates the various formatting requirements your NeurIPS paper must satisfy. The only supported style file for NeurIPS 2021 is \verb+neurips_2021.sty+, rewritten for \LaTeXe{}. \textbf{Previous style files for \LaTeX{} 2.09, Microsoft Word, and RTF are no longer supported!} The \LaTeX{} style file contains three optional arguments: \verb+final+, which creates a camera-ready copy, \verb+preprint+, which creates a preprint for submission to, e.g., arXiv, and \verb+nonatbib+, which will not load the \verb+natbib+ package for you in case of package clash. \paragraph{Preprint option} If you wish to post a preprint of your work online, e.g., on arXiv, using the NeurIPS style, please use the \verb+preprint+ option. This will create a nonanonymized version of your work with the text ``Preprint. Work in progress.'' in the footer. This version may be distributed as you see fit. Please \textbf{do not} use the \verb+final+ option, which should \textbf{only} be used for papers accepted to NeurIPS. At submission time, please omit the \verb+final+ and \verb+preprint+ options. This will anonymize your submission and add line numbers to aid review. Please do \emph{not} refer to these line numbers in your paper as they will be removed during generation of camera-ready copies. The file \verb+neurips_2021.tex+ may be used as a ``shell'' for writing your paper. All you have to do is replace the author, title, abstract, and text of the paper with your own. The formatting instructions contained in these style files are summarized in Sections \ref{gen_inst}, \ref{headings}, and \ref{others} below. \section{General formatting instructions} \label{gen_inst} The text must be confined within a rectangle 5.5~inches (33~picas) wide and 9~inches (54~picas) long. The left margin is 1.5~inch (9~picas). Use 10~point type with a vertical spacing (leading) of 11~points. Times New Roman is the preferred typeface throughout, and will be selected for you by default. Paragraphs are separated by \nicefrac{1}{2}~line space (5.5 points), with no indentation. The paper title should be 17~point, initial caps/lower case, bold, centered between two horizontal rules. The top rule should be 4~points thick and the bottom rule should be 1~point thick. Allow \nicefrac{1}{4}~inch space above and below the title to rules. All pages should start at 1~inch (6~picas) from the top of the page. For the final version, authors' names are set in boldface, and each name is centered above the corresponding address. The lead author's name is to be listed first (left-most), and the co-authors' names (if different address) are set to follow. If there is only one co-author, list both author and co-author side by side. Please pay special attention to the instructions in Section \ref{others} regarding figures, tables, acknowledgments, and references. \section{Headings: first level} \label{headings} All headings should be lower case (except for first word and proper nouns), flush left, and bold. First-level headings should be in 12-point type. \subsection{Headings: second level} Second-level headings should be in 10-point type. \subsubsection{Headings: third level} Third-level headings should be in 10-point type. \paragraph{Paragraphs} There is also a \verb+\paragraph+ command available, which sets the heading in bold, flush left, and inline with the text, with the heading followed by 1\,em of space. \section{Citations, figures, tables, references} \label{others} These instructions apply to everyone. \subsection{Citations within the text} The \verb+natbib+ package will be loaded for you by default. Citations may be author/year or numeric, as long as you maintain internal consistency. As to the format of the references themselves, any style is acceptable as long as it is used consistently. The documentation for \verb+natbib+ may be found at \begin{center} \url{http://mirrors.ctan.org/macros/latex/contrib/natbib/natnotes.pdf} \end{center} Of note is the command \verb+\citet+, which produces citations appropriate for use in inline text. For example, \begin{verbatim} \citet{hasselmo} investigated\dots \end{verbatim} produces \begin{quote} Hasselmo, et al.\ (1995) investigated\dots \end{quote} If you wish to load the \verb+natbib+ package with options, you may add the following before loading the \verb+neurips_2021+ package: \begin{verbatim} \PassOptionsToPackage{options}{natbib} \end{verbatim} If \verb+natbib+ clashes with another package you load, you can add the optional argument \verb+nonatbib+ when loading the style file: \begin{verbatim} \usepackage[nonatbib]{neurips_2021} \end{verbatim} As submission is double blind, refer to your own published work in the third person. That is, use ``In the previous work of Jones et al.\ [4],'' not ``In our previous work [4].'' If you cite your other papers that are not widely available (e.g., a journal paper under review), use anonymous author names in the citation, e.g., an author of the form ``A.\ Anonymous.'' \subsection{Footnotes} Footnotes should be used sparingly. If you do require a footnote, indicate footnotes with a number\footnote{Sample of the first footnote.} in the text. Place the footnotes at the bottom of the page on which they appear. Precede the footnote with a horizontal rule of 2~inches (12~picas). Note that footnotes are properly typeset \emph{after} punctuation marks.\footnote{As in this example.} \subsection{Figures} \begin{figure} \centering \fbox{\rule[-.5cm]{0cm}{4cm} \rule[-.5cm]{4cm}{0cm}} \caption{Sample figure caption.} \end{figure} All artwork must be neat, clean, and legible. Lines should be dark enough for purposes of reproduction. The figure number and caption always appear after the figure. Place one line space before the figure caption and one line space after the figure. The figure caption should be lower case (except for first word and proper nouns); figures are numbered consecutively. You may use color figures. However, it is best for the figure captions and the paper body to be legible if the paper is printed in either black/white or in color. \subsection{Tables} All tables must be centered, neat, clean and legible. The table number and title always appear before the table. See Table~\ref{sample-table}. Place one line space before the table title, one line space after the table title, and one line space after the table. The table title must be lower case (except for first word and proper nouns); tables are numbered consecutively. Note that publication-quality tables \emph{do not contain vertical rules.} We strongly suggest the use of the \verb+booktabs+ package, which allows for typesetting high-quality, professional tables: \begin{center} \url{https://www.ctan.org/pkg/booktabs} \end{center} This package was used to typeset Table~\ref{sample-table}. \begin{table} \caption{Sample table title} \label{sample-table} \centering \begin{tabular}{lll} \toprule \multicolumn{2}{c}{Part} \\ \cmidrule(r){1-2} Name & Description & Size ($\mu$m) \\ \midrule Dendrite & Input terminal & $\sim$100 \\ Axon & Output terminal & $\sim$10 \\ Soma & Cell body & up to $10^6$ \\ \bottomrule \end{tabular} \end{table} \section{Final instructions} Do not change any aspects of the formatting parameters in the style files. In particular, do not modify the width or length of the rectangle the text should fit into, and do not change font sizes (except perhaps in the \textbf{References} section; see below). Please note that pages should be numbered. \section{Preparing PDF files} Please prepare submission files with paper size ``US Letter,'' and not, for example, ``A4.'' Fonts were the main cause of problems in the past years. Your PDF file must only contain Type 1 or Embedded TrueType fonts. Here are a few instructions to achieve this. \begin{itemize} \item You should directly generate PDF files using \verb+pdflatex+. \item You can check which fonts a PDF files uses. In Acrobat Reader, select the menu Files$>$Document Properties$>$Fonts and select Show All Fonts. You can also use the program \verb+pdffonts+ which comes with \verb+xpdf+ and is available out-of-the-box on most Linux machines. \item The IEEE has recommendations for generating PDF files whose fonts are also acceptable for NeurIPS. Please see \url{http://www.emfield.org/icuwb2010/downloads/IEEE-PDF-SpecV32.pdf} \item \verb+xfig+ "patterned" shapes are implemented with bitmap fonts. Use "solid" shapes instead. \item The \verb+\bbold+ package almost always uses bitmap fonts. You should use the equivalent AMS Fonts: \begin{verbatim} \usepackage{amsfonts} \end{verbatim} followed by, e.g., \verb+\mathbb{R}+, \verb+\mathbb{N}+, or \verb+\mathbb{C}+ for $\mathbb{R}$, $\mathbb{N}$ or $\mathbb{C}$. You can also use the following workaround for reals, natural and complex: \begin{verbatim} \newcommand{\RR}{I\!\!R} \newcommand{\Nat}{I\!\!N} \newcommand{\CC}{I\!\!\!\!C} \end{verbatim} Note that \verb+amsfonts+ is automatically loaded by the \verb+amssymb+ package. \end{itemize} If your file contains type 3 fonts or non embedded TrueType fonts, we will ask you to fix it. \subsection{Margins in \LaTeX{}} Most of the margin problems come from figures positioned by hand using \verb+\special+ or other commands. We suggest using the command \verb+\includegraphics+ from the \verb+graphicx+ package. Always specify the figure width as a multiple of the line width as in the example below: \begin{verbatim} \usepackage[pdftex]{graphicx} ... \includegraphics[width=0.8\linewidth]{myfile.pdf} \end{verbatim} See Section 4.4 in the graphics bundle documentation (\url{http://mirrors.ctan.org/macros/latex/required/graphics/grfguide.pdf}) A number of width problems arise when \LaTeX{} cannot properly hyphenate a line. Please give LaTeX hyphenation hints using the \verb+\-+ command when necessary. \begin{ack} Use unnumbered first level headings for the acknowledgments. All acknowledgments go at the end of the paper before the list of references. Moreover, you are required to declare funding (financial activities supporting the submitted work) and competing interests (related financial activities outside the submitted work). More information about this disclosure can be found at: \url{https://neurips.cc/Conferences/2021/PaperInformation/FundingDisclosure}. Do {\bf not} include this section in the anonymized submission, only in the final paper. You can use the \texttt{ack} environment provided in the style file to autmoatically hide this section in the anonymized submission. \end{ack} \section*{References} References follow the acknowledgments. Use unnumbered first-level heading for the references. Any choice of citation style is acceptable as long as you are consistent. It is permissible to reduce the font size to \verb+small+ (9 point) when listing the references. Note that the Reference section does not count towards the page limit. \medskip { \small [1] Alexander, J.A.\ \& Mozer, M.C.\ (1995) Template-based algorithms for connectionist rule extraction. In G.\ Tesauro, D.S.\ Touretzky and T.K.\ Leen (eds.), {\it Advances in Neural Information Processing Systems 7}, pp.\ 609--616. Cambridge, MA: MIT Press. [2] Bower, J.M.\ \& Beeman, D.\ (1995) {\it The Book of GENESIS: Exploring Realistic Neural Models with the GEneral NEural SImulation System.} New York: TELOS/Springer--Verlag. [3] Hasselmo, M.E., Schnell, E.\ \& Barkai, E.\ (1995) Dynamics of learning and recall at excitatory recurrent synapses and cholinergic modulation in rat hippocampal region CA3. {\it Journal of Neuroscience} {\bf 15}(7):5249-5262. } \section*{Checklist} The checklist follows the references. Please read the checklist guidelines carefully for information on how to answer these questions. For each question, change the default \answerTODO{} to \answerYes{}, \answerNo{}, or \answerNA{}. You are strongly encouraged to include a {\bf justification to your answer}, either by referencing the appropriate section of your paper or providing a brief inline description. For example: \begin{itemize} \item Did you include the license to the code and datasets? \answerYes{See Section~\ref{gen_inst}.} \item Did you include the license to the code and datasets? \answerNo{The code and the data are proprietary.} \item Did you include the license to the code and datasets? \answerNA{} \end{itemize} Please do not modify the questions and only use the provided macros for your answers. Note that the Checklist section does not count towards the page limit. In your paper, please delete this instructions block and only keep the Checklist section heading above along with the questions/answers below. \begin{enumerate} \item For all authors... \begin{enumerate} \item Do the main claims made in the abstract and introduction accurately reflect the paper's contributions and scope? \answerTODO{} \item Did you describe the limitations of your work? \answerTODO{} \item Did you discuss any potential negative societal impacts of your work? \answerTODO{} \item Have you read the ethics review guidelines and ensured that your paper conforms to them? \answerTODO{} \end{enumerate} \item If you are including theoretical results... \begin{enumerate} \item Did you state the full set of assumptions of all theoretical results? \answerTODO{} \item Did you include complete proofs of all theoretical results? \answerTODO{} \end{enumerate} \item If you ran experiments... \begin{enumerate} \item Did you include the code, data, and instructions needed to reproduce the main experimental results (either in the supplemental material or as a URL)? \answerTODO{} \item Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)? \answerTODO{} \item Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)? \answerTODO{} \item Did you include the total amount of compute and the type of resources used (e.g., type of GPUs, internal cluster, or cloud provider)? \answerTODO{} \end{enumerate} \item If you are using existing assets (e.g., code, data, models) or curating/releasing new assets... \begin{enumerate} \item If your work uses existing assets, did you cite the creators? \answerTODO{} \item Did you mention the license of the assets? \answerTODO{} \item Did you include any new assets either in the supplemental material or as a URL? \answerTODO{} \item Did you discuss whether and how consent was obtained from people whose data you're using/curating? \answerTODO{} \item Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content? \answerTODO{} \end{enumerate} \item If you used crowdsourcing or conducted research with human subjects... \begin{enumerate} \item Did you include the full text of instructions given to participants and screenshots, if applicable? \answerTODO{} \item Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable? \answerTODO{} \item Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation? \answerTODO{} \end{enumerate} \end{enumerate} \section{Preliminaries and problem statement}\label{sec:prelims} We consider a discrete-time dynamical system \[ \mathbf{x}_{t+1} = f(\mathbf{x}_t,\mathbf{u}_t),\, \mathbf{x}_0\in\mathcal{X}_0. \] The dynamics are defined by the function $f:\mathcal{X}\times \mathcal{U}\rightarrow \mathcal{X}$ where $\mathcal{X}\subseteq \mathbb{R}^m$ is the state space and $\mathcal{U}\subseteq \mathbb{R}^n$ is the control action space, $\mathcal{X}_0\subseteq \mathcal{X}$ is the set of initial states and $t\in\mathbb{N}_{\geq 0}$ denotes a discretized time. At each time step $t$, the action is defined by the (possibly probabilistic) positional policy $\pi:\mathcal{X}\rightarrow\mathcal{D}(\mathcal{U})$, which maps the current state $\mathbf{x}_t$ to a distribution $\pi(\mathbf{x}_t)\in\mathcal{D}(U)$ over the set of actions. We use $\mathcal{D}(U)$ to denote the set of all probability distributions over $U$. The next action is then sampled according to $\mathbf{u}_t\sim \pi(\mathbf{x}_t)$, and together with the current state $\mathbf{x}_t$ of the system gives rise to the next state $\mathbf{x}_{t+1}$ of the system according to the dynamics $f$. Thus, the dynamics $f$ together with the policy $\pi$ form a closed-loop system (or a feedback loop system). The aim of the policy is to maximize the expected cumulative reward (possibly discounted) from each starting state. Given a set of initial states $\mathcal{X}_0$ of the system, we say that a sequence of state-action pairs $(\mathbf{x}_t,\mathbf{u}_t)_{t=0}^{\infty}$ is a trajectory if $\mathbf{x}_0\in \mathcal{X}_0$ and we have $\mathbf{u}_t\in\mathsf{supp}(\pi(\mathbf{x}_t))$ and $\mathbf{x}_{t+1} = f(\mathbf{x}_t,\mathbf{u}_t)$ for each $t\in\mathbb{N}_{\geq 0}$. A neural network (NN) is a function $\pi:\mathbb{R}^m\rightarrow \mathbb{R}^n$ that consists of several sequentially composed layers $\pi=l_1\circ\dots\circ l_k$. Formally, a NN policy maps each system state to a Dirac-delta distribution which picks a single action with probability $1$. Each layer $l_i$ is parametrized by learned weight values of the appropriate dimensions and an activation function $a$, \[ l_i(\mathbf{x}) = a(\mathbf{W}_i\mathbf{x}+\mathbf{b}_i), \mathbf{W}_i\in \mathbb{R}^{n_i\times m_i}, \mathbf{b}_i\in \mathbb{R}^{n_i}. \] In this work, we consider ReLU activation functions $a(\mathbf{x})=\textrm{ReLU}(\mathbf{x})=\max\{\mathbf{x},\mathbf{0}\}$, although other piecewise linear activation such as the leaky-ReLU \citep{JarrettKRL09} and PReLU \citep{HeZRS15} are applicable as well. In Bayesian neural networks (BNNs), weights are random variables and their values are sampled, each according to some distribution. Then each vector of sampled weights gives rise to a (deterministic) neural network. Given a training set $\mathcal{D}$, in order to train the BNN we assume a prior distribution $p(\mathbf{w},\mathbf{b})$ over the weights. The learning then amounts to computing the posterior distribution $p(\mathbf{w},\mathbf{b}\mid \mathcal{D})$ via the application of the Bayes rule. As analytical inference of the posterior is in general infeasible due to non-linearity introduced by the BNN architecture~\citep{MacKay92a}, practical training algorithms rely on approximate inference, e.g.~Hamiltonian Monte Carlo~\citep{neal2012bayesian}, variational inference~\citep{blundell2015weight} or dropout~\citep{GalG16}. When the policy in a dynamical system is a BNN, the policy maps each system state $\mathbf{x}_t$ to a probability distribution $\pi(\mathbf{x}_t)$ over the action space. Informally, this distribution is defined as follows. First, BNN weights $\mathbf{w}$, $\mathbf{b}$ are sampled according to the posterior BNN weight distribution, and the sampled weights give rise to a deterministic NN policy $\pi_{\mathbf{w},\mathbf{b}}$. The action of the system is then defined as $\mathbf{u}_t=\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}_t)$. Formal definition of the distribution $\pi(\mathbf{x}_t)$ is straightforward and proceeds by considering the product measure of distributions of all weights. \textbf{Problem statement} We now define the two safety problems that we consider in this work. The first problem considers feed-forward BNNs, and the second problem considers closed-loop systems with BNN policies. While our solution to the first problem will be a subprocedure in our solution to the second problem, the reason why we state it as a separate problem is that we believe that our solution to the first problem is also of independent interest for the safety analysis of feed-forward BNNs. Let $\pi$ be a BNN. Suppose that the vector $(\mathbf{w},\mathbf{b})$ of BNN weights in $\pi$ has dimension $p+q$, where $p$ is the dimension of $\mathbf{w}$ and $q$ is the dimension of $\mathbf{b}$. For each $1\leq i\leq p$, let $\mu_i$ denote the mean of the random variable $w_i$. Similarly, for each $1\leq i\leq q$, let $\mu_{p+i}$ denote the mean of the random variable $b_i$. Then, for each $\epsilon\in [0,\infty]$, we define the set $W^{\pi}_{\epsilon}$ of weight vectors via \[ W^{\pi}_{\epsilon} = \prod_{i=1}^{p+q}[\mu_i-\epsilon,\mu_i+\epsilon] \subseteq \mathbb{R}^{p+q}. \] We now proceed to defining our safety problem for feed-forward BNNs. Suppose that we are given a feed-forward BNN $\pi$, a set $\mathcal{X}_0\subseteq \mathbb{R}^m$ of input points and a set $\mathcal{X}_u\subseteq \mathbb{R}^n$ of unsafe (or bad) output points. For a concrete vector $(\mathbf{w},\mathbf{b})$ of weight values, let $\pi_{\mathbf{w},\mathbf{b}}$ to be the (deterministic) NN defined by these weight values. We say that $\pi_{\mathbf{w},\mathbf{b}}$ is safe if for each $\mathbf{x}\in\mathcal{X}_0$ we have $\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x})\not\in\mathcal{X}_u$, i.e.~if evaluating $\pi_{\mathbf{w},\mathbf{b}}$ on all input points does not lead to an unsafe output. \begin{adjustwidth}{1cm}{} \begin{problem}[Feed-forward BNNs]\label{problem1} Let $\pi$ be a feed-forward BNN, $\mathcal{X}_0\subseteq \mathbb{R}^m$ a set of input points and $\mathcal{X}_u\subseteq \mathbb{R}^n$ a set of unsafe output points. Let $\epsilon\in [0,\infty]$. Determine whether each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe. \end{problem} \end{adjustwidth} Next, we define our safety problem for closed-loop systems with BNN policies. Consider a closed-loop system defined by a dynamics function $f$, a BNN policy $\pi$ and an initial set of states $\mathcal{X}_0$. Let $\mathcal{X}_u\subseteq\mathcal{X}$ be a set of unsafe (or bad) states. We say that a trajectory $(\mathbf{x}_t,\mathbf{u}_t)_{t=0}^{\infty}$ is safe if $\mathbf{x}_t\not\in \mathcal{X}_u$ for all $t\in\mathbb{N}_0$, hence if it does not reach any unsafe states. Note that this definition implies infinite time horizon safety of the trajectory. Given $\epsilon\in[0,\infty]$, define the set $\mathsf{Traj}^{f,\pi}_{\epsilon}$ to be the set of all system trajectories in which each sampled weight vector belongs to $W^{\pi}_{\epsilon}$. \begin{adjustwidth}{1cm}{} \begin{problem}[Closed-loop systems with BNN policies]\label{problem2} Consider a closed-loop system defined by a dynamics function $f$, a BNN policy $\pi$ and a set of initial states $\mathcal{X}_0$. Let $\mathcal{X}_u$ be a set of unsafe states. Let $\epsilon\in [0,\infty]$. Determine whether each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{problem} \end{adjustwidth} Note that the question of whether the BNN policy $\pi$ is safe (i.e.~whether each trajectory of the system is safe) is a special case of the above problem which corresponds to $\epsilon=\infty$. \section{Proofs} \begin{manualtheorem}{1} Let $\epsilon\in[0,\infty]$. Then each deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ is safe if and only if the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is not satisfiable. \end{manualtheorem} \begin{proof} We prove the equivalent claim that there exists a weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ for which $\pi_{\mathbf{w},\mathbf{b}}$ is unsafe if and only if $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is satisfiable. \medskip First, suppose that there exists a weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ for which $\pi_{\mathbf{w},\mathbf{b}}$ is unsafe and we want to show that $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ is satisfiable. This direction of the proof is straightforward since values of the network's neurons on the unsafe input give rise to a solution of $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Indeed, by assumption there exists a vector of input neuron values $\mathbf{x}_0\in\mathcal{X}_0$ for which the corresponding vector of output neuron values $\mathbf{x}_l=\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}_0)$ is unsafe, i.e.~$\mathbf{x}_l\in\mathcal{X}_u$. By defining $\mathbf{x}_i^{\textrm{in}}$, $\mathbf{x}_i^{\textrm{out}}$ to be the vectors of the corresponding input and output neuron values for the $i$-th hidden layer for each $1\leq i\leq l-1$ and by setting $\mathbf{x}_{0,\textrm{pos}}=\textrm{ReLU}(\mathbf{x_0})$ and $\mathbf{x}_{0,\textrm{neg}}=-\textrm{ReLU}(-\mathbf{x}_0)$, we easily see that these variable values satisfy the Input-output conditions, the ReLU encoding conditions and the BNN input and hidden layer conditions, therefore we get a solution to the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. \medskip We now proceed to the more involved direction of this proof and show that any solution to the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$ gives rise to weights $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ for which $\pi_{\mathbf{w},\mathbf{b}}$ is unsafe. Let $\mathbf{x}_0$, $\mathbf{x}_l$, $\mathbf{x}_{0,\textrm{pos}}$, $\mathbf{x}_{0,\textrm{neg}}$ and $\mathbf{x}_i^{\textrm{in}}$, $\mathbf{x}_i^{\textrm{out}}$ for $1\leq i\leq l-1$, be real vectors that satisfy the system of constraints $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$. Fix $1\leq i\leq l-1$. From the BNN hidden layers constraint for layer i, we have \begin{equation}\label{eq:1} (\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_{i+1}^{\textrm{in}} \leq (\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i+\epsilon\cdot\mathbf{1}). \end{equation} We show that there exist values $\mathbf{W}_i^{\ast},\mathbf{b}_i^{\ast}$ of BNN weights between layers $i$ and $i+1$ such that each weight value is at most $\epsilon$ apart from its mean, and such that $\mathbf{x}_{i+1}^{\textrm{in}}=\mathbf{W}_i^{\ast}\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i^{\ast}$. Indeed, to formally show this, we define $W^{\pi}_{\epsilon}[i]$ to be the set of all weight vectors between layers $i$ and $i+1$ such that each weight value is distant from its mean by at most $\epsilon$ (hence, $W^{\pi}_{\epsilon}[i]$ is a projection of $W^{\pi}_{\epsilon}$ onto dimensions that correspond to the weights between layers $i$ and $i+1$). We then consider a continuous function $h_i:W^{\pi}_{\epsilon}[i]\rightarrow \mathbb{R}$ defined via \begin{equation*} h_i(\mathbf{W}_i,\mathbf{b}_i) = \mathbf{W}_i\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i. \end{equation*} Since $W^{\pi}_{\epsilon}[i]\subseteq\mathbb{R}^{m_i\times n_i}\times\mathbb{R}^{n_i}$ is a product of intervals and therefore a connected set w.r.t.~the Euclidean metric and since $h_i$ is continuous, the image of $W^{\pi}_{\epsilon}[i]$ under $h_i$ is also connected in $\mathbb{R}$. But note that \[ h_i(\mathbf{M}_i-\epsilon\cdot\mathbf{1},\mathbf{m}_i-\epsilon\cdot\mathbf{1})=(\mathbf{M}_i-\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i-\epsilon\cdot\mathbf{1}) \] and \[ h_i(\mathbf{M}_i+\epsilon\cdot\mathbf{1},\mathbf{m}_i+\epsilon\cdot\mathbf{1})=(\mathbf{M}_i+\epsilon\cdot\mathbf{1})\mathbf{x}_i^{\textrm{out}}+(\mathbf{m}_i+\epsilon\cdot\mathbf{1}), \] with $(\mathbf{M}_i-\epsilon\cdot\mathbf{1},\mathbf{m}_i-\epsilon\cdot\mathbf{1}),(\mathbf{M}_i+\epsilon\cdot\mathbf{1},\mathbf{m}_i+\epsilon\cdot\mathbf{1})\in W^{\pi}_{\epsilon}[i]$. Thus, for the two points to be connected, the image set must also contain $\mathbf{x}_{i+1}^{\textrm{in}}$ which lies in between by eq.~\eqref{eq:1}. Thus, there exists $(\mathbf{W}_i^{\ast},\mathbf{b}_i^{\ast})\in W^{\pi}_{\epsilon}[i]$ with $\mathbf{x}_{i+1}^{\textrm{in}}=\mathbf{W}_i^{\ast}\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i^{\ast}$, as desired. \medskip For the input and the first hidden layer, from the BNN input layer constraint we know that \begin{equation*} (\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0-\epsilon\cdot\mathbf{1}) \leq \mathbf{x}_1^{\textrm{in}} \leq (\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0+\epsilon\cdot\mathbf{1}). \end{equation*} Again, define $W^{\pi}_{\epsilon}[0]$ to be the set of all weight vectors between the input and the first hidden layer such that each weight value is distant from its mean by at most $\epsilon$. Consider a continuous function $h_0:W^{\pi}_{\epsilon}[0]\rightarrow \mathbb{R}$ defined via \begin{equation*} h_0(\mathbf{W}_0,\mathbf{b}_0) = \mathbf{W}_0\mathbf{x}_0+\mathbf{b}_0. \end{equation*} Let $\textrm{Msign}(\mathbf{x}_0)$ be a matrix of the same dimension as $\mathbf{M}_0$, with each column consisting of $1$'s if the corresponding component of $\mathbf{x}_0$ is nonnegative, and of $-1$'s if it is negative. Then note that \[ h_0(\mathbf{M}_0-\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0-\epsilon\cdot\mathbf{1})=(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0-\epsilon\cdot\mathbf{1}) \] and \[ h_0(\mathbf{M}_0+\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0+\epsilon\cdot\mathbf{1})=(\mathbf{M}_0+\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{pos}}+(\mathbf{M}_0-\epsilon\cdot\mathbf{1})\mathbf{x}_{0,\textrm{neg}}+(\mathbf{m}_0+\epsilon\cdot\mathbf{1}). \] Since $(\mathbf{M}_0-\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0-\epsilon\cdot\mathbf{1}),(\mathbf{M}_0+\epsilon\cdot\textrm{Msign}(\mathbf{x}_0),\mathbf{m}_0+\epsilon\cdot\mathbf{1})\in W^{\pi}_{\epsilon}[0]$, analogous image connectedness argument as the one above shows that there exist values $\mathbf{W}_0^{\ast},\mathbf{b}_0^{\ast}$ of BNN weights such tha $(\mathbf{W}_0^{\ast},\mathbf{b}_0^{\ast})\in W^{\pi}_{\epsilon}[0]$, and such that $\mathbf{x}_{1}^{\textrm{in}}=\mathbf{W}_0^{\ast}\mathbf{x}_0+\mathbf{b}_0^{\ast}$. \medskip But now, collecting $\mathbf{W}_0^{\ast},\mathbf{b}_0^{\ast}$ and $\mathbf{W}_i^{\ast},\mathbf{b}_i^{\ast}$ for $1\leq i\leq l-1$ gives rise to a BNN weight vector $(\mathbf{W}^{\ast},\mathbf{b}^{\ast})$ which is contained in $W^{\pi}_{\epsilon}$. Furthermore, combining what we showed above with the constraints in $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$, we get that: \begin{compactitem} \item $\mathbf{x}_0\in \mathcal{X}_0$, $\mathbf{x}_l\in\mathcal{X}_u$, from the Input-output condition in $\Phi(\pi,\mathcal{X}_0,\mathcal{X}_u,\epsilon)$; \item $\mathbf{x}_i^{\textrm{out}} = \textrm{ReLU}(\mathbf{x}_i^{\textrm{in}})$ for each $1\leq i\leq l-1$, from the ReLU-encoding; \item $\mathbf{x}_{1}^{\textrm{in}}=\mathbf{W}_0^{\ast}\mathbf{x}_0+\mathbf{b}_0^{\ast}$ and $\mathbf{x}_{i+1}^{\textrm{in}}=\mathbf{W}_i^{\ast}\mathbf{x}_i^{\textrm{out}}+\mathbf{b}_i^{\ast}$ for each $1\leq i\leq l-1$, as shown above. \end{compactitem} Hence, $\mathbf{x}_l\in\mathcal{X}_u$ is the vector of neuron output values of $\pi_{\mathbf{W}^{\ast},\mathbf{b}^{\ast}}$ on the input neuron values $\mathbf{x}_0\in\mathcal{X}_0$, so as $(\mathbf{W}^{\ast},\mathbf{b}^{\ast})\in W^{\pi}_{\epsilon}$ we conclude that there exists a deterministic NN in $\{\pi_{\mathbf{w},\mathbf{b}} \mid (\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}\}$ which is not safe. This concludes the proof. \end{proof} \begin{manualtheorem}{2} If there exists a $W^{\pi}_{\epsilon}$-safe positive invariant, then each trajectory in $\mathsf{Traj}^{f,\pi}_{\epsilon}$ is safe. \end{manualtheorem} \begin{proof} Let $\mathsf{Inv}$ be a $W^{\pi}_{\epsilon}$-safe positive invariant. Given a trajectory $(\mathbf{x}_t,\mathbf{u}_t)_{t=0}^{\infty}$ in $\mathsf{Traj}^{f,\pi}_{\epsilon}$, we need to show that $\mathbf{x}_t\not\in\mathcal{X}_u$ for each $t\in\mathbb{N}_{\geq 0}$. Since $\mathsf{Inv}\cap\mathcal{X}_u=\emptyset$, it suffices to show that $\mathbf{x}_t\in\mathsf{Inv}$ for each $t\in\mathbb{N}_{\geq 0}$. We prove this by induction on $t$. The base case $\mathbf{x}_0\in\mathsf{Inv}$ follows since $\mathbf{x}_0\in\mathcal{X}_0\subseteq \mathsf{Inv}$. As an inductive hypothesis, suppose now that $\mathbf{x}_t\in\mathsf{Inv}$ for some $t\in\mathbb{N}_{\geq 0}$. We need to show that $\mathbf{x}_{t+1}\in\mathsf{Inv}$. Since the trajectory is in $\mathsf{Traj}^{f,\pi}_{\epsilon}$, we know that the BNN weight vector $(\mathbf{w}_t,\mathbf{b}_t)$ sampled at the time-step $t$ belongs to $W^{\pi}_{\epsilon}$, i.e.~$(\mathbf{w}_t,\mathbf{b}_t)\in W^{\pi}_{\epsilon}$. Thus, since $\mathbf{x}_t\in\mathsf{Inv}$ by the induction hypothesis and since $\mathsf{Inv}$ is closed under the system dynamics when the sampled weight vector is in $W^{\pi}_{\epsilon}$, it follows that $\mathbf{x}_{t+1}=f(\mathbf{x}_t,\mathbf{u}_t)=f(\mathbf{x}_t,\pi_{\mathbf{w}_t,\mathbf{b}_t}(\mathbf{x}_t))\in \mathsf{Inv}$. This concludes the proof by induction. \end{proof} \begin{manualtheorem}{3} The loss function $\mathcal{L}$ is nonnegative for any neural network $g$, i.e.~$\mathcal{L}(g)\geq 0$. Moreover, if $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant and $\mathcal{L}_{\textrm{cls}}$ the 0/1-loss, then $\mathcal{L}(g^{\mathsf{Inv}})=0$. Hence, neural networks $g^{\mathsf{Inv}}$ for which $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant are global minimizers of the loss function $\mathcal{L}$ when $\mathcal{L}_{\textrm{cls}}$ is the 0/1-loss. \end{manualtheorem} \begin{proof} Recall, the loss function $\mathcal{L}$ for a neural network $g$ is defined via \begin{equation}\label{eq:totallossupmat} \mathcal{L}(g) = \frac{1}{|D_{\textrm{spec}}|}\sum_{(\mathbf{x},y)\in D_{\textrm{spec}}}^{}\mathcal{L}_{\textrm{cls}}\big(g(\mathbf{x}),y\big) +\lambda \frac{1}{|D_{\textrm{ce}}|}\sum_{(\mathbf{x},\mathbf{x}')\in D_{\textrm{ce}}}^{}\mathcal{L}_{\textrm{ce}}\big(g(\mathbf{x}),g(\mathbf{x}')\big), \end{equation} where $\lambda$ is a tuning parameter and $\mathcal{L}_{\textrm{cls}}$ a binary classification loss function, e.g.~the 0/1-loss $\mathcal{L}_{\textrm{0/1}}(z,y) = \mathds{1}[\mathds{1}[z\geq0]\neq y]$ or the logistic loss $\mathcal{L}_{\textrm{log}}(z,y)= z - z \cdot y + \log(1 + \exp(-z))$ as its differentiable alternative. The term $\mathcal{L}_{\textrm{ce}}$ is the counterexample loss which we define via \begin{equation}\label{eq:losssupmat} \mathcal{L}_{\textrm{ce}}(z,z') = \mathds{1}\big[z>0\big]\mathds{1}\big[z'<0\big] \mathcal{L}_{\textrm{cls}}\big(z,0\big) \mathcal{L}_{\textrm{cls}}\big(z',1\big). \end{equation} The fact that $\mathcal{L}(g)\geq 0$ for each neural network $g$ follows immediately from the fact that summands in the first sum in eq.~\eqref{eq:totallossupmat} are loss functions which are nonnegative, and summands in the second sum are products of indicator and nonnegative loss functions and therefore also nonnegative. We now show that, if $\mathcal{L}_{\textrm{cls}}$ is the 0/1-loss, $\mathcal{L}(g^{\mathsf{Inv}})=0$ whenever $\mathsf{Inv}$ is a $W^{\pi}_{\epsilon}$-safe positive invariant, which implies the global minimization claim in the theorem. This follows from the following two items: \begin{compactitem} \item For each $(\mathbf{x},y)\in D_{\textrm{spec}}$, we have $\mathcal{L}_{\textrm{cls}}\big(g^{\mathsf{Inv}}(\mathbf{x}),y\big)=0$. Indeed, for $(\mathbf{x},y)$ to be added to $D_{\textrm{spec}}$ in Algorithm~1, we must have that either $\mathbf{x}\in\mathcal{X}_0$ and $y=1$, or that $\mathbf{x}\in\mathcal{X}_u$ and $y=0$. Thus, since $\mathsf{Inv}$ is assumed to be a $W^{\pi}_{\epsilon}$-safe positive invariant, $g^{\mathsf{Inv}}$ correctly classifies $(\mathbf{x},y)$ and the corresponding loss is $0$. \item For each $(\mathbf{x},\mathbf{x}')\in D_{\textrm{ce}}$ we have $\mathcal{L}_{\textrm{ce}}\big(g^{\mathsf{Inv}}(\mathbf{x}),g^{\mathsf{Inv}}(\mathbf{x}')\big)=0$. Indeed, since \[ \mathcal{L}_{\textrm{ce}}(g^{\mathsf{Inv}}(\mathbf{x}),g^{\mathsf{Inv}}(\mathbf{x}')) = \mathds{1}\big[g^{\mathsf{Inv}}(\mathbf{x})>0\big]\mathds{1}\big[g^{\mathsf{Inv}}(\mathbf{x}')<0\big] \mathcal{L}_{\textrm{cls}}\big(g^{\mathsf{Inv}}(\mathbf{x}),0\big) \mathcal{L}_{\textrm{cls}}\big(g^{\mathsf{Inv}}(\mathbf{x}'),1\big), \] for the loss to be non-zero we must have that $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and $g^{\mathsf{Inv}}(\mathbf{x})<0$. But this is impossible since $\mathsf{Inv}$ is assumed to be a $W^{\pi}_{\epsilon}$-safe positive invariant and $(\mathbf{x},\mathbf{x}')$ was added by Algorithm~1 as a counterexample to $D_{\textrm{ce}}$, meaning that $\mathbf{x}'$ can be reached from $\mathbf{x}$ by following the dynamics function and sampling a BNN weight vector in $W^{\pi}_{\epsilon}$. Therefore, by the closedness property of $W^{\pi}_{\epsilon}$-safe positive invariants when the sampled weight vector is in $W^{\pi}_{\epsilon}$, we cannot have both $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and $g^{\mathsf{Inv}}(\mathbf{x})<0$. Hence, the loss must be $0$. \end{compactitem} \end{proof} \begin{manualtheorem}{4} If the verifier in Algorithm~1 shows that constraints in three checks are unsatisfiable, then the computed $\mathsf{Inv}$ is indeed a $W^{\pi}_{\epsilon}$-safe positive invariant. Hence, Algorithm~1 is correct. \end{manualtheorem} \begin{proof} The fact that the first check in Algorithm~1 correctly checks whether there exist $\mathbf{x},\mathbf{x}'\in\mathcal{X}_0$ and a weight vector $(\mathbf{w},\mathbf{b})\in W^{\pi}_{\epsilon}$ such that $\mathbf{x}'=f(\mathbf{x},\pi_{\mathbf{w},\mathbf{b}}(\mathbf{x}))$ with $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and $g^{\mathsf{Inv}}(\mathbf{x}')<0$ follows by the correctness of our encoding in Section~4.1, which was proved in Theorem~1. The fact that checks 2 and 3 correctly check whether for all $\mathbf{x}\in\mathcal{X}_0$ we have $g^{\mathsf{Inv}}(\mathbf{x})\geq 0$ and for all $\mathbf{x}\in\mathcal{X}_u$ we have $g^{\mathsf{Inv}}(\mathbf{x})<0$, respectively, follows immediately from the conditions they encode. Therefore, the three checks together verify that (1)~$\mathsf{Inv}$ is closed under the system dynamics whenever the sampled weight vector is in $W^{\pi}_{\epsilon}$, (2)~$\mathsf{Inv}$ contains all initial states, and (3)~$\mathsf{Inv}$ contains no unsafe states. As these are the $3$ defining properties of $W^{\pi}_{\epsilon}$-safe positive invariants, Algorithm~1 is correct and the theorem claim follows. \end{proof} \section{Safe exploration reinforcement learning algorithm} Algorithm \ref{algorithm:serl} shows our sketch of how standard RL algorithms, such as policy gradient methods and deep Q-learning, can be adapted to a safe exploration setup by using the safe weight sets computed by our method. \begin{algorithm}[t] \caption{Safe Exploration Reinforcement Learning} \label{algorithm:serl} \begin{algorithmic} \STATE \textbf{Input} Initial policy $\pi_{0}$, learning rate $\alpha$, number of iterations $N$ \FOR{$i \in 1,\dots N$} \STATE $\epsilon \leftarrow$ find safe $\epsilon$ for $\pi_{i-1}$ \STATE collect rollouts of $\pi_{i-1}$ with rejection sampling $\epsilon$ \STATE compute $\nabla \mu_{i-1}$ for parameters $\mu_{i-1}$ of $\pi_{i-1}$ using DQN/policy gradient \STATE $\mu_i \leftarrow \mu_{i-1} - \alpha \nabla \mu_{i-1}$ (gradient descent) \STATE project $\mu_i$ back to interval $[\mu_{i-1}-\epsilon,\mu_{i-1}+\epsilon]$ \ENDFOR \STATE \textbf{Return} $\pi_{N}$ \end{algorithmic} \end{algorithm} \section{Experimental details} In this section, we describe the details of our experimental evaluation setup. The code and pre-trained network parameters are attached in the supplementary materials. Each policy is a ReLU network consisting of three layers. The first layer represents the input variables, the second one is a hidden layer with 16 neurons, and the last layer are the output variables. The size of the first and the last layer is task dependent and is shown in Table \ref{tab:epx}. The $W^{\pi}_{\epsilon}$-safe positive invariant candidate network differs from the policy network in that its weights are deterministic, it has a different number of hidden units and a single output dimension. Particularly, the invariant networks for the linear dynamical system and the inverted pendulum have 12 hidden units, whereas the invariant network for the collision avoidance task has 32 neurons in its hidden layer. The policy networks are trained with a $\mathcal{N}(0,0.1)$ (from second layer on) and $\mathcal{N}(0,0.05)$ (all weights) prior for the Bayesian weights, respectively. MILP solving was performed by Gurobi 9.03 on a 4 vCPU with 32GB virtual machine. \begin{table}[] \centering \begin{tabular}{c|ccc}\toprule Experiment & Input dimension & Hidden size & Output dimension \\\midrule Linear dynamical system & 2 & 16 & 1 \\ Inverted pendulum & 2 & 16 & 1 \\ Collision avoidance & 3 & 16 & 3\\\bottomrule \end{tabular} \caption{Number of dimensions of the policy network for the three experiments.} \label{tab:epx} \end{table} \paragraph{Linear dynamical system} The state of the linear dynamical system consists of two variables $(x,y)$. The update function takes the current state $(x_t,y_t)$ with the current action $u_t$ and outputs the next states $(x_{t+1},y_{t+1})$ governed by the equations \begin{align*} y_{t+1} &= y_t + 0.2\cdot \textrm{clip}_{\pm 1}(u_t)\\ x_{t+1} &= x_t + 0.3 y_{t+1} + 0.05\cdot \textrm{clip}_{\pm 1}(u_t),\\ \end{align*} where the function $\text{clip}_{\pm 1}$ is defined by \begin{equation*} \textrm{clip}_{\pm z}(x) = \begin{cases}-z & \text{ if } x\leq -z\\ z & \text{ if } x\geq z\\ x & \text{ otherwise. }\end{cases} \end{equation*} The set of unsafe states is defined as $\{(x,y)\in\mathbb{R}^2\mid|(x,y)|_{\infty}\geq 1.2\}$, and the initial states as $\{(x,y)\in\mathbb{R}^2\mid |(x,y)|_{\infty}\leq 0.6\}$. \paragraph{Inverted pendulum} The state of the inverted pendulum consists of two variables $(\theta,\dot{\theta})$. The non-linear state transition is defined by \begin{align*} \dot{\theta}_{t+1} &= \textrm{clip}_{\pm 8}\big(\dot{\theta}_t + \frac{-3g\cdot \textrm{angular}(\theta_t + \pi)}{2l} + \delta_t\frac{7.5 \textrm{clip}_{\pm 1}(u_t)}{(m\cdot l^2)}\big)\\ \theta_{t+1} &= \theta_t + \dot{\theta}_{t+1} * \delta_t, \end{align*} where $g=9.81,l=1,\delta_t=0.05$ and $m=0.8$ are constants. The function $\textrm{angular}$ is defined using the piece-wise linear composition \begin{equation*} \textrm{angular}(x) = \begin{cases} \textrm{angular}(x+2\pi) & \text{ if } x \leq \pi / 2\\ \textrm{angular}(x-2\pi) & \text{ if } x > 5 \pi / 2\\ \frac{x - 2\pi}{\pi / 2} & \text{ if } 3 \pi / 2 < x \leq 5 \pi / 2\\ 2 - \frac{x}{\pi / 2} & \text{ if } \pi / 2 < x \leq 3 \pi / 2. \end{cases} \end{equation*} The set of initial states are defined by $\{(\theta,\dot{\theta})\in\mathbb{R}^2\mid |\theta| \leq \pi/6 \text{ and } |\dot{\theta}|\leq0.2 \}$. The set of unsafe states are defined by $\{(\theta,\dot{\theta})\in\mathbb{R}^2\mid |\theta| \geq 0.9 \text{ or } |\dot{\theta}|\geq2 \}$. \paragraph{Collision avoidance} The state of the collision avoidance environment consists of three variables $(p_x,a_x,a_y)$, representing the agent's vertical position and the vertical and the horizontal position of an intruder. The intruder moves toward the agent, while the agent's vertical position must be controlled to avoid colliding with the intruder. The particular state transition is given by \begin{align*} p_{x,t+1} &= p_{x,t} + u_{t}\\ a_{x,t+1} &= a_{x,t}\\ a_{y,t+1} &= a_{y,t} - 1.\\ \end{align*} Admissible actions are defined by $u_t \in \{-1,0,1\}$. The set of initial states are defined as $\{(p_x,a_x,a_y)\in\mathbb{Z}^3\mid |p_x|\leq 2 \text{ and } |a_x|\leq 2 \text{ and } a_y=5\}$. Likewise, the set of unsafe states are given by $\{(p_x,a_x,a_y)\in\mathbb{Z}^3\mid |p_x-a_x|\leq 1 \text{ and } a_y=5\}$.
{'timestamp': '2021-11-08T02:05:07', 'yymm': '2111', 'arxiv_id': '2111.03165', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03165'}
arxiv
\section{Introduction}\label{intro} \section{Introduction}\label{mot} In this paper, an extension of Principal Component Analysis (PCA) and its rigorous justification are considered. In comparison with known techniques, the proposed extension of PCA allows us to improve the associated accuracy and diminish the numerical load. The innovation of the proposed methodology, differences from the known results and advantages are specified in Sections \ref{wn9w}, \ref{dif77}, \ref{x78an} and \ref{x78kl}. PCA is a technique for finding so called principal components (PCs) of the data of interest represented by a large random vector, i.e. components of a smaller vector which preserve the principal features of the data. PCA also provides a reconstruction of PCs to the original data vector with the least possible error among all linear transforms. According to Jolliffe \cite{Jolliffe2002}, ``Principal component analysis is probably the oldest and best known of the techniques of multivariate analysis''. This is a topic of intensive research which has an enormous number of related references. For instance, a Google search for `principal component analysis' returns about $8,160,000$ results. In particular, the references which are most related to this paper (from our point view) are represented in \cite{Brillinger2001,681430,905856,Tomasz1293,DuongNguyen2014288,tor5277,Scharf1991113}. PCA is used in a number of application areas (in an addition to the previous references see, for example, \cite{diam96,du2006,Saghri2010,gao111}). Therefore, related techniques with a better performance are of vital importance. By PCA in \cite{Jolliffe2002,Brillinger2001}, under the strong restriction of invertibility of the covariance matrix, the procedures for finding the PCs and their reconstruction are determined by the matrix of the rank less or equal to $k$ where $k$ is the number of required PCs. For a fixed number of PCs, the PCA accuracy of their reconstruction to the original data cannot be improved. In other words, PCA has the {\em only degree of freedom} to control the accuracy, it is the number of PCs. Moreover, PCA in the form obtained, in particular, in \cite{Jolliffe2002,Brillinger2001}, is not applicable if the associated covariance matrix is singular. Therefore, in \cite{tor843}, the generalizations of PCA, called generalized Brillinger transforms (GBT1 and GBT2), have been developed. First, the GBT1 and GBT2 are applicable to the case of singular covariance matrices. Second, the GBT2 allows us to improve the errors associated with PCA and the GBT1. We call it the generic Karhunen-Lo\`{e}ve transform (GKLT). The GKLT requires an additional knowledge of covariance matrices $E_{x y^2}$ and $E_{y^2 y^2}$ where $\x$ and $\y$ are stochastic vectors, and $\y^2$ is a Hadamard square of $\y$ (more details are provided in Section \ref{gbt1} below). Such knowledge may be difficult. Another difficulty associated with the GBT2 and GKLT is their numerical load which is larger than that of PCA. Further, it follows from \cite{924074} that the GKLT accuracy is better than that of PCA in \cite{Jolliffe2002,Brillinger2001,681430} subject to the condition which is quite difficult to verify (see Corollary 3 in \cite{924074}). Moreover, for the GBT2 in \cite{tor843}, such an analysis has not been provided. We are motivated by the development of an extension of PCA which covers the above drawbacks. We provide both a detailed theoretical analysis of the proposed extension of PCA and numerical examples that illustrate the theoretical results. \section{Review of PCA and its known generalizations GB1, GB2, GKLT}\label{gbt1} First, we introduce some notation which is used below. Let $\x=[\x_1,\ldots, \x_m]^T\in L^2(\Omega,\mathbb{R}^m)$ and $\y=[\y_1,\ldots, \y_n]^T\in L^2(\Omega,\mathbb{R}^n)$ be random vectors\footnote{Here, $\Omega=\{\omega\}$ is the set of outcomes, $\Sigma$ a $\sigma$-field of measurable subsets of $\Omega$, $\mu:\Sigma\rightarrow[0,1]$ an associated probability measure on $\Sigma$ with $\mu(\Omega)=1$ and $(\Omega,\Sigma,\mu)$ for a probability space.}. Vectors $\x$ and $\y$ are interpreted as reference data and observable data, respectively, i.e. $\y$ is a noisy version of $\x$. Dimensions $m$ and $n$ are assumed to be large. Suppose we wish to denoise $\y$ and reduce it to a `shorter' vector $\uu\in L^2(\Omega,\mathbb{R}^k)$ where $k \leq \min \{m, n\}$, and then reconstruct $\uu$ to vector $\widetilde{\x}$ such that $\widetilde{\x}$ is as close to $\x$ as possible. Entries of vector $\uu$ are called the principal components (abbreviated above as PCs). Let us write $ \displaystyle \|{\bf x}\|^2_{\Omega} =\int_\Omega \|{\bf x}(\omega)\|_2^2 d\mu(\omega) < \infty, $ where $\|{\bf x}(\omega)\|_2$ is the Euclidean norm of ${\bf x}(\omega)\in\mathbb{R}^m$. Throughout the paper, we assume that means $E[\x]$ and $E[\y]$ are known. Therefore, without loss of generality, we will assume henceforth that $\x$ and $\y$ have zero means. Then the covariance matrix formed from $\x$ and $\y$ is given by $E_{xy}=E[\x\y^T]=\{e_{ij}\}_{i,j=1}^{m,n}\in\rt^{m\times n}$ where $\displaystyle e_{ij} = \int_\Omega \x_i(\omega) \y_j(\omega) d\mu(\omega)$. Further, the singular value decomposition (SVD) of matrix $M\in \rt^{m\times n}$ is given by $M=U_M\Sigma_M V_M^T$ where $U_M=[u_1 \;u_2\;\ldots u_m]\in \rt^{m\times m}, V_M=[v_1 \;v_2\;\ldots v_n]\in \rt^{n\times n}$ are unitary matrices, and $\Sigma_M=\diag(\sigma_1(M),$ $\ldots,$ $\sigma_{\min(m,n)}(M))\in\rt^{m\times n}$ is a generalized diagonal matrix, with the singular values $\sigma_1(M)\ge \sigma_2(M)\ge\ldots\ge 0$ on the main diagonal. Further, $M^{\dag}$ denotes the Moore-Penrose pseudo-inverse matrix for matrix $M$. The generalizations of PCA mentioned in Section \ref{mot}, GBT1 and GBT2 \cite{tor843}, are represented as follows. Let us first consider the GBT2 since the GBT1 is a particular case of the GBT2. The GBT2 is given by \begin{eqnarray}\label{bnm11} B_2(\y)=R_1 [P_1\y + P_2\vv], \end{eqnarray} where $\vv\in L^2(\Omega,\mathbb{R}^n)$ is an `auxiliary' random vector used to further optimize the transform, {\bf (Assoc. Edit.: More explanations!!!) } and matrices $R_1\in\rt^{m\times k}$, $P_1\in\rt^{k\times n}$ and $P_2\in\rt^{k\times n}$ solve the problem\footnote{Note that in (\ref{bnm11}) and (\ref{byfx}), strictly speaking, $R_1$ $P_1$ and $P_2$ should be replaced with operators $\rrr_1: L^2(\Omega,\mathbb{R}^k) \rightarrow L^2(\Omega,\mathbb{R}^m)$, $\p_1: L^2(\Omega,\mathbb{R}^n) \rightarrow L^2(\Omega,\mathbb{R}^k)$ and $\p_2: L^2(\Omega,\mathbb{R}^n) \rightarrow L^2(\Omega,\mathbb{R}^k)$, respectively. This is because each matrix, say, $R_1\in\rt^{m\times k}$ defines a bounded linear transformation $\rrr_1: L^2(\Omega,\mathbb{R}^k) \rightarrow L^2(\Omega,\mathbb{R}^m)$. Nevertheless, it is customary to write $R_1$ rather then $\rrr_1$, since $[\rrr_1(\uu)](\omega) = R_1[\uu(\omega)]$, for each $\omega\in \Omega$. We keep this type of notation throughout the paper.} \begin{equation}\label{byfx} \min_{R,\hspace*{1mm} [P_1 P_2]} \displaystyle \|\x - R_1 [P_1\y + P_2\vv]\|_\Omega^2 \end{equation} so that, for $\qq=[\y^T \vv^T]^T\in L^2(\Omega,\mathbb{R}^{2n})$ and $G_q = E_{x q}E_{qq}^{\dag}E_{q x}$, \begin{eqnarray}\label{ac11} R_1= U_{G_q,k},\hspace*{4mm} [P_1, P_2] = \hspace*{-1mm}U_{G_q,k}^T E_{x q}E_{qq}^{\dag}, \end{eqnarray} where $U_{G_q,k}$ is formed by the first $k$ columns of $U_{G_k}$, and $P_1$ and $P_2$ are represented by the corresponding blocks of matrix $U_{G_q,k}^T E_{x q}E_{qq}^{\dag}$. The principal components are then given by $\uu = [P_1, P_2][\y^T \vv^T]^T$. The GBT1 follows from the GBT2 if $R_1 P_2\vv=\mathbf 0$, where $\mathbf 0$ is the zero vector. That is, the GBT2 has one matrix more (i.e., one degree of freedom more) than the GBT1. This allows us to improve the GBT2 performance compared to that by the GBT1 (see \cite{tor843} for more detail). The GKLT \cite{924074} is given by \begin{eqnarray}\label{qmiw8} \kk (\y)=K_1\y + K_2\y^2, \end{eqnarray} where matrices $K_1\in\rt^{m\times n}$ and $K_2\in\rt^{m\times n}$ solve the problem \begin{equation}\label{by29} \min_{ \substack{[K_1 K_2]\\ \rank [K_1 K_2]\leq k}} \displaystyle \|\x - [K_1 \y + K_2\y^2]\|_\Omega^2, \end{equation} and $\y^2$ is given by the Hadamard square so that $\y^2(\omega) = [\y_1^2(\omega),\ldots,\y_n^2(\omega)]^T$, for all $\omega\in\Omega$. PCA is a particular case of the GKLT if $K_2\y^2={\mathbf 0}$ and matrix $E_{yy}$ is non-singular. The PCA, BT, GBT1, GKLT and GBT2 follow from the solution of essentially the same optimization problem. The differences are that first, the associated solutions are obtained under different assumptions and second, the solutions result in transforms that have different computational schemes. More details can be found in \cite{tor843}. Further, each of PCA and the GBT1 has $m\times n$ parameters to optimize, which are entries of matrices $K_1$ and $R_1P_1$, respectively. Similar to PCA, the GBT1 has one degree of freedom to improve the associated accuracy, it is the number $k$ of PCs, i.e., the dimension of vector $\uu$. Thus, for fixed $k$, the GBT1 accuracy cannot be improved. The GKLT \cite{924074} and GBT2 \cite{tor843} each have two degrees of freedom, $k$ and one matrix more than in PCA and GBT1. That is, the GKLT and GBT2 have twice as many parameters to optimize compared to PCA and GBT1. It is shown in \cite{tor843,924074} that this feature allows us to improve the accuracy associated with the GKLT and GBT2 \section{Contribution and novelty}\label{wn9w} We propose and justify the PCA extension which\\ \hspace*{5mm} $\bullet$ always exists, i.e. is applicable to the case of singular data (this is because it is constructed in terms of pseudo-inverse matrices; see Section \ref{det}),\\ \hspace*{5mm} $\bullet$ has better associated accuracy than that of the GBT1, GBT2 and GKLT (Sections \ref{298an}, \ref{1n8an}, \ref{nbm198}), \\ \hspace*{5mm} $\bullet$ has more degrees of freedom to improve the associated accuracy than the PCA, GBT1, GBT2 and GKLT (Sections \ref{xvb8an} and \ref{speccases}),\\ \hspace*{5mm} $\bullet$ has a lower computational load than that of the GBT2 and GKLT; in fact, for large $m, n$, it is about 37\% of that of the GBT2 and 22\% of that of the GKLT (Section \ref{cm9vn}),\\ \hspace*{5mm} $\bullet$ does not require the usage of matrices $E_{x y^2}$ and $E_{y^2 y^2}$ (as required in \cite{924074}) which are difficult to determine. Further, we show, in particular, that \\ \hspace*{5mm} $\bullet$ the condition for the GKLT \cite{924074} mentioned in Section \ref{gbt1} (under which the accuracy improvement is achieved) can be omitted (Section \ref{298an}). In more detail, in the proposed PCA extension, the additional degrees of freedom are provided by the auxiliary random vectors $\w$ and $\h$ which are introduced below in Sections \ref{w0an} and \ref{xvb8an}, respectively. Vectors $\w$ and $\h$ are called $\w$-injection and $\h$-injection. An improvement in the accuracy of the proposed transform follows from the increase in the number of parameters to optimize, which are represented by matrices $T_0$, $T_1$, specific vector transformation $\f$ (Sections \ref{w0an} and \ref{det1}), and $\w$-injection and $\h$-injection (Sections \ref{stat}, \ref{x78an} and \ref{speccases} ). \section{Structure of the proposed PCA extension}\label{w0an} The above advantages are achieved due to the special structure of the proposed transform as follows. Let $\w\in L^2(\Omega,\mathbb{R}^\ell)$ be a random vector and $\f: L^2(\Omega,\mathbb{R}^n)\times L^2(\Omega,\mathbb{R}^\ell) \rightarrow L^2(\Omega,\mathbb{R}^\ell)$ be a transformation of $\y$ and $\w$ in a random vector $\s\in L^2(\Omega,\mathbb{R}^\ell)$, i.e. $$ \s = \f(\y,\w). $$ Reasons for using vector $\w$ and transformation $\f$ are detailed in Sections \ref{stat}, \ref{x78an} and \ref{speccases} below. We propose to determine the PCs and their reconstruction $\widetilde{\x}$ by the transform $\ttt $ given by \begin{eqnarray}\label{sjk92} \widetilde{\x}=\ttt (\y, \w) = T_0\y + T_1 \f(\y, \w), \end{eqnarray} where $T_0$ and $T_1$ are represented by $m\times n$ and $m\times \ell$ matrices, respectively, and \begin{eqnarray}\label{xnm93} \rank [T_0 \hspace*{1mm} T_1] \leq k, \end{eqnarray} where $k=\min\{m, n\}$. Here, three terms, $T_0$, $T_1$ and $\f$, are to be determined. Therefore, transform $\ttt$ will be called the three-term $k$-rank transform. A special version of the three-term $k$-rank transform is considered in Section \ref{xvb8an} below. \section{Statement of the problems}\label{stat} Below, we assume that $\x$, $\y$ and $\w$ are nonzero vectors. {\em Problem 1}: Find matrices $T_0$ and $T_1$ that solve \begin{eqnarray}\label{589mb} \min_{[T_0 \hspace*{1mm} T_1]}\|\x - [ T_0\y + T_1 \f(\y, \w)]\|^2_\Omega \end{eqnarray} subject to constraint (\ref{xnm93}), and determine $\f$ that provides, for $\zz = [\y^T \s^T]^T$, \begin{eqnarray}\label{akl7} E_{zz} =\left[ \begin{array}{cc} E_{yy} & \oo\\ \oo & E_{ss} \end{array} \right], \end{eqnarray} where $\oo$ denotes the zero matrix. The importance of the condition in (\ref{akl7}) is twofold. First, this allows us to facilitate computation associated with a determination of $T_0$ and $T_1$. Second, the condition in (\ref{akl7}) is used in the solution of the Problem 2 stated below. The transform obtained from the solution of Problem 1 (see Section \ref{det1} that follows) is called the {\em optimal} three-term $k$-rank transform or the {\sf\em three-term PCA.} {\em Problem 2}: Show that the error associated with the three-term PCA is less than that of the PCA, GBT1 (see Section \ref{298an}), GBT2 and GKLT (see Section \ref{xvb8an}). Further, show that the computational load associated with the tree-term PCA is less than that of the GBT2 (see Section \ref{58b29}). \section{Differences from known techniques}\label{dif77} The proposed three-term PCA differs from PCA in \cite{Jolliffe2002,Brillinger2001} in several instances. Unlike PCA in \cite{Jolliffe2002,Brillinger2001}, the three-term PCA has the additional terms $T_1$, $\f$ and $\w$-injection, which lead to the improvement in the associated accuracy of determining PCs and the consecutive reconstruction of PCs to the original vector. As distinct from the PCA in \cite{Jolliffe2002,Brillinger2001}, the three-term PCA is always applicable to singular data since it is determined in terms of pseudo-inverse matrices. Differences of the three-term PCA from the GBT2 are threefold. First, the three-term PCA contains transformation $\f$ aimed to facilitate computation. Second, in the three-term PCA, the procedure for determining principal components and their reconstruction to an estimate of $\x$ is different from that in the GBT2. Indeed, the three-term PCA can be written as \begin{eqnarray}\label{sj382} \ttt (\y, \w) = R_1 P_1\y + R_2 P_2\s, \end{eqnarray} where $R_1, R_2$, $P_1$ and $P_2$ are obtained in the form different from those in the GBT2 (see Theorem \ref{389nm} below). Third, in Section \ref{xvb8an} that follows, we show that a special transformation of vector $\s$ to a vector $\widetilde{\s}$ of a greater dimensionality allows us to achieve the better associated accuracy of $\x$ estimation. Differences from the GKLT in (\ref{qmiw8}) are similar and even stronger since the GKLT contains vector $\y^2$ (not $\vv$ as the GBT2) which cannot be changed. The above differences imply the improvement in the performance of the three-term PCA. This issue is detailed in Sections \ref{x78an} and \ref{x78kl} that follow. \section{Solution of Problem 1}\label{det} \subsection{Preliminaries}\label{prel} First, we recall some known results that will be used in the solution of Problems 1 and 2. \begin{proposition} {\em \cite[Theorem 1.21, p. 44]{zhang2005schur}}\label{proposition5} Let $M$ be a positive semi-definite matrix given in the block form $ M=\left[ \begin{array}{cc} A & B \\ B^T & C \\ \end{array} \right], $ where blocks $A$ and $C$ are square. Let $S=C-B^TA^\dagger B$ and $$ N =\left[ \begin{array}{cc} A^\dagger +A^\dagger BS^\dagger B^TA^\dagger & -A^\dagger BS^\dagger \\ -S^\dagger B^TA^\dagger & S^\dagger \\ \end{array} \right]. $$ Then $N=M^\dagger$ if and only if $\mbox{rank}(M)=\mbox{rank}(A)+\mbox{rank}(C)$. \end{proposition} \begin{proposition}{\em \cite[p. 217]{Zhang2011}}\label{proposition6} If $M$ is positive definite, then the condition $\mbox{rank} (M)=\mbox{rank} (A)+\mbox{rank} (C)$ of Proposition \ref{proposition5} is always true and $N=M^{-1}$. \end{proposition} \begin{proposition}{\em \cite[Lemma 4.5.11]{harville2008matrix}}\label{proposition10} For any matrices $A$ and $B$, \begin{eqnarray}\label{zmnb91} \mbox{\rm rank}\left[ \begin{array}{cc} A & \oo \\ \oo & B \\ \end{array} \right]=\mbox{\rm rank}(A)+\mbox{\rm rank}(B). \end{eqnarray} \end{proposition} \begin{proposition} {{\em (Weyl's inequality)}} {\em \cite[Corollary 4.3.15]{9780511810817}}\label{proposition8} Let $A$ and $B$ be $m\times m$ symmetric matrices and let singular values $\sigma_i(A)$, $\sigma_i(B)$ and $\sigma_i(A+B)$, for $i=1,\ldots, m$, be arranged in decreasing order. Then, for $i=1,\ldots, m$, \begin{eqnarray}\label{7hb91} \sigma_i(A)+\sigma_{m}(B)\leq \sigma_i(A+B)\leq \sigma_i(A)+\sigma_{1}(B). \end{eqnarray} \end{proposition} \subsection{Determination of three-term PCA}\label{det1} Let $$\displaystyle P_{M,L}=\hspace*{-4mm}\sum_{k=1}^{\rank (M)}u_k u_k^T\in \rt^{m\times m}, \hspace*{3mm} \displaystyle P_{M,R}=\hspace*{-4mm} \sum_{j=1}^{\rank (M)}v_j v_j^T\in \rt^{n\times n}$$ be the orthogonal projections on the range of matrices $M$ and $M^T$ respectively, and let \begin{eqnarray}\label{mkumk1} [M]_k= \sum_{i=1}^{k}\sigma_i(M)u_i v_i^T\in \rt^{m\times n} \end{eqnarray} for $k=1,\ldots,\rank (M)$, be the truncated SVD of $M$. For $k>\rank (M)$, we define $[M]_k=M\;(=M_{\rank (M)})$. For $1\le k<\rank (M)$, the matrix $M_k$ is uniquely defined if and only if $\sigma_k(M)>\sigma_{k+1}(M)$. Further, $M^{1/2}$ denotes a matrix square root for matrix $M$. For the covariance matrix $E_{x x}$, we denote $E_{x x}^{1/2 \dag}:=(E_{ x x}^{1/2})^ {\dag}$. Matrix $E_{ x x}^{1/2 \dag}$ is unique since $E_{x x}$ is positive semidefinite. The Frobenius matrix norm is denoted by $\|\cdot\|$. Let us denote $G_{xy}=E_{xy}E_{yy}^\dag$ and $G_z = E_{x z}E_{zz}^{\dag}E_{z x}$. Similar to $U_{G_q,k}$ in (\ref{ac11}), $U_{G_z,k}$ denotes the matrix formed by the first $k$ columns of $U_{G_z}$. Recall that, as before in (\ref{akl7}), $\zz=[\y^T \s^T]^T$. \begin{theorem}\label{389nm} Let transformation $\f$ in (\ref{sjk92}) be determined by \begin{eqnarray}\label{smi91} \f(\y, \w) = \s = \w - G_{wy} \y. \end{eqnarray} Then (\ref{akl7}) is true, and $T_0$ and $T_1$ that solve the problem in (\ref{589mb}), (\ref{xnm93}) are such that \begin{eqnarray}\label{z,.23} [T_0\hspace*{1.5mm} T_1] = U_{G_z,k}U_{G_z,k}^T [G_{xy}\hspace*{1.5mm} G_{xs}](I + N) \end{eqnarray} where $N= M(I - P_{E_{zz}^{1/2},L})$ and matrix $M$ is arbitrary\footnote{In other words, the solution is not unique.}. The unique minimum norm solution of problem (\ref{589mb}), (\ref{xnm93}) is given by \begin{eqnarray}\label{294b} T_0 = U_{G_z,k}U_{G_z,k}^T G_{xy}\qa T_1 = U_{G_z,k}U_{G_z,k}^T G_{xs}, \end{eqnarray} where \begin{eqnarray}\label{2mox5} G_z = G_y + G_s. \end{eqnarray} \end{theorem} \begin{proof} For vector $\s$ defined by (\ref{smi91}), $$ E_{ys} = E[\y (\w - E_{wy}E_{yy}^\dag \y)^T]=E_{yw} - E_{yy}E_{yy}^\dag E_{yw}=\oo $$ because by Corollary 1 in {\em\cite{924074}}, $E_{yw} = E_{yy}E_{yy}^\dag E_{yw}$. Then (\ref{akl7}) follows. Further, since $\|\x\|^2_\Omega = \mbox{\em tr} \hspace*{.5mm}E[\x \x^T]$ (see {\em\cite[pp. 166-167]{torbook2007}}) then, for $T=[T_0\hspace*{.5mm} T_1]$, \begin{eqnarray}\label{wnmui} \|\x - [ T_0\y + T_1 \f(\y, \w)]\|^2_\Omega &=& \|\x - T\zz\|^2_\Omega\nonumber\\ &=& \mbox{\em tr}\hspace*{.5mm} E\{(\x - T\zz) (\x - T\zz)^T\}\nonumber\\ &=& \|E_{xx}^{1/2}\|^{2} - \|E_{xz}{E_{zz}^{1/2}}^\dag\|^{2} \nonumber\\ & &\hspace*{17mm} + \|E_{xz}{E_{zz}^{1/2}}^\dag - T{E_{zz}^{1/2}}\|^{2}. \end{eqnarray} Therefore, the problem in (\ref{589mb})--(\ref{xnm93}) is reduced to \begin{eqnarray}\label{} \min_{T: \rank T \leq k} \|E_{xz}{E_{zz}^{1/2}}^\dag - T{E_{zz}^{1/2}}\|^{2}. \end{eqnarray} Its solution is given in \cite{tor5277} by \begin{eqnarray}\label{xm02} T=[T_0 \hspace*{1mm} T_1] = [E_{xz}{E_{zz}^\dag}^{1/2}]_k{E_{zz}^\dag}^{1/2}(I + N). \end{eqnarray} Let us write $U_Q\Sigma_Q V_Q^T = Q$ for the SVD of $Q=E_{xz}{E_{zz}^\dag}^{1/2}$. Then by \cite{tor843}, \begin{eqnarray}\label{amn82} [E_{xz}{E_{zz}^\dag}^{1/2}]_k = U_{Q, k} U_{Q, k}^T E_{xz}{E_{zz}^\dag}^{1/2}. \end{eqnarray} Since ${G_z}=Q Q^T$ then $U_{G_z}=U_Q$ and $U_{{G_z}, k} = U_{Q, k}$. Therefore, (\ref{xm02}) and (\ref{amn82}) imply \begin{eqnarray}\label{9cn02} T=[T_0 \hspace*{1mm} T_1] = U_{{G_z}, k}U_{{G_z}, k}^T G_{xz}(I + N). \end{eqnarray} Here, on the basis of (\ref{akl7}), \begin{eqnarray}\label{am198n} G_{xz} = [E_{xy}\hspace*{1.5mm} E_{xs}]\left[ \begin{array}{cc} E_{yy}^\dag & \oo\\ \oo & E_{ss}^\dag \end{array} \right] = [G_{xy}\hspace*{1.5mm} G_{xs}] \end{eqnarray} and \begin{eqnarray}\label{348vn} &&\hspace*{-30mm} {G_z}=[E_{xy}\hspace*{1.5mm} E_{xs}]\left[ \begin{array}{cc} E_{yy}^\dag & \oo\\ \oo & E_{ss}^\dag \end{array} \right] \left[ \begin{array}{c}E_{yx}\\ E_{sx}\end{array} \right] \nonumber\\ &&\hspace*{-20mm} = E_{xy}E_{yy}^\dag E_{yx} + E_{xs}E_{ss}^\dag E_{sx}= G_{y} + G_{s}. \end{eqnarray} Then (\ref{z,.23}), (\ref{294b}) and (\ref{2mox5}) follow. $\hfill\blacksquare$ \end{proof} Thus, the three-term PCA is represented by (\ref{sjk92}), (\ref{smi91}), (\ref{z,.23}) and (\ref{294b}). \section{Analysis of the error associated with three-term PCA} Let us denote the error associated with the three-term PCA by \begin{eqnarray}\label{s89mb} \varepsilon_{m,n,\ell} (T_0, T_1) = \min_{\substack{[T_0 \hspace*{1mm} T_1]: \\ \rank [T_0 \hspace*{1mm} T_1] \leq k}}\|\x - [ T_0\y + T_1 \f(\y, \w)]\|^2_\Omega. \end{eqnarray} The following theorem establishes a priori determination of $\varepsilon_{m,n,\ell} (T_0, T_1)$. \begin{theorem}\label{377nm} Let $\f$, $T_0$ and $T_1$ be determined by Theorem \ref{389nm}. Then \begin{eqnarray}\label{215smb} \varepsilon_{m,n,\ell} (T_0, T_1) = \|E_{xx}^{1/2}\|^{2} - \sum_{i=1}^{k} \sigma_i ({G_z}). \end{eqnarray} \end{theorem} \begin{proof} It follows from (\ref{wnmui}) and (\ref{xm02}) that \begin{eqnarray}\label{q28mb} &&\hspace*{-10mm}\varepsilon_{m,n,\ell} (T_0, T_1) \nonumber\\ &=& \|E_{xx}^{1/2}\|^{2} - \|E_{xz}{E_{zz}^{1/2}}^\dag\|^{2} + \|E_{xz}{E_{zz}^{1/2}}^\dag - [E_{xz}{E_{zz}^\dag}^{1/2}]_k{E_{zz}^\dag}^{1/2}(I + N){E_{zz}^{1/2}}\|^{2}\nonumber\\ &=& \|E_{xx}^{1/2}\|^{2} - \|E_{xz}{E_{zz}^{1/2}}^\dag\|^{2} + \|E_{xz}{E_{zz}^{1/2}}^\dag - [E_{xz}{E_{zz}^\dag}^{1/2}]_k \|^{2}. \end{eqnarray} The latter is true because by Lemma 42 in \cite[p. 311]{torbook2007}, $$ [E_{xz}{E_{zz}^\dag}^{1/2}]_k = [E_{xz}{E_{zz}^\dag}^{1/2}]_k{E_{zz}^\dag}^{1/2}{E_{zz}^{1/2}}. $$ Then \begin{eqnarray}\label{qr56b} \varepsilon_{m,n,\ell} (T_0, T_1)& = & \|E_{xx}^{1/2}\|^{2} - \sum_{i=1}^{m} \sigma_i({G_z}) + \sum_{i=k+1}^{m} \sigma_i({G_z})\nonumber\\ & = & \|E_{xx}^{1/2}\|^{2} - \sum_{i=1}^{k} \sigma_i({G_z}). \end{eqnarray} Thus, (\ref{215smb}) is true.\hfill$\blacksquare$ \end{proof} \section{Advantages of three-term PCA}\label{x78an} Here and in Section \ref{x78kl} below, we justify in detail the advantages of the three-term PCA that have been highlighted in Section \ref{wn9w}. \subsection{Solution of Problem 2. Improvement in the associated error compared to PCA and GBT1}\label{298an} We wish to show that the error associated with the three-term PCA, ${\varepsilon_{m,n,\ell} (T_0, T_1)}$, is less than that of PCA and the GBT1 \cite{tor843}. A similar statement has been provided in Corollary 3 in \cite{924074} under the condition which is difficult to verify. In Theorems \ref{xnm91n} and \ref{mak92n} below, we show that the condition can be omitted. Let us denote the error associated with the GBT1 by \begin{eqnarray}\label{3290b} \varepsilon_{m,n} (B_0) = \min_{\substack{B_0\in{\mathbb R}^{m\times n}: \\ \rank (B_0) \leq k}}\|\x - B_0\y\|^2_\Omega. \end{eqnarray} Matrix $B_0=R_1P_1$ that solves the RHS in (\ref{3290b}) follows from (\ref{ac11}) if $R_1 P_2\vv=\mathbf 0$ (see Section \ref{gbt1}). \begin{theorem}\label{xnm91n} For any non-zero random vectors $\x, \y$ and $\w$, \begin{eqnarray}\label{al9b} \varepsilon_{m,n,\ell} (T_0, T_1) \leq \varepsilon_{m,n} (B_0). \end{eqnarray} If $G_s=E_{xs}E_{ss}^\dag E_{sx}$ is positive definite then \begin{eqnarray}\label{al9xc} \varepsilon_{m,n,\ell} (T_0, T_1) < \varepsilon_{m,n} (B_0). \end{eqnarray} \end{theorem} \begin{proof} It is known {\em \cite{tor843}} that \begin{eqnarray}\label{xm819} \varepsilon_{m,n} (B_0) = \|E_{xx}^{1/2}\|^{2} - \sum_{i=1}^{k} \sigma_i ({G_y}). \end{eqnarray} Consider ${G_z} = G_y + ({G_z} - {G_y}).$ Clearly, ${G_z} - {G_y}$ is a symmetric matrix. Then on the basis of (\ref{7hb91}) in the above Proposition \ref{proposition8}, \begin{eqnarray}\label{20mna} \sigma_i(G_y)+\sigma_{m}({G_z} - {G_y})\leq \sigma_i(G_z), \end{eqnarray} where $$ {G_z} - {G_y} = G_s=MM^T $$ and $M = E_{xs}{E_{ss}^\dag}^{1/2}$. Thus, by Theorem 7.3 in \cite{Zhang2011}, ${G_z} - {G_y}$ is a positive semi-definite matrix and then all its eigenvalues are nonnegative \cite[p. 167]{golub2013matrix}, i.e., $\sigma_i({G_z} - {G_y})\geq 0.$ Therefore, (\ref{20mna}) implies $ \sigma_i ({G_y})\leq \sigma_i ({G_z}), $ for all $i=1,\ldots,n$, and then \begin{eqnarray}\label{akl81} \sum_{i=1}^k\sigma_i ({G_y})\leq \sum_{i=1}^k\sigma_i ({G_z}). \end{eqnarray} As a result, (\ref{al9b}) follows from (\ref{215smb}), (\ref{xm819}) and (\ref{akl81}). In particular, if $G_s$ is positive definite then $\sigma_i({G_z} - {G_y}) > 0$, for $i=1,\ldots,n$ and therefore, (\ref{al9xc}) is true.\hfill$\blacksquare$ \end{proof} In the following Theorem \ref{mak92n}, we refine the result obtained in the above Theorem \ref{xnm91n}. \begin{theorem}\label{mak92n} Let, as before, $k= \min \{m, n\}.$ There exists $\gamma\in [\sigma_m(G_s), \sigma_{1}(G_s)]$ such that \begin{eqnarray}\label{al917} \varepsilon_{m,n,\ell} (T_0, T_1) = \varepsilon_{m,n} (B_0) - k\gamma, \end{eqnarray} i.e., the error associated with the three-term PCA is less than that of the GBT1 by $k\gamma$. \end{theorem} \begin{proof} The Weyl's inequality in (\ref{7hb91}) and the equality in (\ref{348vn}) imply, for $i= 1,\ldots, m$, \begin{eqnarray*}\label{7dmnf1} \sigma_i(G_y)+\sigma_{m}(G_s)\leq \sigma_i(G_z)\leq \sigma_i(G_y)+\sigma_{1}(G_s) \end{eqnarray*} which, in turn, implies \begin{eqnarray*} \sigma_{m}(G_s)\leq \sigma_i(G_z) - \sigma_i(G_y)\leq \sigma_{1}(G_s) \end{eqnarray*} and \begin{eqnarray*} \sum_{i=1}^k\sigma_{m}(G_s)\leq \sum_{i=1}^k[\sigma_i(G_z) - \sigma_i(G_y)]\leq \sum_{i=1}^k\sigma_{1}(G_s). \end{eqnarray*} Therefore, \begin{eqnarray*} k\sigma_{m}(G_s)\leq \sum_{i=1}^k\sigma_i(G_z) - \sum_{i=1}^k\sigma_i(G_y)\leq k\sigma_{1}(G_s) \end{eqnarray*} and \begin{eqnarray*} k\sigma_{m}(G_s)\leq \left(\|E_{xx}^{1/2}\|^{2} - \sum_{i=1}^k\sigma_i(G_y)\right) - \left(\|E_{xx}^{1/2}\|^{2} - \sum_{i=1}^k\sigma_i(G_z)\right)\leq k\sigma_{1}(G_s). \end{eqnarray*} Thus \begin{eqnarray*} k\sigma_{m}(G_s)\leq \varepsilon_{m,n} (B_0) - \varepsilon_{m,n,\ell} (T_0, T_1) \leq k\sigma_{1}(G_s) \end{eqnarray*} and \begin{eqnarray*} \frac{\varepsilon_{m,n} (B_0) - \varepsilon_{m,n,\ell} (T_0, T_1)}{k} \in [\sigma_{m}(G_s), \sigma_{1}(G_s)], \end{eqnarray*} and then (\ref{al917}) follows. $\hfill\blacksquare$ \end{proof} \begin{remark} If $G_s$ is a full rank matrix then $\sigma_{m}(G_s)\neq 0$ and therefore, $\gamma\neq 0$, i.e. in this case, (\ref{al917}) implies that $\varepsilon_{m,n,\ell} (T_0, T_1)$ is always less than $\varepsilon_{m,n} (B_0)$. If $\rank (G_s) = r_s$ where $r_s <m$ then $\sigma_{m}(G_s) = 0$ and $\gamma\in [0, \sigma_{1}(G_s)]$, i.e. in this case, $\gamma$ might be equal to $0$. \end{remark} \begin{remark} Recall that PCA is a particular case of the GBT1 (see Section \ref{gbt1}). Therefore, in Theorems \ref{xnm91n} and \ref{mak92n}, $\varepsilon_{m,n} (B_0)$ can be treated as the error associated with PCA, under the restriction that matrix $E_{yy}$ is non-singular. \end{remark} \subsection{ Decrease in the error associated with the three-term PCA with the increase in the injection dimension}\label{xvb8an} In Theorem \ref{w791n} that follows we show that the error $\varepsilon_{m,n,\ell} (T_0, T_1)$ associated with the three-term PCA (represented by (\ref{sjk92}), (\ref{smi91})--(\ref{294b})) can be decreased if vector $\s$ is extended to a new vector $\widetilde\s$ of a dimension which is larger than that of vector $\s$. The vector $\widetilde\s$ is constructed as $\widetilde\s = [\s^T \gf^T]^T$ where $\gf = \h - G_{h z}\zz\in L^2(\Omega,\mathbb{R}^\eta)$, $G_{h z}=E_{h z}E_{z z}^\dag$ and $\h\in L^2(\Omega,\mathbb{R}^\eta)$ is arbitrary. As we mentioned before, similar to $\w$-injection, vector $\h$ is called the $\h$-injection. As before, $\s$ is defined by (\ref{smi91}) and $\zz=[\y^T \s^T]^T$. Thus, $\widetilde\s \in L^2(\Omega,\mathbb{R}^{(\ell+\eta)})$ while $\s \in L^2(\Omega,\mathbb{R}^\ell)$, i.e. the dimension of $\widetilde\s$ is larger than that of $\s$ by $\eta$ entries. In terms of $\widetilde\s$, the three-term PCA is represented as \begin{eqnarray}\label{sjk49} \sss (\y, \w,\h) = S_0\y + S_1\widetilde\s, \end{eqnarray} where similar to $T_0$ and $T_1$ in (\ref{294b}), and for $\widetilde{\zz}=[\y^T \hspace*{1mm} \widetilde{\s}^T]^T$, matrices $S_0$ and $S_1$ are given by \begin{eqnarray}\label{wn202} S_0 = U_{G_{\widetilde{z}},k}U_{G_{\widetilde{z}},k}^T G_{xy}\qa S_1 = U_{G_{\widetilde{z}},k}U_{G_{\widetilde{z}},k}^T G_{x {\widetilde{s}}}. \end{eqnarray} Here, $G_{\widetilde{z}} = G_y + G_{\widetilde{s}}$ and $G_{\widetilde{s}} = E_{x {\widetilde{s}}}E_{{\tilde{s}}{\tilde{s}}}^{\dag}E_{{\widetilde{s}} x}$. The associated error is denoted by \begin{eqnarray}\label{cn920} \varepsilon_{m,n,\ell+\eta} (S_0, S_1) = \min_{\substack{[S_0 \hspace*{1mm} S_1]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [S_0 \hspace*{1mm} S_1] \leq k}}\|\x - [ S_0\y + S_1\widetilde\s]\|^2_\Omega. \end{eqnarray} \begin{theorem}\label{w791n} For any non-zero random vectors $\x, \y,\w$ and $\h$, \begin{eqnarray}\label{cnm201} \varepsilon_{m,n,\ell+\eta} (S_0, S_1) \leq \varepsilon_{m,n,\ell} (T_0, T_1). \end{eqnarray} If $G_s=E_{xs}E_{ss}^\dag E_{sx}$ is positive definite then \begin{eqnarray}\label{q87201} \varepsilon_{m,n,\ell+\eta} (S_0, S_1) < \varepsilon_{m,n,\ell} (T_0, T_1). \end{eqnarray} \end{theorem} \begin{proof} Let us represent $S_1$ in terms of two blocks, $S_{11}$ and $S_{12}$, i.e., $S_1 = [S_{11}\hspace*{1mm} S_{12}],$ and also write ${\widehat S} = [S_{0}\hspace*{1mm} S_{11}]$. Then \begin{eqnarray}\label{190cn3} & &\hspace*{-30mm} \min_{\substack{[S_0 \hspace*{1mm} S_1]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [S_0 \hspace*{1mm} S_1] \leq k}}\left\|\x - [ S_0\y + S_1\widetilde\s]\right\|^2_\Omega\nonumber\\ & = & \min_{\substack{[S_0 \hspace*{1mm} S_1]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [S_0 \hspace*{1mm} S_1] \leq k}}\left\|\x - \left[ S_0\y + S_1\left[ \begin{array}{c} \s \\ \gf \\ \end{array} \right]\right]\right\|^2_\Omega \nonumber\\ & = & \min_{\substack{[S_0 \hspace*{1mm} S_1]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [S_0 \hspace*{1mm} S_1] \leq k}}\left\|\x - [ S_0\y + S_{11}\s + S_{12}\gf ]\right\|^2_\Omega \nonumber \\ & = &\min_{\substack{[S_0 \hspace*{1mm} S_1]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [S_0 \hspace*{1mm} S_1] \leq k}} \left\|\x - [{\widehat S}\zz + S_{12}\gf ]\right\|^2_\Omega. \end{eqnarray} Here, $[S_0 \hspace*{1mm} S_1] = [S_0 \hspace*{1mm} S_{11}\hspace*{1mm} S_{12}] = [{\widehat S}\hspace*{1mm} S_{12}]$. Therefore, \begin{eqnarray}\label{3333m} & &\hspace*{-37mm} \min_{\substack{[S_0 \hspace*{1mm} S_1]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [S_0 \hspace*{1mm} S_1] \leq k}} \left\|\x - [{\widehat S}\zz + S_{12}\gf ]\right\|^2_\Omega\nonumber\\ & = & \min_{\substack{[{\widehat S} \hspace*{1mm} S_{12}]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [{\widehat S} \hspace*{1mm} S_{12}] \leq k}}\|\x - [{\widehat S}\zz + S_{12}\gf ]\|^2_\Omega. \end{eqnarray} In (\ref{s89mb}), let us write $\varepsilon_{m,n,\ell} (T_0, T_1)$ in terms of $\s$, \begin{eqnarray}\label{qg59mb} \varepsilon_{m,n,\ell} (T_0, T_1) = \min_{\substack{[T_0 \hspace*{1mm} T_1]\in{\mathbb R}^{m\times (n+\ell)}: \\ \rank [T_0 \hspace*{1mm} T_1] \leq k}}\|\x - [ T_0\y + T_1 \s]\|^2_\Omega. \end{eqnarray} Then by (\ref{al9b}) in Theorem \ref{xnm91n}, \begin{eqnarray}\label{po02m} & & \hspace*{-35mm}\min_{\substack{[{\widehat S} \hspace*{1mm} S_{12}]\in{\mathbb R}^{m\times (n+\ell+\eta)}: \\ \rank [{\widehat S} \hspace*{1mm} S_{12}] \leq k}}\|\x - [{\widehat S}\zz + S_{12}\gf ]\|^2_\Omega \nonumber\\ &\leq &\min_{\substack{T\in{\mathbb R}^{m\times (n+\ell)}: \\ \rank (T) \leq k}}\|\x - T\zz\|^2_\Omega\nonumber\\ & = &\min_{\substack{[T_1 \hspace*{1mm} T_2]\in{\mathbb R}^{m\times (n+\ell)}: \\ \rank [T_1 \hspace*{1mm} T_2] \leq k}}\left\|\x - [T_0 \hspace*{1mm} T_1]\left[ \begin{array}{c} \y \\ \s \\ \end{array} \right]\right\|^2_\Omega\nonumber\\ & = &\min_{\substack{[T_0 \hspace*{1mm} T_1]\in{\mathbb R}^{m\times (n+\ell)}: \\ \rank [T_0 \hspace*{1mm} T_1]\leq k}} \|\x - [T_0\y +T_1\s]\|^2_\Omega, \end{eqnarray} where $T = [T_0 \hspace*{1mm} T_1]$, $T_0\in{\mathbb R}^{m\times n}$ and $T_1\in{\mathbb R}^{m\times \ell}$. Then (\ref{cnm201}) follows from (\ref{3333m}) and (\ref{po02m}), and (\ref{al9xc}) implies (\ref{q87201}). $\hfill\blacksquare$ \end{proof} \begin{remark}\label{hjk29} An intuitive explanation of the statement of Theorem \ref{w791n} is that the increase in the dimension of vector $\widetilde\s$ implies the increase in the dimension of matrix $S_1$ in (\ref{sjk49}) so that $S_1\in\rt^{m\times (n+\ell+\eta)}$ while in (\ref{sjk92}), (\ref{smi91})--(\ref{294b}), $T_1\in\rt^{m\times (n+\ell)}$. Therefore, the optimal matrix $S_1$ has $m\times \eta$ entries more than $T_1$ to further minimize the associated error. As a result, the three-term PCA in form (\ref{sjk49}), for the same number of principal components $k$, provides the more accurate reconstruction of $\x$ than the three-term PCA in form (\ref{sjk92}). \end{remark} \subsection{Decrease in the error associated with the three-term PCA compared with that of the GBT2 and GKLT}\label{1n8an} In Theorem \ref{wd87n} below, we show that the three-term PCA in (\ref{sjk49})-(\ref{wn202}) provides the associated accuracy which is better than that of the GBT2 in (\ref{bnm11})-(\ref{ac11}). Let us denote the error associated with the GBT2 by \begin{eqnarray}\label{ii9m} \varepsilon_{m,n} (B_0, B_1) = \min_{\substack{[B_0 \hspace*{1mm} B_1]\in{\mathbb R}^{m\times (2n)}: \\ \rank [B_0 \hspace*{1mm} B_1]\leq k}} \|\x - [B_0\y +B_1\vv]\|^2_\Omega, \end{eqnarray} where $B_0=R_1 P_1$ and $B_1=R_1 P_2$ are determined by (\ref{ac11}). In fact, the result below is a version of Theorem \ref{w791n} as follows. \begin{theorem}\label{wd87n} Let $\s = \vv$ where $\ell = n$, and random vector $\vv$ is the same as in (\ref{bnm11})-(\ref{ac11}). Then for any non-zero random vectors $\x, \y$ and $\h$, \begin{eqnarray}\label{cnm101} \varepsilon_{m,n,n+\eta} (S_0, S_1) \leq \varepsilon_{m,n} (B_0, B_1). \end{eqnarray} If $G_s=E_{xs}E_{ss}^\dag E_{sx}$ is positive definite then \begin{eqnarray}\label{n29h01} \varepsilon_{m,n,n+\eta} (S_0, S_1) < \varepsilon_{m,n} (B_0, B_1). \end{eqnarray} \end{theorem} \begin{proof} We observe that Theorem \ref{w791n} is true for any form of $\s$. In particular, it is true for $\s = \vv$ where $\ell = n$ and random vector $\vv$ is the same as in (\ref{bnm11})-(\ref{ac11}). Then (\ref{cnm101}) and (\ref{n29h01}) follow from (\ref{cnm201}) and (\ref{q87201}), respectively. $\hfill\blacksquare$ \end{proof} \begin{remark}\label{op28m} Theorem \ref{wd87n} is also valid for $\s = \y^2$ with $\ell =n$. Thus, in this case, the three-term PCA in (\ref{sjk49})-(\ref{wn202}) provides the associated accuracy which is better than that of the GKLT in (\ref{qmiw8}). \end{remark} \section{Special cases of three-term PCA}\label{speccases} In both forms of the three-term PCA represented by (\ref{sjk92}) and (\ref{sjk49}), vectors $\s$ and $\widetilde \s$ are constructed from auxiliary random vectors called $\w$-injection and $\h$-injection, respectively, which are assumed to be arbitrary. At the same time, a natural desire is to understand if there are approaches for choosing $\w$ and $\h$ which may (or may not) improve the three-term PCA performance. Here, such approaches are considered. \subsection{Case 1. Choice of $\w$ on the basis of Weierstrass theorem}\label{} For the three-term PCA represented by (\ref{sjk92}), a seemingly reasonable choice of vector $\w$ is $\w = \y^2$ where $\y^2$ is defined by the Hadamard product, $\y^2 = \y\circ \y$, i.e. by $\y^2(\omega) = [\y^2_1(\omega), \ldots, \y^2_n(\omega)]^T$, for all $\omega\in \Omega$. This is because if $\ttt(\y, \w)$ in (\ref{sjk92}) is written as $\ttt(\y, \y^2) = T_0\y + T_1 \f(\y,\y^2)$, then $\ttt(\y, \y^2)$ can be interpreted as a polynomial of the second degree. If $T_0$ and $T_1$ are defined by Theorem \ref{389nm} then $\ttt(\y, \y^2)$ can be considered as an approximation to an `idealistic' transform $\p$ such that $\x=\p(\y)$. On the basis of the Stone-Weierstrass theorem \cite{Kreyszig1978,Timofte2005}, $\ttt(\y, \y^2)$ should seemingly provide a better associated approximation accuracy of $\p(\y)$ than that of the first degree polynomial $\ttt(\y) = T_0\y$. Nevertheless, the constraint of the reduced ranks implies a deterioration of $\p(\y)$ approximation by $\ttt(\y, \y^2) = T_0\y + T_1\y^2$. That constraint is not a condition of the Stone-Weierstrass theorem. To the best of our knowledge, an extension of the Stone-Weierstrass theorem to a best {\em rank constrained} estimation of $\x$ is still not justified. Further, if for example, $\y = \x +\bxi$ where $\bxi$ is a random noise, then $\y^2 = \x^2 +2\x\circ\bxi + \bxi^2$, i.e., $\y^2$ becomes even more corrupted than $\y$. Another inconvenience is that a knowledge or evaluation of matrices $E_{x y^2}$ and $E_{y^2 y^2}$ is difficult. For the above reasons, the choice of $\w$ in the form $\w = \y^2$ is not preferable. \subsection{Case 2. Choice of $\w$ as an optimal estimate of $\x$}\label{} Another seemingly reasonable choice of $\w$-injection in (\ref{sjk92}) is $\w=A\y$ where $A=E_{xy}E_{yy}^\dag$, i.e. $\w=E_{xy}E_{yy}^\dag \y$ is the optimal minimal-norm linear estimation of $\x$ \cite{torbook2007}. Nevertheless, in this case, $\s = A(\y - E_{yy}E_{yy}^\dag \y)$ and then $$ E_{xs} = (E_{xy} -E_{xy}E_{yy}^\dag E_{yy})A^T = \oo $$ since $E_{xy} =E_{xy}E_{yy}^\dag E_{yy}$ \cite[p. 168]{torbook2007}. The latter implies $E_{xs} E_{ss}^\dag = \oo$. As a result, by (\ref{294b}), $T_1=\oo$ and then in (\ref{sjk92}), $ \ttt(\y,\w) = T_0\y$. In other words, this choice of $\w$ is unreasonable since then the three-term PCA in (\ref{sjk92}), (\ref{294b}) is reduced to the GBT1 in \cite{tor843}. \subsection{ Case 3. Choice of $\h$: `worse is better'}\label{vnb01m} It has been shown in Theorem \ref{w791n} that the error associated with the three-term PCA represented by (\ref{sjk49}) decreases if vector $\s\in L^2(\Omega,\mathbb{R}^{\ell})$ is replaced with a new vector $\widetilde{\s}\in L^2(\Omega,\mathbb{R}^{(\ell+\eta)})$ of a larger dimension. Recall, in (\ref{sjk49}), $\widetilde{\s}$ is formed from an arbitrary $\h\in L^2(\Omega,\mathbb{R}^{\eta})$. In particular, for $\eta = 0$, (\ref{cnm201}) implies $\varepsilon_{m,n,\ell+\eta} (S_0, S_1) = \varepsilon_{m,n,\ell} (T_0, T_1)$. Thus, the increase in $\eta$ implies the decrease in the error associated with the three-term PCA represented by (\ref{sjk49}). Thus, a reasonable (and quite surprising) choice of $\h$ is as follows: $\h$ is random and $\eta$ is large. This is similar to the concept `worse is better' \cite{Gabriel}, i.e., a random $\h$ with large dimension $\eta$ (`worse') is a preferable option (`better') in terms of practicality and usability over, for example, the choice of $\w$ considered, for instance, in Case 1. In Case 1, the dimension of $\w=\y^2$ is $n$ and cannot be changed while dimension $\ell$ can vary and, in particular, can be increased. Another advantage over Case 1 is that there is no need to evaluate matrices $E_{x y^2}$ and $E_{y^2 y^2}$ as required in Case 1. In Example \ref{m2b9} that follows, we numerically illustrate Theorem \ref{w791n} and Case 3. \begin{example}\label{m2b9} Let ${\bf{x}}=[\x_1,\ldots, \x_m]^T\in L^2(\Omega,\mathbb{R}^{m})$ represent a temperature distribution in $m$ locations in Australia. Entries of $\x$ and corresponding locations are represented in Table \ref{table1}. \begin{table}[h] \centering \begin{tabular}{|c|c|} \hline Entry & Location \\ \hline $\x_1$ & Canberra \\ \hline $\x_2$ & Tuggeranong \\ \hline $\x_3$ & Sydney \\ \hline $\x_4$ & Penrith \\ \hline $\x_5$ & Wollongong \\ \hline $\x_6$ & Melbourne \\ \hline $\x_7$ & Ballarat \\ \hline $\x_8$ & Albury-Wodonga \\ \hline $\x_{9}$ & Bendigo \\ \hline $\x_{10}$ & Brisbane \\ \hline $\x_{11}$ & Cairns \\ \hline $\x_{12}$ & Townsville \\ \hline $\x_{13}$ & Gold Coast \\ \hline $\x_{14}$ & Adelaide \\ \hline $\x_{15}$ & Mount Gambier \\ \hline $\x_{16}$ & Renmark \\ \hline $\x_{17}$ & Port Lincoln \\ \hline \end{tabular} \begin{tabular}{|c|c|} \hline Entry & Location \\ \hline $\x_{18}$ & Perth \\ \hline $\x_{19}$ & Kalgoorlie-Boulder \\ \hline $\x_{20}$ & Broome \\ \hline $\x_{21}$ & Hobart \\ \hline $\x_{22}$ & Launceston \\ \hline $\x_{23}$ & Devonport \\ \hline $\x_{24}$ & Darwin \\ \hline $\x_{25}$ & Alice Springs \\ \hline $\x_{26}$ & Tennant Creek \\ \hline $\x_{27}$ & Casey \\ \hline $\x_{28}$ & Davis \\ \hline $\x_{29}$ & Mawson \\ \hline $\x_{30}$ & Macquarie Island \\ \hline $\x_{31}$ & Christmas Island \\ \hline $\x_{32}$ & Cocos Island \\ \hline $\x_{33}$ & Norfolk Island \\ \hline $\x_{34}$ & Howe Island \\ \hline \end{tabular} \caption{\large\small Distribution of entries of signal ${\bf \x}$ and locations in Australia.} \label{table1} \end{table} Suppose $\omega\in\Omega$ is associated with time $t_\omega\in[0, 24]$ of the temperature measurement. Then $\x_j(\omega)$, for $j=1,\ldots,m$, is a temperature in the $j$th location at time $t_\omega$. The values of the minimum and maximum daily temperature, and the temperature at 9am and 3pm, in $m=34$ specific locations of Australia, for each day in 2016, are provided\footnote{There were 366 days in 2016. There are four values of temperature per day. Thus, we have 1464 temperature values for 2016. From a statistical point of view, the temperature measurements should be provided in more times of a day but such data are not available for us.} by the Bureau of Meteorology of the Australian Government \cite{australia_temp}. In particular, the distribution of the maximum daily temperature in 2016 in all 34 locations in Australia is diagrammatically represented in Fig. \ref{fig3}. Let $t_{min}$ and $t_{max}$ denote times when minimal and maximum temperature occur. We denote by $\omega_{t_{min}}$, $\omega_{t_{max}}$, $\omega_{9{am}}$ and $\omega_{3{pm}}$ outcomes associated with times $t_{min}$, $t_{max}$, 9{am} and 3{pm}, respectively. Further, for $j=1,\ldots,m$, we denote by $\x_{j, (date)}(\omega)$ a temperature in the $j$-th location at time $t_\omega$ on the date labeled as `date'. For example, on $07/07/2016$, the corresponding temperature values in Ballarat are $\x_{7, (07/07/2016)}(\omega_{t_{min}}) = 7.4,$ $\x_{7, (07/07/2016)}(\omega_{9 {am}}) = 8.1$, $\x_{7, (07/07/2016)}(\omega_{3{pm}}) = 9.2,$ $\x_{7, (07/07/2016)}(\omega_{t_{max}}) = 9.5.$ Let ${\bf y}=A{\bf x}+\bxi$ where $A\in\mathbb{R}^{m\times m}$ is an arbitrary matrix with uniformly distributed random entries and $\bxi\in L^2(\Omega,\mathbb{R}^{m})$ is white noise, i.e. $E_{\xi \xi} = \sigma^2 I$. Further, let $\w\in L^2(\Omega,\mathbb{R}^{\ell})$ and $\h\in L^2(\Omega,\mathbb{R}^{\eta})$ be Gaussian random vectors used in the three-term PCA given by (\ref{sjk49}), (\ref{wn202}). It is assumed that noise $\bxi$ is uncorrelated with ${\bf x}$, $\w$ and ${\bf h}$. Covariance matrices are represented in terms of samples. For example, $E_{xw} = \frac{1}{p}X W^T$ and $E_{hh} = \frac{1}{p} H H^T$ where $X\in\mathbb{R}^{m\times p}$, $W\in\mathbb{R}^{\ell\times p}$ and $H\in\mathbb{R}^{\eta\times p}$ are samples of ${\bf x}$, ${\bf w}$ and $\h$, and $p$ is the number of samples. Other covariance matrices are represented similarly. In this example, we consider four specific samples of $\x$ as follows. Matrices $X=X_{9am}\in\mathbb{R}^{m\times 366}$ and $X=X_{3pm}\in\mathbb{R}^{m\times 366}$ represent the temperature taken each day in 2016 at 9am in all $m$ locations. Entries of matrices $X_{max}\in\mathbb{R}^{m\times 366}$ and $X_{min}\in\mathbb{R}^{m\times 366}$ are values of the maximum and minimum temperature, respectively, for each day in 2016 in all $m$ locations. The database was taken from the Bureau of Meteorology website of Australian Government \cite{australia_temp}. Matrices $W$ and $H$ were created by MATLAB command {\tt rand(m,p)}. \begin{figure}[h] \centering \includegraphics[scale=0.65]{temperature_Australia_max1.eps}\\ \caption{Values of maximal temperature in 34 locations of Australia in 2016} \label{fig3} \end{figure} We consider eight different cases of simulations. In each case, matrix $X$ is chosen either as one of matrices $X_{9am}$, $X_{3pm}$, $X_{min}$, $X_{max}$, or their combinations as follows: \begin{table}[h] \centering \begin{tabular}{|c|c|c|c|c|c|} \cline{2-6} \multicolumn{1}{c|}{} & {\small Case 1} & {\small Case 2} & {\small Case 3} & {\small Case 4} & {\small Case 5} \\ \hline $X$ & $X_{min}$ & $X_{9am}$ & $X_{3pm}$ & $X_{max}$ & $[X_{9am}, X_{3pm}]$ \\ \hline $p$ & $366$ & $366$ & $366$ & $366$ & $732$ \\ \hline \end{tabular} \vspace{0.7cm} \begin{tabular}{|c|c|c|c|} \cline{2-4} \multicolumn{1}{c|}{}& {\small Case 6} & {\small Case 7} & {\small Case 8} \\ \hline $X$ & $[X_{min}, X_{max}]$ & $[X_{min}, X_{9am}, X_{3pm}]$ & $[X_{min}, X_{9am}, X_{3pm}, X_{max}]$ \\ \hline $p$ & $732$ & $1098$ & $1464$ \\ \hline \end{tabular} \end{table} For each case, the diagrams of the error associated with the GBT1, GBT2 and three-terms PCA in form (\ref{sjk49})-(\ref{wn202}), for $m=\ell = 34$, $k=17$ and $\sigma=1$, versus the dimension $\eta=0, 1, \ldots, 500$ of vector ${\bf h}$ are shown in Fig. \ref{fig4}. \begin{figure}[h!] \centering \begin{tabular}{cc} \includegraphics[scale=0.44]{fig1_pca.eps} & \includegraphics[scale=0.44]{fig2_pca.eps}\\ {\small (a) Case 1: $X=X_{min}$} & {\small (b) Case 2: $X=X_{9am}$} \\ \includegraphics[scale=0.44]{fig3_pca.eps} & \includegraphics[scale=0.44]{fig4_pca.eps}\\ {\small (c) Case 3: $X=X_{3pm}$} & {\small (d) Case 4: $X=X_{max}$} \\ \includegraphics[scale=0.44]{fig5_pca.eps} & \includegraphics[scale=0.44]{fig6_pca.eps}\\ {\small (e) Case 5: $X=[X_{9am}\;X_{3pm}]$} & {\small (f) Case 6: $X=[X_{min}\;X_{max}]$} \\ \includegraphics[scale=0.44]{fig7_pca.eps} & \includegraphics[scale=0.44]{fig8_pca.eps}\\ {\small (g) Case 7: $X=[X_{min}\;X_{9am}\;X_{3pm}]$} & {\small (h) Case 8: $X=[X_{min\;}X_{9AM}\;X_{3PM}\;X_{max}]$}\\ \end{tabular} \caption{Errors associated with the GBT1, GBT2 and three-terms PCA versus dimension $\eta$ of $H$.} \label{fig4} \end{figure} It follows from the diagrams for all cases represented in Fig. \ref{fig4}, that the error associated with the three-term PCA decreases as $\eta$ increases. This is the numerical illustration of Theorem \ref{w791n} and the Case 3 considered in Section \ref{vnb01m}. In particular, in Figs. \ref{fig4} (a)-(d), for $\eta= 335,\ldots, 500$, the error associated with the three-term PCA coincides with that of the GBT1 applied to the case when $\y = \x$, i.e.. with that of PCA applied to the data {\sf\em without any noise.} Further, Fig. \ref{fig5} illustrates the following observation. For $\sigma\in [0, 2]$ and $\eta\in [0, 300]$, the behavior of the error associated with the three-term PCA is similar: the increase in $\eta$ implies the decrease in the error. Interestingly, for $\eta\in [300, 500]$, the error remains constantly small regardless of the value of $\sigma$. Similar to the above, for $\eta\in [300, 500]$, the error associated with the three-term PCA coincides with that that of PCA applied to the data {\sf\em without any noise.} \begin{figure}[h!] \centering \includegraphics[scale=0.6]{surface_example_new.eps}\\ \caption{Diagrams of errors associated with the three-terms PCA versus dimension $\eta$ of $\h$ and values of $\sigma$ of $E_{\xi\xi}$.} \label{fig5} \end{figure} \end{example} \subsection{ Case 4. Pure filtering}\label{} One more special case of the three-term PCA is as follows. Consider transform $\ttt_1$ defined by \begin{eqnarray}\label{sj92} \ttt_1(\y,\w) = A_0\y + A_1 \f(\y, \w), \end{eqnarray} where $A_0\in\rt^{m\times n}$ and $A_1\in\rt^{m\times \ell}$ are full rank matrices. Optimal $A_0$ and $A_1$ are determined from the solution of the following problem: Given $E_{xy}$, $E_{yy}$, $E_{yw}$ are $E_{ww}$, find full rank $A_0$ and $A_1$ that solve \begin{eqnarray}\label{zbn91} \min_{{A_0, A_1}} \|\x - [A_0\y + A_1 \f(\y, \w)]\|^2_\Omega. \end{eqnarray} In other words, $\ttt_1$ is a pure filter, with no principal component determination. As before, we write $\s=\f(\y, \w)=\w- E_{wy} E_{yy}^\dag \y$. We call $\ttt_1$ the three-term filter (TTF). \begin{theorem}\label{1nm0} Minimal norm solution to problem (\ref{zbn91}) is given by \begin{eqnarray}\label{68bn1} A_0=E_{x y} E_{yy}^\dag \qa A_1=E_{x s} E_{ss}^\dag. \end{eqnarray} The associated error is represented by \begin{eqnarray}\label{xmabn1} &&\hspace*{-10mm}\min_{A_0, A_1} \|\x - [A_0 \y + A_1 \s]\|^2_\Omega\nonumber\\ && \hspace*{-3mm}= \|E_{xx}^{1/2}\|^2 - \|[E_{xy}{E_{yy}^{1/2}}^\dag\|^{2} - \|E_{xs}{E_{ss}^{1/2}}^\dag ]\|^{2}. \end{eqnarray} \end{theorem} \begin{proof} Optimal full rank $A_0$ and $A_1$ given by (\ref{68bn1}) follow from (\ref{xm02}) where ${E_{zz}^\dag}^{1/2}$ is represented by ${E_{zz}^\dag}^{1/2} = \left[ \begin{array}{cc} {E_{yy}^\dag}^{1/2} & \oo\\ \oo & {E_{ss}^\dag}^{1/2} \end{array} \right]$ and $[E_{xz}{E_{zz}^\dag}^{1/2}]_{k}$ should be replaced with $E_{xz}{E_{zz}^\dag}^{1/2}$. Further, for $A=[A_0\hspace*{1mm} A_1]$, \begin{eqnarray}\label{} \|\x - [A_1 \y + A_1 \s]\|^2_\Omega = \|E_{xx}^{1/2}\|^2 - \|E_{xz}{E_{zz}^{1/2}}^\dag\|^{2} + \|E_{xz}{E_{zz}^{1/2}}^\dag - A{E_{zz}^{1/2}}\|^{2}. \end{eqnarray} For $A_0$ and $A_1$ given by (\ref{68bn1}), $A=[E_{x y} E_{yy}^\dag \hspace*{1mm}E_{x s} E_{ss}^\dag]=E_{xz}E_{zz}^\dag$. Therefore, \begin{eqnarray*} \hspace*{-17mm}\min_{A_1, A_1} \|\x - [A_1 \y + A_1 \s]\|^2_\Omega \hspace*{-5mm}& & =\|E_{xx}^{1/2}\|^2 - \|E_{xz}{E_{zz}^{1/2}}^\dag\|^{2} \\ & &\hspace*{10mm}+ \|E_{xz}{E_{zz}^{1/2}}^\dag - E_{xz}E_{zz}^\dag {E_{zz}^{1/2}}\|^{2}\\ && \hspace*{20mm} =\|E_{xx}^{1/2}\|^2 - \|E_{xz}{E_{zz}^{1/2}}^\dag\|^{2} \end{eqnarray*} because $E_{zz}^\dag {E_{zz}^{1/2}} = {E_{zz}^{1/2}}^\dag$ {\em \cite[p. 313]{torbook2007}}. Then (\ref{xmabn1}) follows.\hfill$\blacksquare$ \end{proof} The accuracy of the optimal TTF $\ttt_1$ is better than that of the optimal linear filter $\widetilde{F}=A_0= E_{x y} E_{yy}^\dag$ \cite{torbook2007}. More specifically, the following is true. \begin{theorem}\label{nm012} The error associated with the optimal TTF $\ttt_1$ is less than that of the optimal linear filter $\widetilde{F}=A_1$ by $\|E_{xs}{E_{ss}^{1/2}}^\dag ]\|^{2}$, i.e., \begin{eqnarray}\label{wom9} \min_{A_0, A_1} \|\x - [A_0 \y + A_1 \f(\y, \w)]\|^2_\Omega = \min_{A_0} \|\x - A_0 \y \|^2 - \|E_{xs}{E_{ss}^{1/2}}^\dag ]\|^{2}_\Omega. \end{eqnarray} \end{theorem} \begin{proof} The proof follows directly from (\ref{xmabn1}). \hfill$\blacksquare$ \end{proof} \section{Advantages of three-term PCA (continued)}\label{x78kl} \subsection{Increase in accuracy compared to that of GBT2 \cite{tor843} and GKLT}\label{58b29} The three-term PCA represented by (\ref{sjk92}) and (\ref{sjk49}) has more parameters to optimize than those in the GBT2 (\ref{bnm11}) and GKLT (\ref{qmiw8}), i.e., it has more degrees of freedom to control the performance. Indeed, in the three-term PCA, the dimension of $\w$-injection and $\h$-injection are $\ell$ and $\eta$, and they can be varied while in the GBT2, the dimension of auxiliary vector $\vv$ is $n$ and it is fixed. In the GKLT dimension of vector $\y^2$ is also fixed. Thus, in the three-term PCA, $\ell$ and $\eta$ represent the additional degrees of freedom. By Theorem \ref{w791n}, the increase in $\eta$ implies the improvement in the accuracy of the three-term PCA. Thus, unlike the GBT2, the performance of the three-term PCA is improved because of the increase in the dimension of $\h$-injection. \subsection{Improvement in the associated numerical load}\label{cm9vn} In a number of applied problems, dimensions $m,n$ of associated covariance matrices are large. For instance, in the DNA array analysis \cite{Alter11828,ziyang18}, $m={\it O}(10^4)$. In this case, the associated numerical load needed to compute the covariance matrices increases significantly. Therefore, a method which requires a lower associated numerical load is, of course, preferable. Here, we wish to illustrate the computational advantage of the three-term PCA represented by (\ref{sjk92}), (\ref{smi91}) and (\ref{294b}) compared to that of the GBT2 in (\ref{bnm11}) and the GKLT \cite{924074}. In both methods, a pseudo-inverse matrix is evaluated by the SVD. The computational load of the three-term PCA (abbreviated as $C_{PCA3}$) consists of the matrix products in (\ref{294b}), and computation of SVDs for $E_{yy}^\dag\in\rt^{n\times n}$, $E_{ss}^\dag\in\rt^{\ell\times \ell}$ and $G_z\in\rt^{m\times m}$. Recall that $E_{zz}^\dag = \left[ \begin{array}{cc} E_{yy}^\dag & \oo\\ \oo & E_{ss}^\dag \end{array} \right]$. The GBT2 computational load ($C_{GBT2}$) consists of computation of the matrix products in (\ref{ac11}) and the SVD for $E_{qq}^\dag\in\rt^{2n\times 2n}$. The computational load of the GKLT ($C_{GKLT}$) contains computation of the matrix products given in \cite{924074}, and computation of the SVDs for $2n\times 2n$ and $m\times 2n$ matrices. Importantly, the dimensions of matrices in the three-term PCA are less than those in the GBT2 and GKLT. For example, the dimension of $E_{yy}$ is twice less than that of $E_{qq}$. This circumstance implies the decrease in the computational load of the three-term PCA compared to that in the GBT2 and GKLT. Indeed, the product of $m\times n$ and $n\times p$ matrices requires approximately $2mnp$ flops, for large $n$. The Golub-Reinsch SVD method (as given in \cite{golub1996}, p. 254) requires $4mn^2 + 8n^3$ flops to compute the pseudo-inverse for a $m\times n$ matrix\footnote{The Golub-Reinsch SVD method appears to be more effective than other related methods considered in \cite{golub1996}.}. As a result, for $m=n=\ell$, \begin{eqnarray}\label{29cn3} C_{PCA3} = 52m^3 + 2m^2(k+1) \end{eqnarray} while \begin{eqnarray}\label{88cn3} C_{GBT2} = 140m^3 + 2m^2(k+2) \mbox{ and } C_{GKLT} = 240m^3 + 4m^2(k+1)+mk . \end{eqnarray} That is, for large $m$ and $n$, $C_{PCA3}$ is about $37\%$ of $C_{GBT2}$ and $22\%$ of $C_{GKLT}$ . Thus, the three-term PCA may provide a better associated accuracy than that of the GBT2 and GKLT (see Section \ref{1n8an}, Example \ref{m2b9} and Section \ref{58b29}) under the computational load which, for large $m, n$, is about one third of $C_{GBT2}$ and a quarter of $C_{GKLT}$. This observation is illustrated by the following numerical example. \begin{example}\label{nm498} Let ${\bf y}=A{\bf x}+\xi$ where ${\bf x}\in L^2(\Omega,\mathbb{R}^{m})$ is a uniformly distributed random vector, $\xi\in L^2(\Omega,\mathbb{R}^{m})$ is a Gaussian random vector with variance one and $A\in\mathbb{R}^{m\times m}$ is a matrix with normally distributed random entries. We choose ${\bf w}\in L^2(\Omega,\mathbb{R}^{\ell})$ as an uniformly distributed random vector. Covariance matrices $E_{xx}$, $E_{ww}$ and $E_{\xi\xi}$ are represented by $E_{yy}=\frac{1}{s} YY^T,\quad E_{ww}=\frac{1}{s}WW^T, \quad E_{\xi\xi}=\sigma^2 I,$ where $Y\in\mathbb{R}^{m\times p}$ and $W\in\mathbb{R}^{m\times p}$ are corresponding sample matrices, $p$ is a number of samples, and $\sigma=1$. Suppose only samples of $\y$ and $\w$ are available, and for simplicity let us assume that matrix $A$ is invertible. Then, in particular, $ E_{xx} = A^{-1}(E_{yy} - E_{\xi\xi})A^{-T}\qa E_{xy}=E_{xx} A^T. $ \begin{figure}[h!] \centering \includegraphics[scale=0.60]{TIME_PAPER_3.eps}\\ \caption{Example \ref{nm498}: Time versus matrix dimension $m$ used to execute the three-term PCA (blue line), GBT2 (red line) and GKLT (green line). } \label{fig2} \end{figure} In Fig. \ref{fig2}, for a randomly chosen $A$, and $m=\ell$ and $p=3m$, typical diagrams of time (in sec.) used to execute the three-term PCA in form (\ref{sjk92}) and (\ref{294b}), GBT2 (\ref{bnm11})-(\ref{byfx}) and GKLT \cite{924074} versus dimension $m$ are represented. The diagrams in Fig. \ref{fig2} confirm the observation made before this example, i.e., for large $m$, $C_{PCA3}$ is significantly less than $C_{GBT2}$ and $C_{GKLT}$ (see (\ref{29cn3}) and (\ref{88cn3}), respectively). \end{example} \section{Final discussion}\label{nbm198} We have developed the extension of PCA called the three-term PCA. The three-term PCA is presented in two forms considered in Sections \ref{w0an}, \ref{det1}, and \ref{xvb8an}. The associated advantages have been detailed in Sections \ref{x78an} and \ref{x78kl}. We would like to highlight the following observation. The proposed three-term PCA is applied to observed data represented by random vector $\y$. Here, $\y$ is a noisy version of original data $\x$. It is shown that in this case, the error associated with the three-term PCA, $\varepsilon_{m,n,\ell+\eta} (S_0, S_1) $, is less than that of the known generalizations of PCA, i.e. the GBT1, GKLT and GBT2 (see Section \ref{1n8an}). At the same time, in the ideal case of the observed data {\em without any noise}, i.e. when $\y=\x$, the three-term PCA coincides with the GBT1 (with $\y=\x$ in the GBT1 as well) which is a generalization of PCA for the case of singular data. Its associated error is minimal among all transforms of the same rank and cannot be improved. Let us denote this error by $\varepsilon_{(y=x)} $. Example \ref{m2b9} above has discovered an important and quite unanticipated feature of the proposed technique as follows. As dimension $\eta$ of $\h$-injection increases, the error $\varepsilon_{m,n,\ell+\eta} (S_0, S_1) $ decreases up to $\varepsilon_{(y=x)} $. This implies a conjecture that this is true in general, i.e. $ \lim_{\eta \rightarrow \infty} \varepsilon_{m,n,\ell+\eta} (S_0, S_1) = \varepsilon_{(y=x)}. $ We intend to develop a justification of this observation. \bibliographystyle{plain}
{'timestamp': '2021-11-05T01:22:18', 'yymm': '2111', 'arxiv_id': '2111.03040', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03040'}
arxiv
\section{Introduction} \vspace{-8pt} Modern society has refined the condition of solitude to the point where countless seniors, marginalized because of their age, have magically disappeared: left to their own devices, these individuals fade from social life and essentially live in a parallel world. The COVID-19 crisis and resulting lockdowns have both entrenched this phenomenon and helped to reveal how widespread it really is. Can artificial intelligence (AI) help to reconnect generations by making them part of a transgenerational art experience? At the crossroads of laughter—an act of communication between two individuals—and artificial intelligence—a purely functional entity—can we rediscover our humanity? \vspace{-8pt} \paragraph{An interactive experience.} The end-goal of this project is to connect people via an interactive web experience driven by synthetic laughter. Using our models, we will explore the phenomenon of empathy triggered by the sound of laughter, the relationship between individual memory and laughter, and how the sound of laughter evolves over a lifetime. \vspace{-8pt} \paragraph{Laughter generation for advancing audio synthesis research.} With stunning advancements in image synthesis~\cite{karras2017progressive, karras2019style, karras2020analyzing, karnewar2020msg}, Generative Adversarial Networks (GANs) ~\cite{goodfellow2014generative} have gained the attention of researchers in the field of audio synthesis~\cite{donahue2018adversarial, engel2019gansynth, kumar2019melgan, binkowski2019high}. Synthesizing audio opens new doors for musicians and artists and enables them to expand their repertoire of expression~\cite{donahue2018adversarial}. Despite significant progress by the ML community on methods for audio synthesis, there have been only a few attempts in the topic of laughter synthesis~\cite{mancini2013laugh}, and none leveraging modern approaches such as GANs. Compared to speech, laughter is made challenging by its many context-dependent attributes, such as emotions~\cite{schroder2001emotional}, age, and gender. Moreover, compared to well-studied topics like speech synthesis, there are not established evaluation methods for synthesized laughter. Thus laughter synthesis, has the potential to become a standard benchmark in unconditional audio synthesis. \vspace{-8pt} \paragraph{Related work.} Previous work in the field of laughter generation involves~\cite{mori2019conversational} the use of oscillatory system~\cite{sundaram2007automatic}, formant synthesis~\cite{oh2013lolol}, articulatory speech synthesis~\cite{lasarcyk2007imitating}, and hidden Markov models (HMM)~\cite{urbain2014arousal}. Recently, some researchers have also used deep learning~\cite{mori2019conversational, tits2020laughter} methods for laughter synthesis. GANs are advantageous in learning of a compact latent space allowing for interpolation, mixing, and style transfer as well as emotional analysis. In this paper, we propose to use GANs for the purpose of unconditional laughter generation and manipulation (LaughGANter). Our aim is to enable a unique interactive art experience that surprises and connects through the primordial intimacy of our laughter interacting and juxtaposed with others. \vspace{-8pt} \section{Methodology} \vspace{-8pt} We adapt Multi-Scale Gradient GAN (MSG-GAN)~\cite{karnewar2020msg} for laughter synthesis. Among other popular image synthesis methods, like DCGAN~\cite{radford2015unsupervised}, ProgressiveGAN~\cite{karras2017progressive}, and StyleGAN~\cite{karras2019style}, LaughGANter employs multi-scale gradients on a DCGAN architecture to address the training instability prevalent in GANs. Progressive growing of network resolutions is avoided to limit the hyperparameters to be tuned (e.g. training schedule, learning rates for each resolution, etc) while the multi-scale discriminator penalizes intermediate and final layer outputs of the generator. We refer the reader to~\cite{karnewar2020msg} for an in-depth study of the MSG-GAN architecture. Concisely, the generator ($G$) samples a random vector $z$ from a normal distribution and outputs $x=G(z)$. The generated samples are fed into the discriminator ($D$), along with real samples, in order to measure the divergence. We perform \textit{pixel normalization} after every layer in $G$, and employ the \textit{Relativistic Average Hinge} loss~\cite{jolicoeur2018relativistic} in $D$. Moreover, inspired by~\cite{oord2016wavenet, odena2016deconvolution}, we explored the impact of \textit{induced receptive field expansion}, adding residual blocks with dilations after each upsampling layer in $G$, which exponentially increases the model's receptive field and can lead to better long range correlation in audio data. \vspace{-8pt} \paragraph{Categorical Conditional Generation.} A more directed data generation process is employed through a conditional adaptation of MSG-GAN ~\cite{mirza2014conditional}, facilitating the laughter representation learning given additional context beyond unlabeled laughter (e.g. gender, age, humor style, etc). Here, categorical information augments the latent noise vector in $G$, and to each of the multi-scale vectors within $D$, through a concatenation with an embedding of context information. \vspace{-10pt} \begin{figure}[t] \label{fig:spec} \centering \begin{subfigure}[b]{0.32\textwidth} \centering \includegraphics[width=\textwidth]{spec8000.png} \vspace{.5cm} \caption{\small Generated Mel spectrogram} \end{subfigure} \hspace{2pt} \begin{subfigure}[b]{0.32\textwidth} \includegraphics[width=\textwidth]{real1.png} \vspace{.5cm} \caption{ \small Real Mel spectrogram} \end{subfigure} \hspace{2pt} \begin{subfigure}[b]{0.32\textwidth} \centering \includegraphics[width=\textwidth]{FID-paper.pdf} \caption{\small FID score for LaughGANter} \end{subfigure} \caption{(a)-(b) Log-magnitude spectrograms for real and generated samples show similar features on qualitative analysis and (c) FID score for LaughGANter decreases during training, as the diversity of the generated samples approaches that of the training data distribution.} \label{fig:results} \end{figure} \section{Experiments} \vspace{-8pt} \paragraph{Setup.} Our model is implemented in PyTorch. We use a laughter dataset containing 2145 laughter samples collected by the National Film Board of Canada. Samples are 1-8s long (22.05kHz mono), and were collected (and labeled) from subjects with different ages and genders (55\% male, 45\% female; 93\% adult, 6\% child, 1\% teen). The audio data is augmented using a random combination of additive noise, shifting, and changing pitch and duration (using \texttt{pyrubberband}). Then, this data is converted to Mel spectograms and fed into the model. In addition to qualitative evaluation, i.e., listening to generated samples, we have used Fréchet inception distance (FID)~\cite{heusel2017gans} to assess the diversity of the generated samples compared to the training dataset. Instead of using Inception features used in the original FID score, we use features from a classifier (gender and age group) trained on the spectrograms of our laughter dataset. \vspace{-8pt} \clearpage
{'timestamp': '2021-11-08T02:04:29', 'yymm': '2111', 'arxiv_id': '2111.03146', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03146'}
arxiv
\section{Introduction} To date, various neural networks have appeared, and these networks are being used in various fields (classification, generation, detection, etc..). However, there are tasks that humans can do, but neural network models can't. Human's representative ability is imagination and creating something new. In this study, we designed an imagine networks model based on artificial association networks. It was designed by sequencing the structures imagined by humans. several abilities are needed to imagine. (1) The first is recognition. If the information is not recognized, it can't be utilized. We need to recognize which object is what. We learn this through classification or clustering. (2) The second is Deduction. We create a proposition and combine the propositions to create a compound proposition and solve our problems through the relationship between the main object and the other objects. And we need to learn what the results will be if we combine the objects in principle. (3) The third is memory. Humans have a memory input device called the hippocampus and it stores information in the brain. And the memory device can take out the desired information and use it in the deduction process. It is possible to recall information based on experience without input, similar to when we close our eyes and cover ears. (4) The fourth is that the choosing process which is to get the optimal reward. This selector consists of a reinforcement learning structure such as Q-learning\cite{watkins1992q}, and it is known that reinforcement learning is a structure similar to the human brain. And if we choose another object by reinforcement models, it should be something better. (5) the last part is the discriminator. This model is a discriminator of whether the generated sample is a target sample for us to obtain. The discriminator learns the conditions to be the target sample and determines whether the conditions are satisfied every step. It consists of a model like GAN\cite{goodfellow2020generative}, and it determines whether the sample generated is what we want. We will understand the principle relationship between the object and the new object. And this network is characterized by being a data-driven network that uses a association tree data structure. Therefore, the generated data sample may be input to the association model again and used as a model for generating hierarchical and relational information. We experimented in a reinforcement learning environment to learn this. And similar to simulating in our heads, we generated a sample that performs simulation in a network. \section{Related works} \label{sec:related_works} \paragraph{Artificial Association Networks \cite{kim2021association}} This study is the first study of artificial association networks(AANs). In this study, it is possible to learn various datasets simultaneously, and this paper introduces various sensory organs and the association area where information is integrated. instead of using a fixed sequence layer, the network learns according to the tree structure using a data structure called an association tree. The data structure defined $\mathbf{AN} = \{x, t, \mathbf{A}_c, \mathbf{C}\}$, And propagation method is conducted using recursive convolution called DFC and DFD. \paragraph{Associational Deductive Networks \cite{kim2021deductive}} This study is a model for the role of the frontal lobe and is a study to utilize information generally transmitted from the association area. Representatively, it is designed to be responsible for the ability to deduce and think. This model uses the result of the previous proposition as input to the next proposition to combine various principles. \paragraph{Associational Memory Networks \cite{kim2021memory}} This model is designed to store root vectors. In this study, short-term memory is used to solve the class-imbalance problem, and long-term uses it to create distributions of objects. \paragraph{Q-learning \cite{watkins1992q}} This agent learns what information to take out of memory or what action to perform for the current state to get the optimal reward. If the space is continuous, models such as DQN\cite{mnih2013playing} and SAC\cite{haarnoja2018soft} could be used. \paragraph{GAN \cite{goodfellow2020generative}} The main concept is that the generator generates a sample and the discriminator determines whether the sample is the desired sample. \section{Imagine Networks} \label{sec:imagine} \begin{figure}[h] \centering {\includegraphics[width=0.80\textwidth]{figure/imaginenet.png}} \caption{ Ideal Imagine Modeling } \label{fig:long-term} \vspace{-10px} \end{figure} Imagine Networks is created by combining various neural network models. This structure can be seen as the ability to perform in the frontal lobe. In addition, the association tree generated in the frontal lobe learns relational information and hierarchical information, and The generated association tree uses it again for an association model. \subsection{Eureka! Learning} \label{sec:imagine} \paragraph{Recognition} This process is for extracting the feature vector of the object. Classification or Clustering tasks are representative recognition learning processes in which each object can produce different feature vectors. \paragraph{Memorization} This process is to use the information learned in the past by recalling memories without any input. Short-term memory is stored for each class of objects, and each class has a distribution for a generation. \paragraph{Deduction} Deduction performs a prediction task on the proposition result that appears when the objects are combined. This is like learning a simple proposition. This step can be replaced by a style transfer model etc. \paragraph{Reinforcement learning} Q-learning plays the role of using currently recognized information as state and selecting it to perform deduction with other information. And through deduction, information is combined, and optimal compensation is obtained. \paragraph{Discriminator} The discriminator plays a role in determining whether the currently recognized information is what I want and instructing the q-learning model to stop when the desired information comes out. \section{Experimental results} \label{sec:result} \begin{figure}[h] \centering {\includegraphics[width=0.90\textwidth]{figure/imagine-learning.png}} \caption{ Eureka Training } \label{fig:recognition-task} \vspace{-10px} \end{figure} \subsection{Imagination in A Reinforcement Learning Environment} Let's apply the above description to a reinforcement learning environment. First, We created a queue for each state in short-term memory, and samples from the environment are stored in short-term memory(state number(label), screen, action, reward, next state number(label), next screen, next action, done). In addition, sampling was performed as much as batch-size in short-term memory, and the samples were trained to recognition, memory, deduction, discriminator, and agent model. \subsubsection{How to train Imagine Networks} \paragraph{Recognition} In the recognition process, the current screen is input and the number of the current state is recognized. Recognition in this experiment means being aware of the current state. Since the state in this experiment is a discrete space, we numbered this state and labeled it by state, and supervised learning was performed to preset the state number by inputting the screen image of the state. \paragraph{Memorization} In the memorization process, the root vector shown is stored in memory networks, and the distribution is learned together with the decoder. The memory network learns that generates a screen of each state. Therefore, we stored image information generated from environments in short-term memory and learned the images in long-term memory. Each state's information is stored as a distribution. We can generate screen information by entering the number of the desired state. \paragraph{Reinforcement learning} In the agent process, the root vector means current state information. And state information is discrete space. Therefore, we can generate q-table for each state. And encode the optimal action to be performed in the current state and use it as an input to the deductive model. In the future, we can change this process to perform an action on "which sample should be taken out of memory". Reinforcement learning in this experiment has randomness and serves as a role in generating data in the environment. A selector selects an action to move by finding the shortest path. \paragraph{Deduction} In the deduction process, Now, there is a root vector of the current state and action information to be performed, and there is the next screen information that appears when the action is performed. The next screen information becomes the next root vector to learn the state + action = next state relationship with a deductive model. In this experiment, Deduction receives the current state information and action information as input and predicts the root vector containing the next state information. It is similar to receiving action and performing a step in the environment, and the next state is generated. \paragraph{Discriminator} In the discriminator process, Learn with a network that classifies whether the current state is an end state or not. Discriminator in this experiment means whether the current state is the final target endpoint whenever the agent acts. Therefore, Discriminator was learned using done (whether the game was over or not). \subsubsection{Imagine Result} \begin{figure}[h] \centering {\includegraphics[width=0.80\textwidth]{figure/imagine-result.png}} \caption{ A Generated Sample } \label{fig:long-term} \vspace{-10px} \end{figure} The learned network no longer generates data from the environment, but the following simulations are possible. this figure is a generated sample and there are four characteristics. (image generation by state number and root vectors (memory), Continuous scenes(deduction), the shortest path(reinforcement learning), When is the end state?(Discriminator)) \paragraph{Discuss : How do we think creatively? } \begin{equation} G \oplus G \to G^{c} \cap G' \label{eqn:grouptheory1} \end{equation} Creative samples appear when they are moved to other set of elements without being closed to any operation of the elements. If the element move from the current set $G$ to $G^{c}$, It moves away from the existing knowledge and reaches a different set space($G'$) and creates something new. And since it is a sample produced by deduction, it is theoretically valid. I think we may create something new by designing the conditional expression, learning the discriminator, and generating a sample. \section{Conclusion} We are designing an agent model that behaves similarly to the human brain by combining various networks developed to date. The purpose of this study is as follows. "Let’s create a brain that thinks like humans in a similar environment to human life". This paper is part of a series. The next paper is ~. \bibliographystyle{unsrt}
{'timestamp': '2021-11-18T02:25:09', 'yymm': '2111', 'arxiv_id': '2111.03048', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03048'}
arxiv
\section{Selective review of post-census method} Internationally and historically speaking, one can distinguish three main approaches when it comes to the provision of post-census population statistics: Demographic Balancing Equation, Central Population Register and Adjusted Population Dataset. Some selected examples of each approach are briefly reviewed below. \subsection{Demographic Balancing Equation} The Demographic Balancing Equation (DBE) allows one to update census population statistics, based on vital statistics, available data on internal and external migration, and various group-quarter (GQ) or other special populations (e.g. military personals). \begin{itemize}[leftmargin=4mm] \item In reality the approach is based on administrative data of birth, death, internal migration and GQ or special populations. Nevertheless, for various reasons, longitudinal linkage of relevant data and the base (census) population at the individual level is not the case in practice. The basis of production is a yearly constructed population hypercube rather than, say, a one-number census-like population dataset. \item Survey data are often required for the external migration component. Indirect residual estimation methods are sometimes used for certain migration groups and special populations. In the UK context, it may be possible to make greater use of the continuous coverage survey under the DBE approach, as will be commented later. \end{itemize} \subsubsection{Example of USA} In the USA, the Population Estimates Program (PEP) uses the DBE approach, supplemented by the American Community Survey (ACS) for foreign-born immigration. The PEP produces population estimates at three levels: national, state and county, by characteristics of sex, age, race and Hispanic origin; see e.g. CBS (2019). At the first stage, the national characteristics, state total, and county total estimates are created. At the second stage, estimates of states and counties by characteristics are obtained, by raking of the lower-level DBE-estimates to the controlled estimates at a higher level. Linear interpolation between two successive yearly estimates generates the seemingly continuous Population Clock, which can be viewed at \url{http://www.census.gov/popclock/}. The DBE-estimates are essentially based on administrative data, except for foreign-born immigration, which uses the ACS. In particular, for state and county total estimates, one calculates county-to-county net domestic migration based on four sources: Internal Revenue Service tax return data for ages 0-64, Medicare enrollment data from Centers of Medicare and Medicaid Services for ages 65+, Social Security Administration's Numerical Identification File for all ages, and change in the GQ population. The ACS uses an address frame, and aims primarily at producing attribute statistics similar to the census long-form format. Two ACS weights are computed for households and persons, respectively. The household unit weight is produced first, based on sampling design inclusion probabilities reweighted for nonresponse and then raked to county/group of county level totals; person weight is then produced by raking. See e.g. CBS (2014). \subsubsection{Comments on UK} The DBE approach is used to produce the mid year population estimates (MYE) in the UK; see e.g. ONS (2018). The key dissemination levels are national and local authority. Internal migration data are derived from administrative sources. For international migration one makes use of the International Passenger Survey, while administrative sources are used to distribute immigrants to each local authority. One anticipates the relevant administrative sources to be enhanced in the coming years. The most relevant sources include the Benefits and Income data, the Patient Register, Education data at all levels, the Council Tax data, and so on. In particular, updates of home addresses in the Drivers' License database may potentially prove to be an important addition, regarding internal migration. Moreover, Migrant Work Scan data can provide information on all overseas nationals who have registered for and allocated a National Insurance Number. Together with Exit Checks they could be expected to greatly improve the external migration data in future. Going forward, two important questions need to be considered for potential improvements of the estimation of DBE components in the UK context. \begin{itemize}[leftmargin=4mm] \item Can the ability to link individual-level administrative data across sources improve the quality of address or locality information, and extend the range of sources to be used? For instance, in the USA, one splits the non-GQ population into 0-64 and 65+ by age, each with its designated source, which may be simplistic and practical, only if individual linkage is infeasible but not otherwise. \item Can greater use be made of the coverage survey in the DBE approach in the UK, compared to the ACS in the USA? The question is natural, especially provided linkage to the administrative data. But even without linkage, it may be possible to combine area-level administrative and survey migration data, e.g. by means of generalised structure preserving estimation for small area compositions. \end{itemize} \subsection{Central Population Register} In a number of countries that produce register-based census-like population statistics, Central Population Register (CPR) is used for continuous updating of neighbourhood population statistics at very low aggregation levels. A wide range of statistics can be produced with much greater ease and lower cost, including timely population dynamics, detailed migration flows and household statistics that can inform policy makers, researchers, businesses and general public. See e.g. some statistics produced by Statistics Norway at \url{https://www.ssb.no/befolkning/faktaside/befolkningen#blokk-1}. There are two key political and cultural premises of the CPR approach: infrastructure and population concept. The CPR approach is only feasible, given the necessary legal framework, uptake of universal person identification in public services, and adequate time labelling of relevant demographic events and recording in the CPR. It requires also the population to be counted at their \emph{de jure} instead of \emph{de facto} address. The latter poses a key challenge to the relevance of the statistics, in which respect statistical adjustment may still be necessary for certain topics. See e.g. Zhang (2011) and Zhang and Fosen (2018) for a discussion of register-based household statistics. \subsection{Adjusted Population Dataset} In some countries, the CPR does not have the desired accuracy to warrant the CPR approach directly, often due to a lack of updated migration data. Moreover, in countries where CPR does not exist at all, it may still be possible to construct a statistical Population Dataset (PD), based on linkage and integration of relevant administrative registers, which can yield national population counts that are similar to the census population estimates, as it is e.g. the case in the UK (ONS, 2015), New Zealand and Australia. In either case, statistical adjustment is then necessary. Despite nearly all the examples below are based on adjustment of the CPR, we shall refer to this approach as \textit{Adjusted Population Dataset (APD)}, in anticipation of future developments that can enable the approach in those countries that do not have CPR at all. The main issues for adjustment are \emph{erroneous enumeration}, \emph{missing enumeration} and \emph{misplacement} in the PD. Erroneous and missing enumerations causes over- and under-counting at the national level, respectively; whereas misplacement causes inter-locality over- and under-counting simultaneously but does not cause over- or under-counting at the national level. Below we give some examples of the different cases. \subsubsection{APD for misplacement in Israel} The CPR in Israel has only negligible over- and under-counting errors at the national level. The Israeli Integrated Census 2008 was conducted chiefly to adjust for misplacement in the CPR. See e.g. Nirel and Glickman (2009). All the persons registered in a Statistical Area (SA) according to the CPR were given a weight, such that their weighted total equals to the estimated population size in that SA. There are over 3000 SAs in Israel. For post-census population statistics, a person's weight would remain the same, as long as the person stays in the same SA. A person would in principle take on the weight of the destination SA, if the person registers a move to another SA in the CPR. In this way, the pattern of misplacement adjustment in each SA is preserved, while the CPR count of persons registered in the SA naturally varies over time. Notice that in reality the basic idea expounded above needs to be refined in several ways. For instance, the weight may vary across different sub-populations within an SA. Moreover, ad hoc adjustment may be required, if one detects an abnormal change in a given SA, often due to delays of previous or new housing developments. \subsubsection{APD for erroneous enumeration in Latvia and Estonia} Erroneous enumerations due to lack of updating of emigration were evidenced in the last census in both Latvia and Estonia. Each developed new method for post-census population statistics, which are similar in some respects while differ in others. The initial census 2011 enumeration returned a population count of 2.075 million in Latvia, which was about 7\% lower than the CPR count. The Central Statistical Bureau of Latvia worked out an adjustment method based on statistical classification and migration mirror statistics (CSBL, 2019). By combining the census data with relevant administrative data including the CPR, approximately 100 000 persons were added to the census enumeration from the administrative data. Treating the imputed census enumeration as the labelled units, supervised learning by logistic regression yielded a predicted probability of erroneous enumeration for each eligible person in the CPR. The fitted model was used in the post-census years to adjust the CPR population count. The imputation of census under-enumeration was similar in Estonia, which added about 30 000 persons from the relevant administrative sources to the initial census enumeration of about 1.3 million in total. A residency index was developed for the post-census years, which is updated on a yearly basis (Tiit and Maasing, 2016). First, an extended population $(U_+)$ is constructed, which has negligible under-coverage errors. Next, 27 administrative sources are used to construct a Sign-of-Life score $X(k,t-1)$ for person $k\in U_+$ in year $t$, including special care, parental leave, dental care, digital prescription, prison visit, change of vehicle, residence permit, and so on. The residency index for person $k$ in year $t$, denoted by $R(k,t)$ is calculated from $R(k,t-1)$ and $X(k,t-1)$ as \[ R(k, t) = d\cdot R(k, t-1) + g\cdot X(k, t-1) \] where $d$ is the stability rate and $g$ the signs of life rate, the values of which are heuristically chosen to yield plausible updated population counts. \subsubsection{APD for erroneous and missing enumerations in Italy} The population census in Italy is moving to a `permanent' census, which will produce annual population statistics instead of the previous decennial cycle, using information from administrative sources integrated with sample surveys. Moreover, the first-phase sample for population statistics will provide the frame for the main social survey samples, which are negatively coordinated at the second phase. The first-phase sample has two components. The component A consist of a sample of Enumeration Areas or addresses selected from an Integrated Address File. The component L is selected from a list of households (in the CPR), to provide reliable information on the `census' variables that are not available from the administrative sources. The two components A and L will amount to a yearly sample size of about 400,000 households and 1,000,000 persons, respectively, drawn from 2850 out of 7950 municipalities. Population estimates will be obtained by an extended Dual System Estimation method, accounting for both under-coverage and over-coverage errors of the CPR. It is planned that all the eligible persons in the CPR will be given a weight, such that the weighted totals are equal to the estimated population sizes in the respective municipalities. \subsubsection{APD for missing enumerations in Ireland} The traditional population census in Ireland takes place every 5 years. Despite the absence of CPR, the CEO has developed an alternative estimation methodology at the national level, based purely on administrative sources; see e.g. Dunne (2015), Zhang and Dunne (2017). The Irish APD approach is unique internationally, where it operates in such a way that one only needs to deal with the missing enumerations at the national level. The core of Dual System Estimation consists of two lists both subjected to missing enumerations only. The CEO constructs a Sign-of-Life register, called the Person Activity Register (PAR), based on observed activities across a range of administrative sources, such that the PAR is expected to have only negligible over-counting errors, whereas it can have systematic under-coverage errors in different parts of the usual resident population. Next, the Drivers' License Database (DLD) provides a plausible second cross-sectional enumeration list, based on the fact that each holder needs to renew the license every 10 years. As discussed in Zhang (2019b), the two lists PAR and DLD can satisfy the assumptions of Dual System Estimation, which differ from those assumptions traditionally held for estimation based on census and census coverage surveys (Wolter, 1986). \section{Fractional counting and rolling} The CPR approach is unlikely to be feasible in the UK in the near future beyond 2021. Provided linkage across the sources, the APD approach will encompass the DBE approach, now that all the administrative data for component estimation can be brought together into an integrated PD. The key challenge then, for making greater use of the combined administrative and survey data, will be to achieve an individual-based estimation methodology (such as in Israel, Latvia and Estonia), instead of population hypercube-based estimation (such as currently envisaged in Italy and Ireland). This requires above all two extensions to the existing APD approach: \begin{itemize}[leftmargin=6mm] \item whereas the current Israeli approach focuses only on misplacement and the Latvian and Estonian approaches only on erroneous enumeration, one needs to be able to account for more than one type of error in the APD approach for the UK; \item one needs a more rigorous methodology for the updating of weights, score or index over time, for the individuals in the PD. \end{itemize} Below, to address the first issue, we outline a theory of \emph{fractional counting} for population statistics; regarding the second issue, we discuss the basic ideas for the rolling or incremental learning of the fractional counters. \subsection{Fractional counting for misplacement} To focus on the idea, suppose for the moment that the PD, denoted by $\mathcal{P}$, is only subjected to misplacement, where $\mathcal{P} = U$ and $U$ is the target population. \paragraph{Sign-of-Life (SoL) addresses} For each person $k$ in $\mathcal{P}$, one finds the possible distinct addresses, at which the person may be located according to all available administrative sources. For instance, a student may have home address (of the parents) in addition to an address in the Higher Education loan register. Or a person may have different addresses in the Patient Register and the Council Tax register. Notice that depending on the data available and the aggregation detail required for population statistics, the address may identify a coarser-than-dwelling location, such as post code or municipality. We shall refer to such addresses as the SoL-addresses. \paragraph{SoL-address classifier and predictor} Let ${\bf a}_k$ be the $q$-vector containing all the available SoL-addresses of person $k$ in $\mathcal{P}$. Let ${\bf z}_k$ contain all the relevant auxiliary data, such as known family relationships, emigration status, previous addresses, work or study place, and so on. A SoL-address \textit{classifier} is given by \[ {\bf y}_k = g({\bf a}_k, {\bf z}_k) \in \{ 0, 1\}^q\qquad\text{where}\quad {\bf y}_k^{\top} {\bf 1} = 1 \] i.e. one and only one of the available addresses is chosen as the address for person $k$, such that the corresponding component of ${\bf y}_k$ is set to 1 and all the other components are set to 0. Moreover, a SoL-address \textit{predictor}, or \emph{fractional counter}, is given by \[ \boldsymbol{\mu}_k = h({\bf a}_k, {\bf z}_k) \in [0, 1]^q\qquad\text{where}\quad \boldsymbol{\mu}_k^{\top} {\bf 1} = 1 \] i.e. each component can take value from 0 to 1 and all the components sum to 1. The idea is for each component of $\boldsymbol{\mu}_k$ to be probability that the corresponding address is the true usual resident address of person $k$, denoted by adr$_k$. \paragraph{Population size based on fractional counting} Based on the individual classifier for all $k\in \mathcal{P}$, the population count of locality $i$, for $i = 1, ..., m$, is given by \begin{equation}\label{cls} \widehat{N}_i^C = \sum_{k\in \mathcal{P}} {\bf y}_k^{\top} \boldsymbol{\delta}_k \qquad\text{and}\qquad \boldsymbol{\delta}_k = \boldsymbol{\delta}({\bf a}_k \in A_i) \end{equation} where $A_i$ denotes the set of admissible addresses for the $i$th locality, and $\boldsymbol{\delta}({\bf a}_k \in A_i)$ is the $q$-vector with each component taking value 1 if the corresponding address belongs to $A_i$ and 0 otherwise. Whereas, based on the fractional counter $\boldsymbol{\mu}_k$ and the method of \emph{fractional counting}, the population count of the same locality is given by \begin{equation}\label{pred} \widehat{N}_i^P = \sum_{k\in \mathcal{P}} \boldsymbol{\mu}_k^{\top} \boldsymbol{\delta}_k \qquad\text{and}\qquad \boldsymbol{\delta}_k = \boldsymbol{\delta}({\bf a}_k \in A_i) \end{equation} \paragraph{Properties of fractional counting} Prediction by classifier \eqref{cls} resembles election by majority vote, where the winner takes \emph{all} the votes regardless of the margin over the votes for the loser. It will cause bias of population statistics. Prediction by fractional counting \eqref{pred} aims to avoid this problem. It is unbiased for any $N_i$, provided \begin{equation} \label{unbias} \begin{cases} \boldsymbol{1}^{\top} \mbox{Pr}(\mbox{adr}_k = {\bf a}_k) = 1 \\ \boldsymbol{\mu}_k = \boldsymbol{\mu}({\bf a}_k, {\bf z}_k) \end{cases} \end{equation} The first condition ensures that the true address (adr$_{k}$) can only be one of the SoL-addresses, insofar misplacement is the only problem at hand. The second condition then ensures that the probabilities of $\mbox{adr}_k = \boldsymbol{a}_k$ is entirely determined by ${\bf a}_k$ and $\boldsymbol{z}_k$. In reality the matter will depend on the covariates $\boldsymbol{z}_k$ and how well $\boldsymbol{\mu}_k$ in \eqref{pred} is modelled. Given the $\boldsymbol{\mu}_k$'s, the prediction variance of $\widehat{N}_i^P$ by \eqref{pred} is \[ V(\widehat{N}_i^P - N_i) = \sum_{k\in \mathcal{P}} \boldsymbol{\mu}_k^{\top} \boldsymbol{\delta}_k \big( 1 - \boldsymbol{\mu}_k^{\top} \boldsymbol{\delta}_k \big) \] where we assume that $\delta(\mbox{adr}_k \in A_i)$ is independent across different persons, conditional on the $({\bf a}_k, {\bf z}_k)$'s. However, it is possible to allow for clustering effects in the variance calculation, depending on the model underlying $\boldsymbol{\mu}_k$, such as when it always assigns the same $\boldsymbol{\mu}_k$ to all the persons in the same family and family relationship is part of $\boldsymbol{z}_k$. \paragraph{Producing social statistics} Population and sub-population totals based on fractional counting can provide calibration totals for social surveys in the same way as the MYEs. Consider register-based attribute statistics. Denote by $\epsilon_k$ the value of interest for $k\in \mathcal{P}$, and $\hat{\epsilon}_k$ the corresponding register-based value. In cases where $\epsilon_k$ is observed without error, one can simply set $V(\hat{\epsilon}_k - \epsilon_k) = 0$; otherwise the variance will be positive in cases of model-based prediction of $\epsilon_k$ based on register sources. The population and fractional counting totals in the $i$th locality are given, respectively, as \[ t_i = \sum_{k\in \mathcal{P}} \delta_k \epsilon_k \qquad \text{and}\qquad \hat{t}_i = \sum_{k\in \mathcal{P}} \hat{\mu}_k \hat{\epsilon}_k \] where $\delta_k = \delta(\mbox{adr}_k \in A_i)$ as defined in \eqref{cls} and \eqref{pred}, and $\hat{\mu}_k = \boldsymbol{\mu}_k^{\top} \boldsymbol{\delta}_k = \widehat{\mbox{Pr}}(k \in U_i)$ by the fractional counter. We have unbiased $\hat{t}_i$, for $i = 1, ,..., m$, provided \[ E(\hat{\mu}_k - \delta_k) = 0 \quad\text{and}\quad E(\hat{\epsilon}_k - \epsilon_k) =0 \quad\text{and}\quad (\hat{\epsilon}_k, \epsilon_k) \perp (\hat{\mu}_k, \delta_k)~, \] since $E(\hat{t}_i - t_i) = \sum_{k\in \mathcal{P}} E(\hat{\mu}_k \hat{\epsilon}_k - \delta_k \epsilon_k)$, where \[ E(\hat{\mu}_k \hat{\epsilon}_k - \delta_k \epsilon_k) = E(\hat{\mu}_k \hat{\epsilon}_k - \delta_k \hat{\epsilon}_k + \delta_k \hat{\epsilon}_k - \delta_k \epsilon_k) = 0 ~. \] Provided independence across different persons, the prediction variance is given as \[ V(\hat{t}_i - t_i) = \sum_{k\in \mathcal{P}} V(\hat{t}_i - t_i) \] Again, it is possible to relax the independence assumption and allow for clustering effects in the variance calculation. \subsection{Initiation in the absence of missing enumerations} It is natural to initiate the fractional counters in connection with the next census. The pre-2011 MYEs were retrospectively adjusted upwards given the census population estimates. This suggests that the administrative sources for the DBE component estimation may suffer from some under-coverage. Nevertheless, we shall assume that going forward the enhanced administrative sources will enable one to construct the PD as an extended population, denoted by $\mathcal{P}$, which has negligible under-coverage of the population, denoted by $U$. However, for any in-scope person, we do not require the first condition of \eqref{unbias} to hold, in anticipation of possible weakness of the SoL-address sources. That is, for each person $k\in \mathcal{P} \cap U$, we allow for a probability of being \emph{displaced}, denoted by \[ \xi_k = 1 - \boldsymbol{1}^{\top} \mbox{Pr}(\mbox{adr}_k = {\bf a}_k) \geq 0 ~. \] For supervised learning of \emph{fractional counter}, one ideally needs to label everyone in $\mathcal{P}$ first as erroneous or not, then in the latter case, displaced or not, and finally in the case of not displaced, the vector $\mbox{adr}_k = {\bf a}_k$. The situation following the UK census 2021 is ragged due to the presence of multiple errors, as depicted in Table \ref{tab-initial}. \begin{table}[ht] \begin{center} \caption{Initiation of fractional counters in $\mathcal{P}$ based on census} \begin{tabular}{cccccccccccc} \hline \multicolumn{8}{c}{Fractional counter} & & & & Enum. \\ \cline{1-8} \multicolumn{4}{c}{Placement} & $~$ & Displaced & $~$ & Erroneous & $~$ & $\mathcal{P}$ & $~$ & Census \\ \cline{4-4} \cline{6-6} \cline{8-8} \cline{10-10} \cline{12-12} & & & \multicolumn{1}{|r|}{1 adr} & & \multicolumn{1}{|c|}{$\xi_1$} & & \multicolumn{1}{|c|}{$\theta_1$} & & \multicolumn{1}{|c|}{1} & & \multicolumn{1}{|c|}{1} \\ \cline{3-4} & & \multicolumn{2}{|r|}{2 adr} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & Core & \multicolumn{1}{|c|}{$\vdots$} \\ \cline{2-4} & \multicolumn{3}{|r|}{3 adr} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} \\ \cline{1-4} \multicolumn{4}{|r|}{$\cdots\quad\cdots\quad\vdots$} & & \multicolumn{1}{|c|}{$\xi_{N_c}$} & & \multicolumn{1}{|c|}{$\theta_{N_c}$} & & \multicolumn{1}{|c|}{$N_c$} & & \multicolumn{1}{|c|}{$N_c$} \\ \cline{1-4} \cdashline{5-12} & & & \multicolumn{1}{|r|}{1 adr} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} \\ \cline{3-4} & & \multicolumn{2}{|r|}{2 adr} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & (Non- & \multicolumn{1}{|c|}{$N_L$} \\ \cline{2-4} \cline{12-12} & \multicolumn{3}{|r|}{3 adr} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & & \multicolumn{1}{|c|}{$\vdots$} & core) & $\widehat{N}$ \\ \cline{1-4} \multicolumn{4}{|r|}{$\cdots\quad\cdots\quad\vdots$} & & \multicolumn{1}{|c|}{$\xi_{N_p}$} & & \multicolumn{1}{|c|}{$\theta_{N_p}$} & & \multicolumn{1}{|c|}{$N_p$} \\ \cline{1-4} \cline{6-6} \cline{8-8} \cline{10-10} \\ \multicolumn{8}{c}{$\underbrace{\sum \boldsymbol{\mu}_k^{\top} \boldsymbol{1} + \sum \xi_k = \widehat{N}, \quad \widehat{N} + \sum \theta_k = N_p}_\text{Benchmarking}$} \end{tabular} \label{tab-initial} \end{center}\end{table} Reading from right to left, the census enumerations are numbered as 1, ..., $N_L$, where $N_c$ of them can be linked to $\mathcal{P}$. The linked part of $\mathcal{P}$ is referred to as the \emph{core} of PD, denoted by $\mathcal{P}_c$. One observes $\delta(k\in U) = 1$ and $\delta(\mbox{adr}_k = \boldsymbol{a}_k)$ for all $k\in \mathcal{P}_c$, based on the census data. One can treat $\mathcal{P}_c$ as a non-probability sample from $\mathcal{P}$. Under the assumption of non-informative selection, i.e. \[ \boldsymbol{\mu}(\boldsymbol{a}_k, \boldsymbol{z}_k | k\in \mathcal{P}_c) = \boldsymbol{\mu}(\boldsymbol{a}_k, \boldsymbol{z}_k | k\in \mathcal{P} \cap U) ~, \] one can estimate $\boldsymbol{\mu}(\boldsymbol{a}_k, \boldsymbol{z}_k | k\in \mathcal{P} \cap U)$ consistently from $\mathcal{P}_c$. This allows one to populate the probabilities $\xi_k$ and $\boldsymbol{\mu}_k$ for all $k\in \mathcal{P}$, in the case of $k\in U$. Moreover, these probabilities can be benchmarked to the census population estimates, denoted by $\widehat{N}$, at any aggregation level or for any sub-population of choice. There are different ways of benchmarking; see e.g. Favre et al (2005) for a method that can incorporate unit-level constraints. The estimation of the probability of erroneous enumeration, denoted by $\theta_k$ for $k\in \mathcal{P}$, requires a different approach. Some possibilities are given below. \begin{itemize}[leftmargin=5mm] \item One can replicate the approach of Latvia and Estonia, whereby one labels a subset of $\widehat{N}$ persons in $\mathcal{P}$, denoted by $\mathcal{P}_U \subset \mathcal{P}$. The additional non-core persons in $\mathcal{P}_U \setminus \mathcal{P}_c$ are the ones judged to be the most likely in-scope persons in $\mathcal{P}\setminus \mathcal{P}_c$ or, equivalently, the persons in $\mathcal{P}\setminus \mathcal{P}_U$ are the most likely out-of-scope persons in $\mathcal{P}\setminus \mathcal{P}_c$. \item One can use the population hypercube estimated from the census and census coverage survey, and assign the probabilities $\theta_k$ according to the cell of person $k$, for $k\in \mathcal{P}$. \item One can draw a probability sample $s$ from $\mathcal{P}\setminus \mathcal{P}_c$ and obtain $\delta(k\in U)$ for $k\in s$, and use the combined sample $\mathcal{P}_c \cup s$ to estimate $\theta_k$, for $k\in \mathcal{P}$. \end{itemize} Benchmarking of the estimated $\theta_k$'s may be necessary, denoted by $\widehat{N} + \sum \theta_k = N_p$, in the case of individual-based estimation. Finally, notice that international migration and other special populations may need to be treated separately from the above. \subsection{Basic ideas of rolling} By \emph{rolling} we mean that in principle the fractional counters can be updated in a nearly continuous manner over time, just as $\mathcal{P}$ itself. It seems most similar to \emph{incremental learning} in the statistical machine learning literature. Below we first summarise the data that can be made available for rolling, and then discuss the basic ideas in the parametric and algorithmic settings, respectively. \subsubsection{Data for rolling} Let $\mathcal{P}_t$ be the PD at time $t$, where $t\geq 0$, and $\mathcal{P}_0$ is the initiation PD, say, at the census time point. Denote by $\mathcal{L}_t$ the set of labelled persons, where $\mathcal{L}_t \subseteq \mathcal{P}_t$, on which supervised learning can be based. Without losing generality, one can partition $\mathcal{L}_t$ into three parts: \begin{equation} \label{data} \mathcal{L}_t = S_t \cup \mathcal{B}_t \cup \mathcal{A}_t \end{equation} where $S_t$ denotes the subset of persons that are associated with known inclusion probabilities, and $\mathcal{B}_t$ denotes the other persons for whom we observe updated labels of (erroneous, displaced, placement), and $\mathcal{A}_t$ the rest for whom we have only the labels from $t-1$. \textit{It will be important and helpful to enhance the collection, organisation and usage of all the relevant data, across the ONS, in order to facilitate efficient rolling and enable the transition to a sustainable system for population statistics in the long term.} \paragraph{Coverage survey} The planned post-census coverage survey is a source of $S_t$. The observations in $S_t$ can obviously be used for updating of $\boldsymbol{\mu}$ and $\xi$, pertaining to the probabilities of displaced and placement. Depending on the actual design and estimation method, it may as well be possible to update the erroneous enumeration probability $\theta$, especially if it is possible to administer follow-up surveys at the sampled addresses in the coverage survey. \paragraph{On-going surveys} As mentioned before, the planned approach at Istat is to draw household samples for the main social surveys from their first-phase sample for population statistics. Unless the ONS adopts the same approach, there will be other labelled persons from the on-going social surveys, in addition to the coverage survey. Notice that the fieldwork protocol in the on-going surveys will need to be enhanced to ensure the quality of the data collected for rolling. Whether these additional labelled persons can be classified as part of $S_t$ or $\mathcal{B}_t$ depends on the actual sampling design. \paragraph{Administrative sources} Updating in the relevant administrative sources can generate labelled persons. For instance, updating of the Council Tax register, the home addresses in Drivers' License database, the PAYE register, and so on, can all provide data for $\mathcal{B}_t$. The distinction of core and non-core in $\mathcal{B}_t$ can be relevant at least in the near future. \subsubsection{Rolling in the parametric setting} \label{EBP} For a parametric setting of the fraction counters, suppose the relevant probabilities are given by the inverse of the logistic link function, denoted by \[ \boldsymbol{\pi}(\boldsymbol{x}_k, \boldsymbol{\beta}) = E(\boldsymbol{y}_k | \boldsymbol{x}_k ; \boldsymbol{\beta}) \] for person $k$, where $\boldsymbol{y}_k$ is the vector of indicators whose components sum to 1, and $\boldsymbol{x}_k$ is the vector of known covariates, and $\boldsymbol{\beta}$ the logistic regression coefficients. Suppose the initial $\boldsymbol{\beta}_0$ are estimated based on a large dataset in connection with the census, denoted by $\hat{\boldsymbol{\beta}}_0$, with associated variance $\hat{\boldsymbol{\Sigma}}_0$. At the next time point $t=1$, one could refit the model using the labelled persons in $\mathcal{L}_1$, of which $\mathcal{D}_1 = S_1\cup \mathcal{B}_1$ are associated with updated observations of $\boldsymbol{y}_{1,k}$, for $k\in \mathcal{D}_1$. This assumes $\boldsymbol{y}_k$ remains the same at $t=0, 1$, for any non-updated person $k\in \mathcal{L}_1 \setminus \mathcal{D}_1$, which may be problematic if the lack of updating is due to delays or errors in the sources. One could refit the model using only the data associated with $\mathcal{D}_1$, under some suitable assumption of non-informative selection of $\mathcal{D}_1$ from $\mathcal{P}_1$. The estimation precision is then determined by the size of $\mathcal{D}_1$, which is much smaller than the initiation dataset $\mathcal{L}_0$, so that the uncertainty of the estimated $\boldsymbol{\beta}_1$ will be much larger than that of $\hat{\boldsymbol{\beta}}_0$. Consider empirical Bayes (best) prediction (EBP) under the hierarchical model: \begin{gather*} E(\boldsymbol{y}_{1,k} | \boldsymbol{x}_{1,k} , \boldsymbol{\beta}_1) = \boldsymbol{\pi}(\boldsymbol{x}_{1,k}, \boldsymbol{\beta}_1) \\ \boldsymbol{\beta}_1 \sim N(\hat{\boldsymbol{\beta}}_0, \hat{\boldsymbol{\Sigma}}_0) \end{gather*} where the normal distribution is motivated by the large size of initiation dataset $\mathcal{L}_0$. At the lower level, the population dynamics which change the parameter $\boldsymbol{\beta}_0$ from time 0 to $\boldsymbol{\beta}_1$ at time 1 is modelled as a `random' departure from the previous `position' $\hat{\boldsymbol{\beta}}_0$ with variance $\hat{\boldsymbol{\Sigma}}_0$. This differs in concept to fully Bayesian approach, where the hyper-parameter of the prior distribution of $\boldsymbol{\beta}_1$ needs not to have any empirical connotation. Assuming IID observations over $\mathcal{D}_1$, we obtain the prediction function for $\boldsymbol{\beta}_1$ as \[ f(\boldsymbol{\beta}_1 | \boldsymbol{y}_{1,\mathcal{D}_1}, \boldsymbol{x}_{1,\mathcal{D}_1} ; \hat{\boldsymbol{\beta}}_0, \hat{\boldsymbol{\Sigma}}_0) = \frac{\prod_{k\in \mathcal{D}_1} f(\boldsymbol{y}_{1,k} | \boldsymbol{x}_{1,k}, \boldsymbol{\beta}_1) \cdot \phi(\boldsymbol{\beta}_1; \hat{\boldsymbol{\beta}}_0, \hat{\boldsymbol{\Sigma}}_0)}{\prod_{k\in \mathcal{D}_1} f(\boldsymbol{y}_{1,k} | \boldsymbol{x}_{1,k})} \] Let $\hat{\boldsymbol{\beta}}_1$ and $\hat{\boldsymbol{\Sigma}}_1$ be the prediction mean and variance of $\boldsymbol{\beta}_1$, respectively. In this way the lower-level model is updated to $\boldsymbol{\beta}_2 \sim N(\hat{\boldsymbol{\beta}}_1, \hat{\boldsymbol{\Sigma}}_1)$, by which the model is rolled forward and ready to be used for updating at $t=2$. The EBP approach can thus facilitate the rolling of fractional counters, without the extra and potentially problematic assumption that $\boldsymbol{y}_k$ remains the same for $k\in \mathcal{L}_1 \setminus \mathcal{D}_1$, or losing efficiency as when estimating $\boldsymbol{\beta}_1$ only based on $\mathcal{D}_1$. It achieves stability over time, balancing between the signals from $\mathcal{D}_t$ and the inertia of $N(\hat{\boldsymbol{\beta}}_{t-1}, \hat{\boldsymbol{\Sigma}}_{t-1})$: any value of $\boldsymbol{\beta}_t$ far from $\hat{\boldsymbol{\beta}}_{t-1}$ are `weighted down' by $\phi$, compared to only based on $f(\boldsymbol{y}_{t,k} | \boldsymbol{x}_{t,k}, \boldsymbol{\beta}_t)$. \subsubsection{Rolling in the algorithmic setting} \label{learning} Machine learning or statistical machine learning has a vast and rapidly growing literature. There does not exist a unified framework of the different approaches. Below we first list some classifications and concepts that seem relevant, before we illustrate and discuss the basic ideas of decision tree updating in the present context. With respect to the logical basis of learning, a distinction is between transduction and induction. Transduction or transductive inference is reasoning from observed (training) cases to specific (test) cases. In contrast, induction is reasoning from observed training cases to general rules, which are then applied to the test cases. The distinction seems most interesting in siutations where the predictions of the transductive model are not achievable by any inductive model. However, transductive algorithms that seek to predict discrete labels tend to be derived by adding partial supervision to a clustering algorithm, while supervised learning is generally considered to be a form of induction. With respect to the context of learning, one commonly distinguishes among unsupervised learning (without labelled units), supervised learning (based on labelled units), and reinforcement learning (in an interactive environment). The last type of algorithm enables an agent to learn by trial and error using feedbacks from its own actions and experiences, such as in gaming. Semi-supervised learning is a class of techniques that typically use a small amount of labelled data with a large amount of unlabelled data, as many researchers have found that unlabelled data, when used in conjunction with a small amount of labelled data, can produce considerable improvement in learning accuracy. With respect the process of learning, broadly speaking there are two ways to train a model. A static model is trained offline, once and then used as-is for a while. A dynamic model is trained online, where data is continually entering the system and incorporated into the model through frequent updates. \begin{itemize}[leftmargin=4mm] \item In active learning, one seeks to select the most informative unlabelled instances and ask an omniscient oracle for their labels, in order to retrain a learning algorithm to maximise accuracy. Clearly, the selection mechanism can be designed to resemble audit sampling for model validation or improvement. \item In incremental learning, the data is generated by an external process, and continually used to further train the model, i.e. without the model being completely retrained using all the available data at any given time point. The motivation may be technical, e.g. the data becomes available only gradually over time or its size is out of system memory limits. A central concern is to allow the model to adapt to new data without forgetting its existing knowledge. Some incremental learners have built-in parameters or assumptions that control the relevancy of new and old data. See e.g. Ade and Deshmukh (2013), Gepperth and Hammer (2016). \end{itemize} Regarding the validity of the trained model, data or concept shift is a term one finds in the machine learning literature, which is said to occur when the joint distribution of inputs and outputs differs between training and test stages. Covariate shift, a particular case of data shift, occurs when only the input distribution changes. An example is email spam filtering, which may fail to include spams (for training) that are not detected by the filter used to classify spams. Relevant statistical concepts developed for various informative selection mechanisms do not seem to have attracted much attention here. \subsubsection{Rolling of a decision tree} \label{tree} The Very Fast Decision Tree (VFDT) system is one of the most successful algorithms for mining data streams (Domingos and Hulten, 2000). Its main innovation is the use of Hoeffding bound to decide how many examples (observations) are necessary to observe before installing a split-test at a leaf of the tree. Splitting the leaf makes only a local change to the tree, since the prediction of units ending at another leaf is not affected. The theoretical result refers to the maximum expected disagreement between the Hoeffding tree and the asymptotic batch tree given infinite observations. However, the asymptotic batch tree is hardly our present interest, where one may assume that the population structure (hence the tree itself) must change over time, and the target is not the tree that one will grow given infinite observations that span infinitely over time. \begin{align*} x\leq c ~ & : ~ x> c \\ \swarrow \hspace{8mm} & \hspace{10mm} \searrow \\ \{ 1, 0, 0, 0\} \hspace{6mm} & \hspace{10mm} \{ 0, 1, 1, 1\} \end{align*} To illustrate the issue, consider the above split for two leaves in the tree grown at $t-1$. Let there be one observation $(x', y')$ at $t$ passing this way. Now, \begin{itemize}[leftmargin=6mm] \item if $x' \leq c$ and $y' = 1$, or $x' > c$ and $y' = 0$, then $(x', y')$ may be considered to provide `negative' evidence to the current tree, but perhaps not necessarily so if the value 1 in the left leaf or 0 in the right leaf happens to be observed a long time ago; \item if $x' \leq c$ and $y' = 0$, or $x' > c$ and $y' = 1$, then $(x', y')$ may be considered to provide `positive' evidence to the current tree, but perhaps not necessarily so if a value 0 in the left leaf or 1 in the right leaf happens to be observed a long time ago. \end{itemize} In other words, for the rolling of a decision tree that evolves over time (subjected to concept shift), more considerations are required than the number of observations and the discriminant measure of the split. It seems that one may still need to use part of the updated observations in $\mathcal{D}_t$ for training and part of them for validation. Let $M_t$ denote the updated tree, and $M_{t-1}$ the tree grown at $t-1$. At least two measures may be needed: \begin{itemize}[leftmargin=16mm] \item[$\Delta_{\epsilon}$:] how much better $M_t$ predicts for the updated units in $\mathcal{D}_t$ than $M_{t-1}$, \item[$\Delta_M$:] how much change $M_t$ predicts for the non-updated units in $\mathcal{P}_t \setminus \mathcal{D}_t$. \end{itemize} Since $M_{t-1}$ yields 0 in terms of both measures, one may need to balance between the two measures when growing $M_t$. For instance, one may choose to maximise $\Delta_{\epsilon}$ subjected to an upper bound on $\Delta_M$, or minimise $\Delta_M$ subjected to a lower bound on $\Delta_{\epsilon}$. \section{Register-based auditing-assisted approach} \label{RBAA} Greater resource savings will be the case in future, if population statistics are produced from administrative data and on-going surveys under the APD approach, while purposely designed coverage survey is only used from time to time for \emph{auditing}. There are two necessary elements to such a \textit{register-based auditing-assisted} APD approach. \paragraph{Rolling without coverage surveys} At some stage one needs to be able to exclude the envisaged regular coverage survey data from $\mathcal{L}_t$ in \eqref{data}, and only use the updated observations from other on-going surveys and administrative sources for the rolling of fractional counters, whether it is in the parametric or algorithmic setting. This is not as unthinkable as it may seem at first. For instance, it may be noticed that the existing DBE approach is essentially a register-based APD approach, based on an estimated population hypercube. The Irish APD approach suggests it may be possible to estimate the population hypercube purely based on administrative data, albeit using a different methodology than DBE component estimation. In the register-based APD approaches of Israel, Latvia and Estonia, individual counters are produced by different methods, none of which uses any regular coverage surveys. The Norwegian household register provides another example, where decision rules are applied to individual-level data from the administrative sources. So the question that matters is how good a register-based individual-level APD approach can become in the UK. \paragraph{Auditing inference} Zhang (2018) contrasts register-based APD approach to the APD approach based on combining registers and coverage survey. Under the purely register-based approach, ``an estimator, denoted by $\hat{N}_n$, can be calculated under a statistical model, using multiple incomplete administrative registers, where $N$ denotes the unknown population size and $n$ the generic size of the available datasets.'' It is suggested that, regardless how effective the rolling of $\hat{N}_n$ may be, one is unlikely ``to have $\hat{N}_n / N \stackrel{P}{\rightarrow} 1$ under some asymptotic setting, as $n, N\rightarrow \infty$''. Audit sampling will be necessary, in order to ``validate the model underlying $\hat{N}_n$, ..., which is affected by the sampling error of the auditing survey''. This raises the challenge of audit sampling inference. Using disaggregation of Consumer Price Index based on proxy household expenditure measures obtained from transaction data, Zhang (2019a) develops an audit sampling inference approach for big-data statistics. Generically speaking, let $\theta_0$ be the true scalar parameter value of interest. Let $\theta^*$ be a point estimate based on big data, such that its variance is negligible compared to its potential bias for all practical purposes. One can test $H_0: \theta^* = \theta_0$ based on audit sampling. However, an accuracy measure is needed, even if the hull hypothesis cannot be rejected at the chosen level. A general dilemma in this context is the following. Let $\hat{\theta}$ be an unbiased estimator of $\theta_0$ based on audit sampling, and let $\widehat{V}(\hat{\theta})$ be an unbiased estimator of its audit sampling variance. An unbiased estimator of the mean squared error (MSE) of $\theta^*$ can be given as \[ \widehat{\mbox{MSE}} = (\theta^* - \hat{\theta})^2 - \widehat{V}(\hat{\theta}) ~. \] However, when the bias $\theta^* - \theta$ is small, auditing may fail to yield a meaningful measure, if the audit sampling variance is not small enough, in which case one easily obtains $\widehat{\mbox{MSE}} < 0$ as the result. To overcome the dilemma, Zhang (2019a) proposes a novel accuracy measure to replace the standard MSE. If feasible in the present context, then one can employ an audit sample that is much smaller than the envisaged coverage survey sample. \paragraph{Summary} In the long-term perspective, greatest gains can be achieved via a gradual transition from an APD approach that requires coverage survey sampling to a register-based auditing-assisted APD approach. Audit sampling aims to validate the register-based statistics, and to generate meaningful accuracy measure, for which one can use a much smaller sample size than the envisaged coverage survey sample. To enable the transition, it will be important that one as soon as possible starts the development, so that one can test and refine the required methods and to obtain the necessary experience and confidence over time. \section{Key topics for methodology development} Four inter-related topics for methodological development emerge from the above: \begin{itemize} \setstretch{1.0} \item data linkage for longitudinal PD; \item rolling or incremental learning, including benchmarking, design of coverage survey, and parallel development of register-based auditing-assisted APD approach; \item appropriate uncertainty propagation or accuracy measure in various scenarios; \item methodology for producing social statistics in the new environment. \end{itemize} \subsection{Longitudinal PD} \textit{Generic scalable linkage methodology is a premise to the provision of UK neighbourhood population statistics}. In the first instance, the relevant longitudinal administrative data should be linked to form the longitudinal PD; in the next instance, longitudinal data linkage is the ability to link the longitudinal PD to other open or free data, as well as relevant sample surveys (often longitudinal themselves). Davis-Kean et al. (2017) projects an ambitious outlook to the longitudinal population for ESRC UK longitudinal study resources. In particular, this aims at standardising the designs of the various longitudinal surveys so that they all use the same \emph{longitudinal population register} (i.e. a population spine) as their sampling frame, and with all ESRC research-related linkage of different administrative and survey data sources harmonised to this spine. As an example of such a constructed longitudinal population spine, in countries that do not have a population register to start with, one may refer to the Integrated Data Infrastructure (IDI) at Statistics New Zealand (SNZ, 2018). Although the Fellegi and Sunter (FS) methodology for record linkage has proven to be very useful in practice (e.g. Owen et al., 2015), it does have some theoretical issues. \begin{itemize}[leftmargin=6mm] \item Applying the Likelihood Ratio Test to all the pairs $A\times B$ in files $A$ and $B$ creates a multiple comparison problem. The acceptable pairs require deduplication, e.g. when both $(ab)$ and $(ab')$ are above the acceptance threshold. It is difficult to link multiple files in a transitive manner, e.g. that $(ab)$ in $A\times B$ and $(bc)$ in $B\times C$ are links does not necessarily entail $(ac)$ will be accepted as a link when looking at $A\times C$. \item The joint distribution of all the $n_A n_B$ comparison scores is ill-defined, if one treats e.g. the comparison scores for $(ab)$ and $(ab')$ as if they were independent of each other. The so-called maximum likelihood estimator of the parameters of the $m$- and $u$-probabilities (Jaro, 1989) are biased in reality; see e.g. Fortini and Tuoto (2019). \end{itemize} Entity resolution provides theoretically a more attractive formulation (e.g. Christen, 2012), where the set of (unique) entities underlying the separate datasets are envisaged as a latent spine of unknown size, and each record (in any dataset) is attached to one and only one latent entity on the spine. In this way, the records in different files are linked to each other or deduplicated, provided they are attached to the same latent entity, in a transitive manner regardless of the number of datasets involved. There are a few applications of the entity resolution perspective under the Bayesian paradigm of computation (e.g. Tancredi and Liseo, 2011; Stoerts et al., 2017), although there is nothing intrinsically Bayesian about this perspective to record linkage. Lack of scalability has been a central challenge to the proposed methodology so far, which is not yet feasible e.g. to link the population census file with the patient register. Scalable linkage methods for multiple population-size datasets are important to the creation of the longitudinal PD. Moreover, the generic ability to link multiple files in a transitive manner can be expected to improve the quality of statistical information harnessed in the linked dataset. Replacing the FS-paradigm to record linkage by the entity resolution perspective can provide the angle for innovative approaches. \subsection{Rolling or incremental learning} \textit{The methodology of rolling or incremental learning needs to be studied and decided upon.} Firstly, one needs to find out how rolling by EBP in the parametric setting (Section \ref{EBP}) works out in practice. Next, it is possible that algorithmic learning (Section \ref{learning}) can provide a more flexible and powerful predictive modelling approach. However, incremental learning in the presence of concept shift (i.e. the model changes over time) does not yet have an established approach in the literature. Methodological developments in this respect will be necessary, in case one would like to pursue algorithmic learning. Whether one adopts parametric or algorithmic learning, there are at least three other relevant aspects that seem worth attention, as discussed below. Firstly, one may naturally wish to benchmark the updated fractional counters, towards the estimated population hypercube from combined register and coverage survey data, as during their initiation (Table \ref{tab-initial}). A possibility is to only apply benchmarking when producing population statistics to be disseminated, say, on a yearly basis in the years immediate after 2021. In other words, benchmarking and rolling of fractional counters can have different frequencies. The methodology and practice need to be established. Secondly, how to make effective use of the coverage survey, and can active learning be related to its design? By active learning, one seeks to observe the unlabelled instances that are most effective for model validation or improvement. For instance, in the present context, it seems reasonable that one should give higher sample representation of the non-core part of the PD, or the persons who are judged to have weak fractional counters, e.g. placement probabilities $\boldsymbol{\mu}_k$ are not `close' to a dummy vector, or a relatively large probability of being displaced ($\xi_k$) or out-of-scope ($\theta_k$). Regardless of the exact characterisation, this suggests that one may need a method for follow-up surveys of some addresses, given the PD-status of the persons at different addresses. Thirdly, `parallel' learning of register-based fractional counters (Section \ref{RBAA}) requires a different approach, where the coverage survey data are only used indirectly for updating of the model, but not directly as labelled observations for supervised learning. This means that one would like to combine supervised learning from $\mathcal{L}_t \setminus \mathcal{C}_t$, where $\mathcal{C}_t$ denotes the coverage survey sample, and heuristic updating of the fitted model, based on the evidence in $\mathcal{C}_t$. Such heuristic updating differs from benchmarking, where the latter requires estimates using the coverage survey. For instance, one may envisage heuristic updating in the form of a decision tree, where the paths close to the root are determined by stable decision rules evidenced from the comprehensive coverage survey data, while the observations in $\mathcal{L}_t \setminus \mathcal{C}_t$ are only used for the splits and sprouting near the leaves. \subsection{Uncertainty propagation or accuracy measure} \textit{Theoretical conceptualisation and practical method for uncertainty propagation or accuracy measures are needed in several scenarios}. Firstly, for the initiation of fractional counters, the core part of PD that can be linked to the census enumerations will be used for the estimation of displacement and misplacement probabilities, whereas the census enumerations and the census coverage survey will be used for estimating the probability of erroneous enumeration. It needs to be verified whether conditional uncertainty propagation given the estimated fractional counters can sensibly capture the various underlying variations, and if not, how it might be modified to produce plausible accuracy measures in a practical manner. As explained in Section \ref{EBP}, uncertainty propagation from parameter updating to fractional counting given the parameter can be based on a coherent scheme under the rolling of parametric EBP. The matter is less clear under incremental algorithmic learning. Suppose the fitted model is given as a decision tree, which is updated by a constrained optimisation method (Section \ref{tree}). Conditional uncertainty propagation given the updated tree is straightforward, just as when the fractional counters are given parametrically. But how can one incorporate the uncertainty of the tree updating itself? One can introduce some kind of bootstrap. But at which level should one allow the replicate trees to vary from each other: simply where the new splits are created, or higher up? Finally, the methodology of audit sampling inference needs to be worked out for register-based fractional counting (Section \ref{RBAA}). It will be possible to treat the coverage survey sample, or part of it, as the audit sample, whether the coverage survey is designed to accommodate active learning or not. This is necessary in order to provide the statistical argument for the transition towards a register-based auditing-assisted APD approach in the long term, in replacement of the more costly continuous coverage survey. \subsection{Producing social statistics in the new environment} Though not central to this report, it must be pointed out that \textit{the production of social statistics requires a broad perspective to design and estimation in the new environment}. The specifics of future provision of population statistics will change considerably in the UK. Traditional MYEs with decennial census updating will no longer be the foundation of social statistics on temporally varying topics and phenomena of interest. It would be narrow-minded and ineffective to simply replace the population benchmarks, albeit produced based on a different APD approach beyond 2021, but keep the same design strategies across the spectrum of social survey programmes. For instance, as mentioned earlier, a two-phase approach is currently being developed in Italy, where the first-phase sample targets mainly at the population statistics, and the major social survey samples are selected as negatively coordinated second-phase samples. It is yet unclear whether this is a suitable solution in the UK. Neither is it necessarily the most effective approach, generally speaking or in the long run, when it comes to the combined use of coverage survey and other social social surveys. The coverage survey as currently envisaged may no longer be necessary, provided the transition to a register-based auditing-assisted APD approach to population statistics. How to combine audit sampling and on-going social surveys will be then a different overall design question. Indeed, greater use of administrative data is expected to extend to the area of social statistics as well. It is thus perhaps appropriate to set on a future landscape of register-based auditing-assisted population \emph{and} social statistics.
{'timestamp': '2021-11-08T02:01:11', 'yymm': '2111', 'arxiv_id': '2111.03100', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03100'}
arxiv
\section{Introduction}\label{sec:introduction} \IEEEPARstart{R}{ecently}, the amount of videos uploaded to the internet has increased substantially. According to Statista \cite{StatistaResearchDepartment}, by May 2019, more than 500 hours of video were uploaded to YouTube every minute, and the numbers did not slow down. Therefore, the need for robust algorithms to analyse this enormous amount of data has increased accordingly. \par An action recognition system based upon human body motions is the most efficient way of interpreting videos' contents. Several solutions have been proposed in this regard, and they vary from the analysis of optical flow \cite{Bobick2001}, convolutional neural networks upon RGB images \cite{Tran2015} and more recently, the skeleton movements \cite{yan2018spatial}. The skeleton movements approach offers multiple advantages over the other solutions. The skeleton information is robust to changes in the illumination of the environment where the action takes place. Also, it is robust to changes in the background \cite{Keskes2021}. Moreover, the computational cost for training is considerably reduced for skeleton data consisting of only sets of joint cartesian coordinates. For these reasons, we have chosen this approach to define the premise of our proposed method.\par There are multiple sources to obtain the skeleton information from videos. Among these, the OpenPose library \cite{Cao2021a} is the simplest yet effective tool to accomplish this. This system receives a video clip as an input and outputs the 2D or 3D coordinates of the 18 main skeleton joints. Each skeleton joint information consists of three values as (x, y, c), where x and y are the cartesian coordinates in the horizontal and vertical axis, respectively, and c represents the confidence score of the detected joint. The keypoints indexes of the OpenPose output layout are shown in Fig. \ref{fig:keypoints}. \begin{figure}[!t] \centering \includegraphics[width=0.4\textwidth]{Figures/Open_Pose_Components_1.png} \caption{Skeleton components and the keypoints indexes of OpenPose layout.} \label{fig:keypoints} \end{figure} Our study is based upon the proposal presented by Yan \textit{et al.} in \cite{yan2018spatial}. Instead of analysing the frames of a video by their pixel values (i.e., RGB images), the authors first represent the actors as a set of the main joints of the body using the OpenPose library \cite{Cao2021a}. Given the skeleton representation of the person performing the action, they model the skeleton joints as a set of vertices of a graph. On the other hand, the bones-like connections can be represented as the edges of the graph. Thus, the video clips are transformed from RGB image sequences to a sequence of skeleton joints. To achieve the action recognition, the authors proposed the Spatial-Temporal Graph Convolutional Neural Network (ST-GCN) model. As the name indicates, this framework can analyse both the spatial and the temporal relations between the set of nodes (i.e., the skeleton joints) during the performance of the action (Fig. \ref{fig:skeleton_rep}). Subsequently, the model is trained in an end-to-end manner using a Graph Convolutional Neural Network (GCN) architecture \cite{Zhou2018}. \begin{figure*}[!t] \centering \begin{subfigure}[b]{0.45\textwidth} \centering \includegraphics[width=\textwidth]{Figures/skeleton_video_clip.png} \caption{Spatial-temporal skeleton.} \label{fig:skeleton_rep} \end{subfigure} \hfill \begin{subfigure}[b]{0.45\textwidth} \centering \includegraphics[width=\textwidth]{Figures/array_video_clip.png} \caption{Tensor.} \label{fig:tensor_rep} \end{subfigure} \caption{Video clip representations.} \label{fig:video_rep} \end{figure*} Presently, there are multiple datasets available for research on human action recognition. Among these alternatives, the UCF-101 \cite{Soomro2012}, and the HMDB-51 \cite{Kuehne2011a} datasets are considered to be reference benchmarks. \subsection{UCF-101} The UCF-101 is the most commonly used benchmark human action dataset. Every video sample from this dataset is sourced from YouTube. The clip's duration varies from 1.06 sec to 71.04 sec and has a fixed frame rate of 25 fps and a fixed resolution of 320×240 pixels. This dataset provides a total of 13,320 clips classified into 101 action classes. These classes can be broadly divided into five major subsets: \textit{Human-Object Interaction}, \textit{Body-Motion Only}, \textit{Human-Human Interaction}, \textit{Playing Musical Instruments} and \textit{Sports} \cite{Soomro2012}. \subsection{HMDB-51} Similar to the UCF-101, the Human Motion Database (HMDB) is considered as one of the top 5 most popular datasets for action recognition \cite{Zhang2019b}. Aside from YouTube, the HMDB-51 dataset was collected from a wider range of sources (i.e., movies, Google videos, etc.). For that reason, the height of all the samples was scaled to 240 pixels, and the width has was scaled to maintain the original video ratio. Furthermore, the frame rate was modified to have a fixed value of 30 fps. It provides a total of 6,766 video clips of 51 different classes. These classes can be broadly classified into 5 categories: \textit{General facial actions}, \textit{Facial actions with object manipulation}, \textit{General body movements}, \textit{Body movements with object interaction} and \textit{Body movements for human interaction} \cite{Kuehne2011a}. \subsection{ST-GCN additional layer: the M-Mask} Complex movements can be inferred from a small set of representatives \emph{bright spots} on the joints of the human body \cite{Johansson1973}. However, not all the joints provide the same quality and quantity of information regarding the movement performed. Therefore, it is intuitive to assign a different level of importance to every joint in the skeleton. In the ST-GCN framework, the authors added a mask M (or M-mask) to each layer of the GCN to express the importance of each joint \cite{yan2018spatial}. This mask scales the contribution of each skeleton's joint according to the learned weights of the spatial graph network. According to their results, the proposed M-mask considerably improves their architecture's performance. Therefore, the authors constantly apply it to the ST-GCN network in their experiments. \subsection{Our Contribution} The convolution operation is not explicitly defined on graphs. Suppose a graph with no fixed structure (i.e., the quantity and arrangement of the nodes may vary), label mapping criteria need to be defined to perform the convolution process. For instance, the work of Yan \textit{et al.} in \cite{yan2018spatial} proposed three skeleton partition strategies (Uni-label, distance, and spatial configuration partitioning) to perform action recognition. This strategy was applied using ST-GCN upon the UCF-101 dataset \cite{Zheng2019}. However, to the best of our knowledge, there is no previous evidence of using the ST-GCN model on the HMDB-51 dataset for action recognition. In what follows, we summarise our contributions below: \begin{itemize} \item We present the first results of the ST-GCN model trained on the HMDB-51 dataset for action recognition. Moreover, we have used the previous skeleton extraction information of both the UCF-101 and the HMDB-51 datasets for the experiments. \item We have implemented our proposed partitioning strategies on the ST-GCN model \cite{Alsawadi2021} on the benchmark datasets (UCF-101 and the HMDB-51 datasets). \item We provide a deep analysis of the impact of different batch sizes during training upon the accuracy performance of the output models using the both benchmark datasets. \item Additionally, we have provided the open-source skeleton information of the UCF-101 and HMDB-51 datasets for the research community\footnote{https://github.com/malswadi/skeleton\_ucf\_hmdb}. \end{itemize} The remainder of the paper is structured as follows: in \textbf{Section II}, we present the state-of-the-art skeleton-based systems that utilize the ST-GCN model for action recognition. In \textbf{Section III} we explain the constraints we have used in our experiments. The experimental results are described in depth in \textbf{Section IV}. Finally, \textbf{Section V} presents the summary and discussions. \section{Action recognition using ST-GCN} In order to perform the convolution operation, Yan \textit{et al.} \cite{yan2018spatial} first divided the skeleton into subsets of joints (\textit{i.e., neighbor-sets}). Each of these sets are composed by a \textit{root node} and its adjacent nodes (Fig. \ref{fig:keypoints}). On the other hand, each kernel has a size of $K$ x $K$. In the same research \cite{yan2018spatial}, the authors used their architecture to recognize human actions upon the NTU-RGB+D \cite{Shahroudy2016} and the Kinetics \cite{Kay2017} dataset. They used the skeleton information of both datasets for their training. The NTU-RGB+D \cite{Shahroudy2016} provides the skeleton modality for their data with the main joints of the actors. However, the skeleton data is not available for the Kinetics dataset \cite{Kay2017}. Therefore, they initially extracted the skeleton data with the use of the OpenPose library \cite{Cao2021a} and released this data as the Kinetics-skeleton dataset \cite{yan2018spatial}. Once the skeleton information has been obtained, each video clip is modeled as a tensor (18,3, T), where T represents the length of the video as it is shown in Fig. \ref{fig:tensor_rep}. As a consequence, the data is prepared to perform the convolution process. \subsection{Partitioning strategies} For graphs with no specific order, priority criteria must be set in each neighbor-set to map each joint to a label. Hence, the convolution process can be performed, and network training can be possible. In \cite{yan2018spatial}, three neighbor set partitioning criteria were presented: Uni-labeling, Distance, and Spatial configuration partitioning. In the first approach, the kernel size K = 1. Therefore, all the joints in the neighbor set share the same label (label 0). In the second, the kernel size K = 2. The root node has the top priority (label 0), and the adjacent nodes share the same label (label 1). On the other hand, spatial configuration partitioning is more complex. \subsubsection{Spatial Configuration partitioning} In this approach, the kernel size K = 3 and the center of gravity of the skeleton (average of the values on each joint axis across all the training set) are considered. Mathematically, the mapping for this strategy is defined with the following equation \begin{equation} l_{ti}(v_{tj}) = \left\{ \begin{array}{lcr} 0 & if & r_j=r_i\\ 1 & if & r_j<r_i\\ 2 & if & r_j>r_i \end{array} \right. , \label{eq:Strategy3} \end{equation} where $l_{ti}(v_{tj})$ represents the label mapping for the node $v_{tj}$, $r_j$ is the average value from the root node to the center of gravity and $r_i$ is the average value from the $i_{th}$ node to the center of gravity. Yan \textit{et al.} \cite{yan2018spatial} have reported a maximum performance accuracy on both of the NTU-RGB+D \cite{Shahroudy2016}, and the Kinetics-skeleton \cite{yan2018spatial} datasets using this partitioning strategy.\par There have been multiple action recognition systems using the ST-GCN architecture \cite{Keskes2021, liutwo, Jiang2020, Yang2020}. Zheng \textit{et al.} \cite{Zheng2019} extracted the skeleton from the UCF-101 dataset in a similar manner as Yan \textit{et. al.} \cite{yan2018spatial} with the Kinetics \cite{Kay2017} and obtained 50.53\% top-1 accuracy using the spatial configuration partitioning for label mapping. Some additional hand-craft work needed to be done. They selected only the video clips on which the skeleton was detected during the first 250 frames.\par Recently, we were able to improve the ST-GCN performance upon the NTU-RGB+D \cite{Shahroudy2016} and the Kinetics \cite{Kay2017} benchmarks in \cite{Alsawadi2021}. As the base model \cite{yan2018spatial} proposed, we defined each neighbor set to contain a root node with its adjacent nodes. Nevertheless, in our previous work \cite{Alsawadi2021}, we considered a kernel size K=4. Thus, each of the nodes in the neighbor sets owns a separate label. The root node was set to have the highest priority in every split strategy (label 0). However, to define which of the adjacent nodes in the neighbor set has the highest priority in the label mapping, we have introduced three novel partitioning strategies: the \textit{full distance}, \textit{connection} and \textit{index splits}. \subsubsection{Full distance split} In this strategy, we took the contribution of the spatial configuration partitioning from Yan \textit{et al.} \cite{yan2018spatial} one step further. We considered the distance from \textit{every joint} in the neighbor set to the center of gravity of the skeleton. As it is shown in Fig. \ref{fig:full_distance}, the nearest the node is to the center of gravity, the highest priority it is assigned to it \cite{Alsawadi2021}. In the figure, the joint labeled as \textit{B} has the highest priority among the adjacent nodes because of its closeness to the center of gravity. To describe this strategy mathematically, a set $\mathcal{F}$ is defined. This set contains the Euclidean distances of the \textit{i}-th adjacent node $u_{ti}$ (of the root node $u_{tj}$) with respect to the center of gravity of the skeleton, sorted in ascending order as \begin{equation} \mathcal{F}=\{f_{m|m=1,\cdots,N}\} \end{equation} where $N$ is the number of adjacent nodes to the root node $u_{tj}$. With this auxiliary set in place, the label mapping can be defined using the Eq. \ref{eq:full_distance}. \begin{equation} l_{ti}(u_{tj}) = \left\{ \begin{array}{lcr} 0 &if& |u_{ti}-cg|_{2}=x_{r}\\ m &if& |u_{ti}-cg|_{2}=f_{m} \end{array} \right. , \label{eq:full_distance} \end{equation} where $l_{ti}$ represents the label map for each joint $u_{ti}$ in the neighbor set of the root node $u_{tj}$, $x_{r}$ is the Euclidean distance from the root node $u_{tj}$ to the center of gravity of the skeleton. \begin{figure}[h] \centering \includegraphics[width=0.35\textwidth]{Figures/full_distance.png} \caption{Full distance split.} \label{fig:full_distance} \end{figure} \subsubsection{Connection split} For this partitioning criteria, the degree of each vertex (i.e., the joints) of the skeleton graph is considered. The higher degree, the higher priority \cite{Alsawadi2021}. For instance, consider the skeleton graph shown in Fig. \ref{fig:connection}. In the figure are indicated the connections of each of the adjacent nodes in the neighbor set. For this example, the root node has the top priority (label 0), and the node labeled as \textit{B} has the next priority (label 1). Given that both nodes \textit{A} and \textit{C} have the same degree, we considered them with the same priority; hence, their priority is set randomly. \begin{figure}[h] \centering \includegraphics[width=0.35\textwidth]{Figures/connection.png} \caption{Connection split.} \label{fig:connection} \end{figure} To define the label mapping, we describe a set $\mathcal{C}$ as the degree values of each of the $N$ adjacent nodes of the root node sorted in descending order as follows \begin{equation} \mathcal{C}=\{c_{m|m=1,\cdots,N}\} \end{equation} Given the set $\mathcal{C}$ defined, the label mapping can be obtained using Eq. \ref{eq:index_eq}. \begin{equation} l_{ti}(u_{tj}) = \left\{ \begin{array}{lcr} 0 &if&d(u_{ti})=d_{r}\\ m &if&d(u_{ti})=d_{m}\\ \end{array} \right. , \label{eq:index_eq} \end{equation} where $l_{ti}$ represents the label map for each joint $u_{ti}$ in the neighbor set of the root node $u_{tj}$ and $d_{r}$ is the degree corresponding the root node. \subsubsection{Index split} For this strategy, we considered the OpenPose \cite{Cao2021a} output keypoints shown in Fig. \ref{fig:keypoints}. The priority criteria are defined as follows: the smallest value of the keypoint index, the highest priority \cite{Alsawadi2021}. For instance, consider the neighbor set shown in Fig. \ref{fig:index}. Like the other partition strategies, the highest priority is assigned to the root node (label 0). Subsequently, the adjacent with the highest priority is given to the node labeled as \textit{B} because its keypoint index is the smallest (index 1). Finally, the node labeled as \textit{A} and the node labeled as \textit{C} have the second and third priority, respectively. \begin{figure}[h] \centering \includegraphics[width=0.35\textwidth]{Figures/index.png} \caption{Index split.} \label{fig:index} \end{figure} Similar to the other split strategy, we defined an auxiliary set $\mathcal{P}$ with the keypoint index values of the adjacent nodes. \begin{equation} \mathcal{P}=\{p_{m|m=1,\cdots,N}\} \end{equation} The values of $\mathcal{P}$ are ascendant ordered. Then, the label mapping is obtained using Eq. \ref{eq:connection_eq}. \begin{equation} l_{ti}(u_{tj}) = \left\{ \begin{array}{lcr} 0 &if&ind(u_{ti})=in_{r}\\ m &if&ind(u_{ti})=p_m\\ \end{array} \right. , \label{eq:connection_eq} \end{equation} where $l_{ti}$ and $ind(u_{ti})$ represent the label map and the index keypoint value of the $i_{th}$ joint, respectively; and $in_{r}$ is the index of the keypoint corresponding to the root node $u_{tj}$. \section{Experimental settings} Given that the skeleton representation of the actors is not provided for either the UCF-101 \cite{Soomro2012} or the HMDB-51 \cite{Kuehne2011a}, we first extract that skeleton representation from both datasets. Similarly to \cite{yan2018spatial}, we used the Open-Pose library to extract the skeleton data for our evaluation. The library installation was oriented to be compatible with the Ubuntu 18.04 environment.\par We followed the experiment guidelines provided in \cite{yan2018spatial}. First, the resolution of each video sample has been resized into a fixed dimension of 340 × 256 pixels. Second, the set of resized image frames of the video samples is input to the Open-Pose algorithm. Third, due to the variability of the duration of each clip, a fixed duration of 300 frames has been proposed. Therefore, if any video clip has less than 300 frames, we repeat the initial frames until we reach the amount needed. Otherwise, if the video clip exceeds the frame number, we trim it. Consequently, the Spatio-temporal information of the skeleton of each video sample can be represented as a tensor with shape (18, 3, 300). By setting the \textit{T} value to 300, our output tensor is illustrated in Fig. \ref{fig:tensor_rep}. In the fourth step, we considered the joint recognition score provided by the Open-Pose algorithm (i.e., the \textit{C} value). After several experiments, we concluded to consider for training only those videos with more than 50\% skeleton joint recognition.\par Additionally, we only considered those samples with a maximum of two people performing the action. Finally, the Spatio-temporal skeleton data of the UCF-101 and the HMDB-51 video that fulfilled those quality criteria is collected during the \textit{Data extraction} stage. We have iterated through the video clips of the datasets and saved the skeleton information as JSON files. An independent JSON file has been exported for each video sample. Thus, the outcome of this process are 13,320 and 6,766 JSON files with the skeleton information of the UCF-101 and the HMDB-51 datasets, respectively. These files are publicly available for the research community. \footnotemark[\value{footnote}] \subsection{Training Details} We utilized the PyTorch framework \cite{Paszke2017} for deep learning modelling to execute our experiments. The experiment process is composed in 3 stages: \textit{Data Splitting}, \textit{ST-GCN Model Setup} and the \textit{Model Training}. The first stage divides each of the datasets mentioned above into two subsets: the training and the validation sets. For our experiments, we considered a 3:1 relation for training and validation split, respectively. Then, the second stage aims to prepare the ST-GCN architecture to be trained using the spatial configuration partitioning strategy proposed by Yan \textit{et al.} \cite{yan2018spatial} and also with the use of the our previously proposed split processes presented in \cite{Alsawadi2021}. \par Finally, in the \textit{Model Training} stage, we performed the experiments of the implementation of the ST-GCN model using the spatial configuration partitioning \cite{yan2018spatial}. During this stage, we utilized the enhanced split strategies proposed in \cite{Alsawadi2021} in our experiments to find the partitioning approach that offered the best performance in terms of accuracy. To provide a valid comparison, we included the M-mask layer in the architecture during experimentation. Additionally, we perform a further analysis without the M-mask implementation. Every model has been trained using the stochastic gradient descent (SGD) with learning rate decay as optimization algorithm. Also, all the models training started with a learning rate value of 0.1. The models were trained for 80 epochs and the learning rate decays by a factor of 0.1 every \(10^{th}\) epoch, starting from the epoch number 20. Additionally, in order to avoid overfitting on the datasets, a weight decay value of 0.0001 has been considered.\par One experiment setting criteria was to find the optimal batch size. This hyperparameter allows the model to adjust its parameters during optimization with respect to a small subset of training samples called \textit{mini batches} \cite{Goodfellow-et-al-2016}. The optimization algorithm requires a lower computational cost to update the weights by training the network in mini-batches. If the batch size is too small, the learned parameters in each step of the gradient descent tend to be less robust, given that the weights were updated from a set of samples with minor variation; if the batch size is too big, the computational cost increases accordingly. Therefore, we proposed this hyper-parameter to be one of the experiment's definition criteria. We performed the experiments using different batch sizes values. These vary from 8, 16, 32, 64, and 128. \section{Results} The experiment's outcome for each benchmark dataset is presented separately in different sections. The results correspond to the models with the best performance in terms of accuracy. The accuracy values shown were obtained using top-1 criteria. \subsection{UCF-101} As mentioned in the previous section, we vary the implemented partition strategy in the ST-GCN architecture. Additionally, we performed experiments with and without the implementation of the M-mask. In Table \ref{table:batch_ucf_performance} are shown the results of these experiments upon the UCF-101. The "Y" ("Yes") and "N" ("No") values in the "M-mask" column represent whether the M-mask layer was implemented or not in that experiment, respectively. It can be noticed that, in most experiments, the output model tends to be more robust as the batch size increases. \begin{table}[ht] \caption{Experiments performance upon UCF-101} \centering \begin{tabular}{c c c c} \hline\hline \centering Method & Batch size & M-mask & Accuracy \\ [0.5ex] \hline \centering Spatial C.P. & 8 & Y & 46.42\% \\ & & N & 65.36\% \\ & 16 & Y & 68.71\% \\ & & N & 65.89\% \\ & 32 & Y & 68.96\% \\ & & N & 68.55\% \\ & 64 & Y & 70.47\% \\ & & N & 68.18\% \\ & \textbf{128} & \textbf{N} & \textbf{70.72\%} \\[1ex] \hline \centering Full Distance Split & 8 & Y & 48.51\% \\ & & N & 58.73\% \\ & 16 & Y & 61.02\% \\ & & N & 67.89\% \\ & 32 & Y & 69.16\% \\ & & N & 66.30\% \\ & \textbf{64} & \textbf{Y} & \textbf{70.43}\% \\ & & N & 68.59\% \\ & 128 & N & 66.91\% \\[1ex] \hline \centering Connection Split & 8 & Y & 63.03\% \\ & & N & 63.48\% \\ & 16 & Y & 64.46\% \\ & & N & 62.99\% \\ & 32 & Y & 70.88\% \\ & & N & 69.41\% \\ & \textbf{64} & \textbf{Y} & \textbf{70.96\%} \\ & & N & 68.18\% \\ & 128 & N & 70.35\% \\[1ex] \hline \centering Index Split & 8 & Y & 56.61\% \\ & & N & 58.24\% \\ & 16 & Y & 69.33\% \\ & & N & 62.70\% \\ & 32 & Y & 68.34\% \\ & & N & 68.34\% \\ & 64 & Y & 72.31\% \\ & & N & 72.19\% \\ & \textbf{128} & \textbf{N} & \textbf{73.25\%} \\ [1ex] \hline \end{tabular} \label{table:batch_ucf_performance} \end{table} By analysing the output values of the experiments shown in Table \ref{table:batch_ucf_performance}, we have created Table \ref{table:m_mask_ucf_performance} with the results with the M-mask layer proposed by Yan \textit{et al.} \cite{yan2018spatial}. To provide a comparative, we have also included the outcome of the previous ST-GCN implementation performed by Zheng \textit{et al.} \cite{Zheng2019} in this table. \begin{table}[ht] \caption{UCF-101 performance using M-mask} \centering \begin{tabular}{c p{2.7cm} c} \hline\hline & \centering Method & Accuracy \\ [0.5ex] \hline ST-GCN & \centering Spatial Configuration Partitioning & 70.47\% \\ Zheng \textit{et al.} \cite{Zheng2019} & \centering Spatial Configuration Partitioning & 50.53\% \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Full Distance Split & 70.43\% \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Connection Split & 70.96\% \\ \textbf{Alsawadi and Rio \cite{Alsawadi2021}} & \centering \textbf{Index Split} & \textbf{72.31}\% \\ [1ex] \hline \end{tabular} \label{table:m_mask_ucf_performance} \end{table} The model with M-mask implementation that achieved the best accuracy performance was trained using a 64 batch size and utilized the index split partitioning strategy. It has achieved 1.84\% of accuracy improvement with respect to the spatial configuration partitioning approach proposed by Yan \textit{et al.} in \cite{yan2018spatial}. Moreover, this model enhances the previous state-of-the-art results by 21.78\%. \begin{table}[ht] \caption{UCF-101 performance without M-mask} \centering \begin{tabular}{c p{2.7cm} c} \hline\hline & \centering Method & Accuracy \\ [0.5ex] \hline ST-GCN & \centering Spatial Configuration Partitioning & 70.72\% \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Full Distance Split & 68.59\% \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Connection Split & 70.35\% \\ \textbf{Alsawadi and Rio \cite{Alsawadi2021}} & \centering \textbf{Index Split} & \textbf{73.25\%} \\ [1ex] \hline \end{tabular} \label{table:no_m_mask_ucf_performance} \end{table} On the other hand, Table \ref{table:no_m_mask_ucf_performance} shows that the accuracy performance increased when the M-mask implementation is not considered in the ST-GCN architecture. Again, the index split partitioning strategy allowed the ST-GCN model to achieve the best accuracy performance. For this model, a batch size of 128 was considered. This solution enhanced the spatial configuration partitioning model approach proposed by Yan \textit{et al.} in \cite{yan2018spatial} by 2.53\%.\par Therefore, we can reach the highest accuracy performance by using the index split partitioning approach upon the ST-GCN architecture without the M-mask implementation. We have evaluated the model for each of the five epochs. The outcome of this model during training is shown in Fig. \ref{fig:ucf_index}. The evaluation of the training and the test set are shown in red and blue curves, respectively. \begin{figure}[h] \centering \includegraphics[width=0.45\textwidth]{Figures/acc_UCF_Cus2NoIm_128_128_20211020104844.png} \caption{Best UCF-101 Model Training Process.} \label{fig:ucf_index} \end{figure} \subsection{HMDB-51} The results corresponding to the different experiments upon the HMDB-51 dataset are shown in Table \ref{table:batch_hmdb_performance}. Similar to the outcome obtained in Table \ref{table:batch_ucf_performance}, in most of the experiments, the accuracy performance tends to improve as the batch size increases. \begin{table}[ht] \caption{Experiments performance upon HMDB-51} \centering \begin{tabular}{c c c c} \hline\hline \centering Method & Batch size & M-mask & Accuracy \\ [0.5ex] \hline \centering Spatial C.P. & 8 & Y & 37.34\% \\ & & N & 40.77\% \\ & 16 & Y & 44.39\% \\ & & N & 41.08\% \\ & 32 & Y & 43.89\% \\ & & N & 45.45\% \\ & \textbf{64} & Y & 45.64\% \\ & & \textbf{N} & \textbf{46.82\%} \\ & 128 & N & 44.64\% \\[1ex] \hline \centering Full Distance Split & 8 & Y & 41.77\% \\ & & N & 33.23\% \\ & 16 & Y & 38.97\% \\ & & N & 42.08\% \\ & 32 & Y & 33.23\% \\ & & N & 45.51\% \\ & \textbf{64} & Y & 42.02\% \\ & & \textbf{N} & \textbf{45.82\%} \\ & 128 & N & 45.26\% \\[1ex] \hline \centering Connection Split & 8 & Y & 23.63\% \\ & & N & 39.34\% \\ & 16 & Y & 43.27\% \\ & & N & 40.84\% \\ & 32 & Y & 40.52\% \\ & & N & 41.52\% \\ & 64 & Y & 32.29\% \\ & & N & 47.19\% \\ & \textbf{128} & \textbf{N} & \textbf{48.88\%} \\[1ex] \hline \centering Index Split & 8 & Y & 38.97\% \\ & & N & 34.91\% \\ & 16 & Y & 35.47\% \\ & & N & 46.57\% \\ & 32 & Y & 43.20\% \\ & & N & 45.51\% \\ & \textbf{64} & \textbf{Y} & \textbf{47.69\%} \\ & & N & 43.39\% \\ & 128 & N & 46.51\% \\ [1ex] \hline \end{tabular} \label{table:batch_hmdb_performance} \end{table} There is no previous application of the ST-GCN model upon the HMDB-51 dataset to the author's knowledge. Hence, the table only contains the results of the present study using the different partitioning strategies. \begin{table}[ht] \caption{HMDB-51 performance using M-mask} \centering \begin{tabular}{c p{2.7cm} c} \hline\hline & \centering Method & Accuracy \\ [0.5ex] \hline ST-GCN & \centering Spatial Configuration Partitioning & 45.64\% \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Full Distance Split & 42.02\% \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Connection Split & 45.89\% \\ \textbf{Alsawadi and Rio \cite{Alsawadi2021}} & \centering \textbf{Index Split} & \textbf{47.69\%} \\ [1ex] \hline \end{tabular} \label{table:m_mask_hmdb_performance} \end{table} Table \ref{table:m_mask_hmdb_performance} contains the highest performance achieved with each partitioning strategy with M-mask implementation upon the HMDB-51 dataset. As indicated in bold letters, the highest value was performed using the index split partition strategy. This model was trained by choosing a training batch size of 64. It has reached more than 2\% accuracy improvement with respect to the spatial configuration partitioning proposed by Yan \textit{et al.} in \cite{yan2018spatial}. Additionally, it can be noticed that also the connection split outperformed the spatial configuration partitioning outcome. \begin{table}[ht] \caption{HMDB-51 performance without M-mask} \centering \begin{tabular}{c p{2.7cm} c} \hline\hline &\centering Method & Accuracy \\ [0.5ex] \hline ST-GCN & \centering Spatial Configuration Partitioning & 46.82\% \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Full Distance Split & 45.82\% \\ \textbf{Alsawadi and Rio \cite{Alsawadi2021}} & \centering \textbf{Connection Split} & \textbf{48.88\%} \\ Alsawadi and Rio \cite{Alsawadi2021} & \centering Index Split & 46.57\% \\ [1ex] \hline \end{tabular} \label{table:no_m_mask_hmdb_performance} \end{table} In the experiments with no M-mask implementation shown in Table \ref{table:no_m_mask_hmdb_performance}. The partitioning strategy that achieved the highest accuracy performance was the connection split. This model was trained using a batch size of 128. The result obtained with this model outperformed with more than 2\% the outcome of the ST-GCN architecture without M-mask implementation using the spatial configuration partitioning. The training process performance of this model is shown in Fig. \ref{fig:hmdb_connection}. As Fig. \ref{fig:ucf_index}, the evaluation upon the training and the test set is shown in the colours red and blue, respectively. We have tested the performance of the trained model for every five epochs. \begin{figure}[h] \centering \includegraphics[width=0.45\textwidth]{Figures/acc_HMDB_Cus1NoIm.png} \caption{Best HMDB-51 Model Training Process.} \label{fig:hmdb_connection} \end{figure} \section{Conclusion} In this paper, we have proposed novel action recognition method using ST-GCN model by exploiting partitioning strategies: \textit{spatial configuration paritioning}, \textit{full distance split}, \textit{connection split} and \textit{index split}. We have presented the first implementation of the ST-GCN framework on the HMDB-51 \cite{Kuehne2011a} dataset achieving 48.88\% top-1 accuracy by using the connection split partitioning approach. Our proposal outperforms the state-of-the-art using the ST-GCN framework on the UCF-101. Our results further show performance superiority over the most recent related work proposed in \cite{Alsawadi2021} with much lower training and computational inference costs and structural simplicity.\par The difference in the amount of training data impacted considerably in the final performance. The UCF-101 provides more than twice the amount of samples for training than the HMDB-51 counterpart. Therefore, the learning achieved with this dataset is more robust to changes in the input data than the model obtained with the second set. This is clearly demonstrated in the accuracy result values of Tables \ref{table:batch_ucf_performance} and \ref{table:batch_hmdb_performance}. As future work, we propose increasing the size of nodes in the neighbor sets to capture the relationships between joints that are distant from each other. We believe that the more details we can capture of each movement, the more we can model the action to increase the overall accuracy. \bibliographystyle{IEEEtran}
{'timestamp': '2021-11-08T02:01:51', 'yymm': '2111', 'arxiv_id': '2111.03106', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03106'}
arxiv
\section{Introduction} \label{sec:intro} One of the main objectives in computer vision is to develop systems that can ``see'' the world \cite{marr1982vision,tarr2002visual}. Here we tackle the problem of single image holistic understanding and 3D reconstruction, which is deeply rooted in decades of development in computer vision and photogrammetry but became practically feasible only recently thanks to the exploding growth in modeling, computing \cite{krizhevsky2012imagenet,szegedy2015going,simonyan2015very,he2016deep,goodfellow2016deep,xie2017aggregated}, and large-scale datasets \cite{deng2009imagenet,Lin2014COCO,Cordts2016Cityscapes,chang2015shapenet,fu20203dfuture}. \begin{table*}[!ht] \vspace{-2mm} \begin{center} \caption{\small Comparison for different 3D reconstruction methods. Mesh-RCNN \cite{gkioxari2019meshrcnn} only allows single-instance per image during training, but it will enable outputs of multi-object components at inference time. Nevertheless, efforts are still required to allow for the multi-object module in an end-to-end pipeline for training and evaluation. } \label{tab:method_comparison} \scalebox{0.90}{ \begin{tabular}{ccccccc} \hline Method &3D & Single & Layout & Panoptic & Outdoor &Multiple \\ & & image & 3D & segmentation & scenes & objects \\ \hline \cite{zhang2018genre,kanazawa2018end,groueix2018atlas,xu2019disn} & \cmark & \cmark & & & &\\ \cite{gkioxari2019meshrcnn} & \cmark & \cmark & & & & $\dagger$\\ \cite{han2004automatic} & \cmark & \cmark & & & \cmark & \\ \cite{Tulsiani17factored3d,zou2018layoutnet,huang2018cooperative,nie2020total3d} & \cmark & \cmark & \cmark & & & \cmark\\ \cite{Li2018megadepth} & \cmark & \cmark & & & \cmark &\\ \cite{Alhashim2018densedepth}&\cmark&\cmark&\cmark& &\cmark&\\ \cite{pollefeys1999self,pollefeys2008detailed} & \cmark & &\cmark & & \cmark & \cmark\\ \cite{Kirillov2018panoptic,Kirillov2019fpn,xiong19upsnet,Lazarow2019ocfusion} & & \cmark & & \cmark & \cmark & \cmark\\ \hline {\small Panoptic3DParsing (ours)} & \cmark & \cmark & \cmark & \cmark & \cmark & \cmark\\ \hline \end{tabular} } \end{center} \vspace{-3mm} \end{table*} We name our system single image panoptic 3D parsing (Panoptic3D). It takes in a single natural RGB image and jointly performs dense image semantic labeling \cite{shotton2006textonboost,tu2008auto,long2015fully}, object detection \cite{Ren2015FasterRCNN}, instance segmentation \cite{he2017mask}, depth estimation \cite{Li2018megadepth, Alhashim2018densedepth}, object shape 3D reconstruction \cite{zhang2018genre, gkioxari2019meshrcnn}, and 3D layout estimation \cite{Tulsiani17factored3d} from a single natural RGB image. Figure \ref{fig:teaser} gives an illustration for the pipeline where a 3D scene is estimated from a single-view RGB image with the background layout (``stuff'') segmented and the individual foreground instances (``things'') detected, segmented, and fully reconstructed. A closely related work to our Panoptic3D is the recent Total3DUnderstanding method \cite{nie2020total3d} where 3D layout and instance 3D meshes are reconstructed for an indoor input image. However, Total3DUnderstanding \cite{nie2020total3d} does not perform panoptic segmentation \cite{Kirillov2018panoptic}/image parsing \cite{tu2005image} and is limited to indoor scenes. We briefly discuss the literature from two main angles: 1). 3D reconstruction, particularly from a single-view RGB image; and 2). image understanding, particularly for panoptic segmentation \cite{Kirillov2018panoptic} and image parsing \cite{tu2005image}. 3D reconstruction is an important area in photogrammetry \cite{linder2009digital,colomina2014unmanned} and computer vision \cite{hartley2003multiple,ma2012invitation, ullman1979interpretation,brown2003advances,pollefeys1999self,kutulakos2000theory,pollefeys2008detailed,szeliski2010computer}. We limit our scope to single RGB image input for 3D instance reconstruction \cite{wu2015shapenets,zhang2018genre,wang2018pixel2mesh,groueix2018atlas,kanazawa2018end,xu2019disn,chen2020topology} and 3D layout generation \cite{Tulsiani17factored3d,zou2018layoutnet}. There is a renewed interest in performing holistic image and object segmentation (Image Parsing \cite{tu2005image}), called panoptic segmentation \cite{Kirillov2018panoptic,Kirillov2019fpn,xiong19upsnet,Lazarow2019ocfusion}, where the background regions (``stuff'') are labeled with the foreground objects (``things'') detected. Our panoptic 3D parsing method is a system that gives holistic 3D scene reconstruction and understanding for an input image. It includes multiple tasks such as depth estimation, panoptic segmentation, and object instance reconstruction. In Section \ref{sec:related}, we discuss the motivations for the individual modules. A comparison between the existing methods and ours is illustrated in Table \ref{tab:method_comparison}. The contributions of our work are summarized below. \begin{itemize} \setlength\itemsep{0mm} \item We present a stage-wise system for panoptic 3D parsing, Panoptic3D (stage-wise), by comabatting the issue where full annotations for panoptic segmentation, depth, and 3D instances are absent. To the best of our knowledge, this is the first system of its kind to perform joint panoptic segmentation and holistic 3D reconstruction for the generic indoor and outdoor scenes from a single RGB image. \item In addition, we have developed an end-to-end pipeline for panoptic 3D parsing, Panoptic3D (end-to-end), where datasets have complete segmentation and 3D reconstruction ground-truth annotations. \end{itemize} Observing the experiments, we show encouraging results for indoor \cite{fu20203dfuture} and the outdoor scenes for the natural scenes \cite{Lin2014COCO,Cordts2016Cityscapes}. \section{Related Work \label{sec:related}} Table \ref{tab:method_comparison} shows a comparison with related work. Our panoptic 3D parsing framework has the most complete set of properties and is more general than the competing methods. Next, we discuss related work below in details. \noindent{\bf Single-view 3D scene reconstruction}. Single image 3D reconstruction has a long history \cite{roberts1963machine,han2004automatic,Tulsiani17factored3d,zou2018layoutnet,huang2018cooperative,nie2020total3d}. The work in\cite{huang2018cooperative} jointly predicts 3D layout bounding box, 3D object bounding box, and camera intrinsics without any geometric reconstruction for indoor scenes. Factored3D \cite{Tulsiani17factored3d} is closely related to our work, which combines indoor scene layout (amodal depth) with 3D instance reconstructions without much abstraction. Still, no label is predicted for the scene layout (``stuff'') \cite{Tulsiani17factored3d}, and the instance object reconstruction tends to overfit the canonical shape of known categories. Total3DUnderstanding \cite{nie2020total3d} infers a box layout and has produced 3D reconstruction inference results on natural indoor images. However, as discussed before, these methods do not perform holistic 3D reconstruction for natural outdoor scenes or panoptic segmentation in general. \noindent{\bf Single image depth estimation}. David Marr pioneered the 2.5D depth representation \cite{marr1982vision}. Depth estimation from a single image can be performed in a supervised way and has been extensively studied in the literature \cite{Saxena2009make3d,Eigen2014depth}. Development in deep learning \cite{long2015fully} has expedited the progress for depth estimation \cite{Bansal2016normal,Li2018megadepth}. In our work, we adopt a relatively lightweight inverse depth prediction module from Factored3D \cite{Tulsiani17factored3d} and regress the loss jointly with 3D reconstruction and panoptic segmentation. \noindent {\bf Single-view single object reconstruction}. Single image single object 3D reconstruction can typically be divided into volume-based \cite{wu2015shapenets,zhang2018genre,chen2020topology}, mesh-based \cite{wang2018pixel2mesh,groueix2018atlas,kanazawa2018end}, and implicit-function-based \cite{chen2019learning, xu2019disn} methods. In this paper, we adopt the detection and shape reconstruction branch from Mesh R-CNN \cite{gkioxari2019meshrcnn} for multi-object prediction . Building on top of it, we can perform supervised end-to-end single image panoptic 3D parsing. We also adopt unseen class reconstruction, GenRe \cite{zhang2018genre}, for multi-object reconstruction for natural image reconstruction when well-aligned ground truth 3D mesh models are not available. \noindent{\bf Panoptic and instance segmentation}. Panoptic segmentation \cite{Kirillov2018panoptic} or image parsing \cite{tu2005image} combines semantic segmentation and instance detection/segmentation. In our work, we build our panoptic head by referencing the end-to-end structure of UPSNet \cite{xiong19upsnet}. Additionally, we predict the 3D reconstruction of instances for each corresponding instance mask. However, the instance segmentation in panoptic segmentation is occluded. In comparison, amodal instance segmentation predicts un-occluded instance masks for ``things''. In this work, we generate both amodal as well as panoptic segmentation annotations from the 3D-FRONT dataset. This dataset enables the network to jointly perform 3D ``things'' reconstruction as well as panoptic segmentation. In the stage-wise pipeline, we utilize the work from Zhan \etal. \cite{zhan2020self} to better assist 3D reconstruction on natural images. \section{Method} We design our networks with the following goals in mind: 1). The network should be generalizable to both indoor and outdoor environments; 2). Datasets with various levels of annotations should be able to utilize the framework with simple replacement; 3). The segmentation masks should align with the reconstruction from the input view. We will first introduce our stage-wise system, Panoptic3D (stage-wise) and show that it can process natural images without corresponding 3D annotations in training. Then, we will present our end-to-end network, Panoptic3D (end-to-end). \subsection{Stage-wise Panoptic3D} \begin{figure}[!ht] \vspace{-2mm} \centering \includegraphics[width=\linewidth]{hybrid_framework.png} \caption{Our stage-wise system, Panoptic3D (stage-wise). We adopt DenseDepth \cite{Alhashim2018densedepth} for depth prediction, UPSNet \cite{xiong19upsnet} for panoptic segmentation, a de-occlusion network \cite{zhan2020self} for amodal mask completion, and GenRe \cite{zhang2018genre} to perform instance-based single image 3D reconstruction. The alignment module in Panoptic3D (stage-wise) outputs the image on the bottom.} \label{fig:networkstructure2} \end{figure} We present our stage-wise system, Panoptic3D (stage-wise), in Figure~\ref{fig:networkstructure2}. We design this system for natural image datasets that contain well-annotated panoptic segmentation information but lack 3D information, such as COCO \cite{Lin2014COCO} and Cityscapes \cite{Cordts2016Cityscapes}. This stage-wise system contains four main parts: 1). Instance and panoptic segmentation network. 2). Instance amodal completion network. 3). Single object 3D reconstruction network for unseen classes. 4). Single-image depth prediction network. We take advantage of the state-of-art panoptic segmentation system, UPSNet \cite{xiong19upsnet}, scene de-occlusion system \cite{zhan2020self}, depth prediction system, DenseDepth \cite{Alhashim2018densedepth}, and unseen class object reconstruction networks \cite{zhang2018genre} and integrate them into a single pipeline. This Panoptic3D (stage-wise) framework takes an RGB image and predicts the panoptic 3D parsing of the scene in point cloud (for ``stuff'') and meshes (for `` things''). The implementation details are as follows: the network first takes panoptic results from UPSNet and depth estimation from DenseDepth. It then passes the modal masks to the de-occlusion net to acquire amodal masks. We use GenRe to reconstruct the instance meshes based on the amodal masks. The module then maps panoptic labels to depth pixels and uses empirically estimated camera intrinsics estimation to inverse project depth into point clouds. Since GenRe \cite{zhang2018genre} only predicts normalized meshes centering at the origin, the final module aligns individual shapes using depth estimation in the z-direction and the mask in the x-y direction. The module takes the mean of the $98th$ percentile and the $2nd$ percentile of the filtered and sorted per-pixel depth prediction within the predicted mask region to estimate the z center depth of each object. Finally, it places meshes and depth point cloud in the same coordinate system to render the panoptic 3D parsing results. The general inference time is 2.4 seconds per image on one NVIDIA Titan X GPU. \subsection{End-to-end Panoptic3D} \begin{figure*}[!ht] \centering \includegraphics[width=0.9\textwidth]{end-2-end.png} \caption{Network architecture for our Panoptic3D (end-to-end) pipeline. dz: means depth extent. The red stop sign indicates that only predictions with centered ground truth shapes are used for regression during training. } \label{fig:networkstructure1} \vspace{-2mm} \end{figure*} The overview of the end-to-end network structure, Panoptic3D (end-to-end), is shown in Figure~\ref{fig:networkstructure1}. Similar to Panoptic3D (stage-wise), Panoptic3D (end-to-end) also has four main components: 1). instance segmentation head. 2). multi-object training enabled shape heads. 3). panoptic segmentation head. 4). ``stuff'' depth and relative object z center prediction branch. The entire network is trained end-to-end and can jointly predict amodal instance, semantic, and panoptic segmentation, ``stuff'' depth, and ``things'' reconstruction in 3D. Our design ideas are as follows. For the panoptic 3D prediction, we predict ``stuff'' depth instead of box representation because it is not easily generalizable to scenes with other ``stuff'' categories, such as windows, doors, rugs, etc., and it does not apply to outdoor environments. Taking advantage of the advanced development in 2D panoptic segmentation, we first predict 2D panoptic segmentation and then align ``stuff'' segmentation with the depth prediction. We predict that amodal ``stuff'' prediction would significantly improve the panoptic 3D parsing task for future works. For multi-object 3D reconstruction, we first enable multi-object training and evaluation for the baseline network. For joint training with panoptic segmentation, we mainly address the following three challenges: 1). With multiple objects in a scene, mesh shapes that are too close to the camera may have a negative z-center, not tolerated in end-to-end detection and reconstruction baseline model by design. 2). For objects that appear to be cut-off by the camera view (non-centered/boundary objects) or too close to the camera, transformation to camera coordinate will deform ground truth 3D voxel and mesh into a shape that contain infinitely far points, preventing the network from converging. One approach would be to cut the ground truth shapes to be within the camera frustum. However, this may result in unnatural edge connections, and the preprocessing step is time-consuming. Instead, we introduce a partial loss. We first detect and mark objects occluded by image boundaries (non-centered/boundary objects) and exclude their loss for shape-related regressions. For example, we use an indicator function $\mathds{1}(\cdot)$ to return 1 for centered objects and 0 for boundary objects. The final loss per batch is defined as $\mathcal{L} = \mathcal{L}_{mask}$\cite{he2017mask} $+ \mathcal{L}_{box}$ \cite{he2017mask} $+ \mathcal{L}_{class}$ \cite{he2017mask} $+ \mathcal{L}_{panoptic}$ \cite{xiong19upsnet}$ + \mathcal{L}_{semantic}$ \cite{Kirillov2019fpn} $+ \mathcal{L}_{depth}$ \cite{Tulsiani17factored3d} $+ \mathds{1} \cdot (\mathcal{L}_{dz}$ \cite{gkioxari2019meshrcnn} $+ \mathcal{L}_{zc} + \mathcal{L}_{voxel}$ \cite{gkioxari2019meshrcnn} $+ \mathcal{L}_{mesh}$ \cite{gkioxari2019meshrcnn}$)$. For depth, we use a simple U-Net network structure to predict inverse ``stuff'' depth, which is adopted from Factored3D \cite{Tulsiani17factored3d} because it is relatively lightweight. In addition to depth, to assist the positioning of objects relative to their environment, we add an inverse z center prediction head to align predicted objects with the predicted layout or depth map in 3D. The z center is defined as $z_c$ in $\bar{dz} = \frac{d_z}{z_c} \cdot \frac{f}{h}$, where $\bar{dz}$ is defined as the scale-normalized depth extent \cite{gkioxari2019meshrcnn}, $h$ is the height of the object's bounding box, $f$ is the focal length, $d_z$ is the depth extent. Our z center head predicts the inverse $z_c$, which is the object's center in the z-axis of the camera coordinate system. In summary, the Panoptic3D (end-to-end) network uses a ResNet and an FPN network as our backbone for detection, along with an FPN-based semantic head to assist the 2D panoptic prediction, an inverse z center head in predicting object centers relative to inverse depth prediction produced by the depth branch, and enables multi-object training and evaluation for the shape heads. \begin{table*}[!ht] \centering \caption{Available datasets comparison. More comparison is available in \cite{fu20203dfuture}. The last row shows the panoptic 3D 3D-FRONT dataset rendered and annotated by us.} \label{tab:inhouse_dataset} \scalebox{0.9}{ \begin{tabular}[width=\linewidth]{cccccccc} \hline Dataset & Instance & Semantic & Panoptic &Depth & 3D ``things'' & 3D ``stuff'' & Alignment\\ \hline SUN-RGBD\cite{song2014sunrgbd} &\cmark&\cmark&-&\cmark&0&-&-\\ AI2Thor\cite{Kolve2017AI2THORAn}&\cmark&\cmark&\cmark&\cmark&100&\cmark&\cmark\\ ScanNet\cite{dai2017scannet}&\cmark&\cmark&-&\cmark&14225/1160\cite{Avetisyan2019scan2cad}&-&approx.\cite{Avetisyan2019scan2cad}\\ 3D-FUTURE\cite{fu20203dfuture}&\cmark&-&-&-&9992&-&\cmark\\ 3D-FRONT\cite{fu20203dfuture}&-&-&-&-&9992&\cmark&\cmark\\ Panoptic 3D 3D-FRONT&\cmark&\cmark&\cmark&\cmark&2717&\cmark&\cmark\\ \hline \end{tabular} } \end{table*} \begin{figure*}[!ht] \centering \includegraphics[width=0.9\linewidth]{cityscapes.png} \caption{Qualitative results of Panoptic3D (stage-wise) on Cityscapes images \cite{Cordts2016Cityscapes}. Results are taken from an off-angle shot to show the difference between depth and 3D panoptic results. We sampled the point cloud from the result object meshes for better visualization of the 3D effect. We show that our alignment module outputs visually correct alignment between things reconstruction and ``stuff'' depth point cloud.} \label{fig:cityscapes} \vspace{-4mm} \end{figure*} \section{Datasets} For Panoptic3D (stage-wise), we show qualitative results for natural datasets such as COCO and Cityscapes, where well-annotated panoptic segmentation labels are provided. To our best knowledge, no available dataset is accurately annotated with amodal instance segmentation, panoptic segmentation, 2.5D information for ``stuff'', and 3D meshes for ``things''. Most natural image datasets either do not provide panoptic segmentation annotations or suffer from low diversity or low quantity for corresponding 3D mesh annotations. ScanNet \cite{dai2017scannet} has a diverse environment, a large number of images annotated with instance/semantic segmentation, and annotations for corresponding 3D meshes. However, the mesh annotations on ScanNet do not have good alignment with their masks. Additionally, our attempt to generate panoptic segmentation information for ScanNet suffers from significant human errors in semantic and instance segmentation annotations. Therefore, we are not able to work on ScanNet for the current end-to-end supervised system. We are also aware of other 3D datasets such as SUN-RGBD \cite{song2014sunrgbd}, AI2Thor \cite{Kolve2017AI2THORAn}, Scan2CAD \cite{Avetisyan2019scan2cad}, 3D-FUTURE \cite{fu20203dfuture} and OpenRooms \cite{Li2020OpenRoomsAE}. We show in Table~\ref{tab:inhouse_dataset} that the natural datasets, such as SUN-RGBD and ScanNet, do not precisely align 3D ``stuff'' or ``things''. For a virtual dataset, even though we can extract all the information from AI2Thor, the number of shapes was too limited for shape reconstruction training during the early stages of our project. OpenRooms has not yet released its 3D CAD models. Thanks to the availability of the 3D-FRONT dataset \cite{fu20203dfuture}, we can generate a first version of the panoptic 3D parsing dataset with COCO-style annotations, including 2D amodal instance and panoptic segmentation, modal and amodal (layout) depth, and corresponding 3D mesh information for every image. Referenced from the 3D-FUTURE dataset \cite{fu20203dfuture}, we adopt 34 instance categories representing all of the countable objects as ``things'', and add three categories representing walls, ceilings, and floors as ``stuff'' as no other ``stuff'' categories exist in the first release. For rendering, the first release of the 3D-FRONT dataset does not provide the textures and colors for ``stuff'' objects, so we adopt textures from the SceneNet RGB-D dataset \cite{McCormac2017scenenet}. We place a point light at the renderer's camera position for the lightning to make sure the scene is fully lit. We use the official Blender\cite{blender} script with the officially released camera angles for this work. \begin{figure*}[!ht] \centering \includegraphics[width=0.7\linewidth]{COCOv2.png} \caption{Qualitative results for Panoptic3D (stage-wise) on COCO images \cite{Lin2014COCO}. Results are taken from an off-angle shot to show the difference between depth and 3D panoptic results. We sampled the point cloud from the predicted object meshes for better visualization of 3D structures. } \label{fig:COCO} \vspace{-4mm} \end{figure*} We use the first 1620 houses as the train set and the last 200 houses as the test set for the experiments. We first mark all objects that appear both in the train and test sets as invalid during training, ensuring that the 3D models are disjoint between the train and test sets. We only train and evaluate our mesh prediction on non-boundary (or relatively centered) objects. After filtering out images with no valid things, there are 7734 images in the train set and 1086 in the test set. There are 55216 instances in the train set for the panoptic segmentation task and 7548 instances in the test set. For the 3D reconstruction task, there are 1559 unique models in the train set and 1158 unique models in the test set. The final dataset covers 33 categories for ``things'' during training and 31 types of ``things'' during evaluation. \section{Experiment Details and Evaluation} \begin{table*}[!ht] \centering \caption{\small \textbf{Comparison of re-projected 2D panoptic qualities from a subset of COCO indoor images between Total3DUnderstanding and our Panoptic3D (stage-wise) system.} For Total3DUnderstanding, the re-projection uses inferred camera extrinsic and we change the predicted layout box into meshes for wall, ceiling, and floor. Our Panoptic3D (stage-wise) method outperforms Total3DUnderstanding on every metrics.} \label{tab:total3dpanoptic} \vspace{-2mm} \scalebox{0.85}{ \begin{tabular}{c|ccc|ccc|ccc} \hline & \multicolumn{3}{c}{PQ $\uparrow$} & \multicolumn{3}{c}{SQ $\uparrow$} & \multicolumn{3}{c}{RQ $\uparrow$} \\ Methods & [email protected] & [email protected] & [email protected] & [email protected] & [email protected] & [email protected] & [email protected] & [email protected] & [email protected] \\ \hline Total3DUnderstanding \cite{nie2020total3d} & 0.043 & 0.06 & 0.077 & 0.046 & 0.063 & 0.081 & 0.065 & 0.101 & 0.15\\ Panoptic3D (stage-wise) (ours) & \textbf{0.168} & \textbf{0.176} & \textbf{0.181} & \textbf{0.177} & \textbf{0.184} & \textbf{0.181} & \textbf{0.21} & \textbf{0.220} & \textbf{0.226}\\ \bottomrule \end{tabular} } \end{table*} \subsection{Stage-wise Panoptic3D} Datasets such as COCO and Cityscapes, have well-annotated panoptic segmentation annotations but lack annotations of 3D shapes and depth information. Figure~\ref{fig:networkstructure2} shows the stage-wise system pipeline. With UPSNet\cite{xiong19upsnet} as the backbone, we can use a de-occlusion network \cite{zhan2020self} for amodal mask prediction and a depth network \cite{Alhashim2018densedepth} and an alignment module for scene alignment. Additionally, we use the predicted amodal mask and the input RGB image for unseen class instance reconstruction \cite{zhang2018genre}. The outputs of these networks would then be passed through an alignment module that produces the 3D panoptic parsing results. For the Cityscapes dataset, we compute its camera intrinsics with FOV = 60, height = 1024 and width = 2048 \cite{Cordts2016Cityscapes}. Since it doesn't provide camera information for the COCO dataset, we estimate its FOV to be 60 based on heuristics and use an image size of $480 \times 640$, which is compatible with every sub-module of the stage-wise system. In Figure~\ref{fig:cityscapes} and Figure~\ref{fig:COCO}, we show qualitative measures for Cityscapes and COCO, respectively. The pipeline has demonstrated qualitatively good results for both indoor and outdoor natural images. Using the COCO dataset, we can project the panoptic 3D results back to the input view and evaluate it against their ground truth 2D panoptic annotation to show its image parsing capability. We acquired around 300 images from the COCO test set that contains overlapped panoptic labels Total3DUnderstanding. In Table~\ref{tab:total3dpanoptic}, we show that our pipeline outperforms Total3DUnderstanding on reprojected panoptic segmentation metrics. \subsection{End-to-end Panoptic3D} We train our networks with a learning rate of 0.005 for 30000 iterations. We use PyTorch for code development and 4 GeForce GTX TITAN X GPUs for ablation studies. We switch to 8 GPUs for larger architectures with depth/layout predictions. The experiments with the largest model take 16 hours to run on 8 GeForce GTX TITAN X GPUs. Our input size for the detection backbone is $1024 \times 1024$ instead of the original $800 \times 800$ used by Mesh R-CNN because the depth network requires the input to be divisible by 64. The input image is resized to $512 \times 512$ for the depth branch. The final network contains 13 losses: semantic segmentation pixel-wise classification loss, panoptic segmentation loss, RPN box classification loss, RPN box regression loss, instance box classification loss, instance box regression and segmentation loss, depth extent loss, inverse depth center loss, voxel loss, mesh loss, depth loss, and ``stuff'' depth loss. Partial loss is used for depth extent, object inverse depth loss, voxel loss, and mesh loss. \subsection*{Shape Reconstruction} For the baseline model, we add multi-instance training and allow shape regression only on centered objects on top of detection and reconstruction network structures used in \cite{gkioxari2019meshrcnn}. Ablations on partial-loss training and joint training with other heads are included in Table~\ref{tab:baselines} and Table~\ref{tab:shape}. We find that utilizing more samples per image for training the instance head can help improve mesh prediction with higher $AP^{mesh}$ in Table~\ref{tab:baselines}. In Table~\ref{tab:shape}, we show that adding additional panoptic, z-center, depth, and layout heads significantly improve the average precision for boxes and masks, but only a slight improvement on meshes when used together. Notice that adding z-center loss starting from the model (b) does not significantly boost the earlier models; however, it provides considerably better qualitative visualization in Figure~\ref{fig:3dfront}. Compared to row 6 (without z-center loss), row 7 (with z-center loss) shows a more consistent layout against the input RGB image. The furniture cluster around a similar depth in row 6. \begin{table}[!ht] \centering \caption{Baseline model comparisons. Our baseline model (1) is a multi-object training and evaluation enabled detection and reconstruction network \cite{gkioxari2019meshrcnn} trained on on centered objects in all three heads (instance, voxel, mesh). Model (2) is the baseline model trained on all things with a partial loss on voxel and mesh heads. N indicates the number of annotations used to regress each corresponding head during training. } \label{tab:baselines} \scalebox{0.65}{ \begin{tabular}{c|ccc|ccc} \hline Baseline&N&N&N&$AP^{box}$ & $AP^{mask}$ & $AP^{mesh}$ \\ &instances&voxels&meshes&&&\\ \hline (1)&16175&16175&16175& 37.8 $\pm$ 1.4& 34.2 $\pm$ 1.9& 5.9 $\pm$ 0.4\\ (2)&55216&16175&16175& 56.5 $\pm$ 0.9& 52.6 $\pm$ 1.1& 8.9 $\pm$ 1.5\\ \hline \end{tabular} } \end{table} \begin{table}[ht] \centering \caption{Ablation studies for the Panoptic3D (end-to-end) model on the panoptic 3D 3D-FRONT dataset. Our ablation study is compared with the baseline (2) in Table~\ref{tab:baselines}. The results show that during joint training, the network can maintain its $AP^{mesh}$ performance while improving on $AP^{box}$ and $AP^{mask}$.} \label{tab:shape} \scalebox{0.66}{ \begin{tabular}{c|cccc|ccc} \hline &panoptic &z-center & depth& layout &$AP^{box}$ & $AP^{mask}$ & $AP^{mesh}$\\ \hline (2)& -&-&-&- & 56.5 $\pm$ 0.9& 52.6 $\pm$ 1.1& 8.9 $\pm$ 1.5 \\ \hline (a) & \cmark&&& &56.7 $\pm$ 2.2& 55.8 $\pm$ 2.7 & 8.3 $\pm$ 0.6 \\ (b) & \cmark&\cmark&&& 57.0 $\pm$ 1.7& 55.5 $\pm$ 1.2 & 8.1 $\pm$ 1.5\\ (c) & \cmark&\cmark&\cmark& &59.4 $\pm$ 0.6&56.7 $\pm$ 2.4 & 9.0 $\pm$ 1.2\\ \hline ours &\cmark &\cmark&\cmark&\cmark&\textbf{60.0 $\pm$ 1.4}&\textbf{56.0 $\pm$ 1.4}&\textbf{9.0 $\pm$ 1.3} \\ \hline \end{tabular} } \end{table} \begin{figure*} \centering \includegraphics[width=0.8\linewidth]{3dfront.png} \caption{Qualitative results for Panoptic3D (end-to-end) on the 3D-FRONT dataset \cite{fu20203dfuture}. We show our predicted panoptic results (row 3) compared to panoptic ground truth (row 2) and our reconstruction results (row 5 to 7) to reconstruction ground truth (row 4). Row 8 shows the final panoptic 3D results, where we sample point clouds from meshes for better visualization. Comparing rows 6 and 7, row 7 shows the object placement is more consistent with the input RGB image. Our final results show that the shape predictions align well with the predicted ``stuff'' depth prediction.} \label{fig:3dfront} \end{figure*} \subsection*{Panoptic Segmentation} We compare our panoptic segmentation results with the original UPSNet panoptic segmentation results as one of our baselines. Although we use a panoptic feature pyramid network \cite{Kirillov2019fpn} instead of the FPN network with deformable CNNs from UPSNet, the results are comparable. We notice a slight decrease when we switch masks for instance head from modal to amodal, as amodal masks may pose challenges to the panoptic head. As for joint training, we show in Table~\ref{tab:panoptic} that the results from joint training are comparable with our baseline. We use the metrics of PQ, SQ, and RQ following the panoptic segmentation paper \ref{tab:panoptic}. We are aware that our ``stuff'' categories are an easy set for panoptic segmentation tasks. 3D-FRONT offers new releases from when we began the project, so for future studies, we will attempt to incorporate more categories, such as doors and windows, with better rendering effects. However, our dataset does provide the first version of any such dataset that enables end-to-end training on the task of panoptic 3D parsing. Based on our acquired results, there are still challenges even with the current ``stuff'' categories for panoptic segmentation. \begin{table}[ht] \centering \caption{Ablation studies for the Panoptic3D (end-to-end) model on the panoptic 3D 3D-FRONT dataset. The model numbers here correspond to models in Table~\ref{tab:shape}. Here we show that the panoptic performance is comparable to the baseline performance with joint training.} \label{tab:panoptic} \scalebox{0.8}{ \begin{tabular}{c|cccc|ccc} \hline &panoptic &z-center & depth& layout &PQ & SQ & RQ\\ \hline (a) & \cmark&&& &46.4&76.8&54.0 \\ (b) & \cmark&\cmark&&& 46.0& 75.9 &53.4 \\ (c) & \cmark&\cmark&\cmark& &47.4&76.1 & 55.2\\ \hline ours &\cmark &\cmark&\cmark&\cmark&46.9&75.7&54.4 \\ \hline \end{tabular} } \end{table} \subsection*{Depth and Layout predictions} We adopt the U-Net structure from Factored3D and jointly train the depth with the rest of our pipeline. We find regressing for layout depth alone is an easier task for the network than joint training. Joint training using layout depth loss with other losses appear to be a challenging problem. Adding cross-consistency loss \cite{zamir2020consistency} between layout depth and normal does not seem to improve depth's performance easily. Nonetheless, adding layout depth loss appears to help the network to perform better in general in both shape metrics and panoptic metrics as shown in Table~\ref{tab:shape} and Table~\ref{tab:panoptic}. \vspace{-2mm} \section{Conclusions} \vspace{-2mm} This paper presents a framework that aims towards tackling panoptic 3D parsing for a single image in the wild. We demonstrate qualitative results for natural images from datasets such as Cityscapes \cite{Cordts2016Cityscapes} (shown in Figure~\ref{fig:cityscapes}) and COCO \cite{Lin2014COCO} (shown in Figure~\ref{fig:COCO}) under the stage-wise system. Additionally, an end-to-end pipeline that can be trained with full annotations is also proposed. For societal impact, we are proposing a new task in computer vision, Panoptic 3D Parsing (Panoptic3D), that is concerned with a central task in computer vision: joint single image foreground object detection and segmentation, background semantic labeling, depth estimation, 3D reconstruction, and 3D layout estimation. A successful Panoptic3D system can see its applications in a wide range of domains beyond computer vision such as mapping, transportation, computer graphics etc. However, Panoptic3D is a learning based system and may have bias introduced in various training stages. Careful justification and adoption of the system in appropriate tasks subject to regulation are needed.\\ \noindent {\bf Limitations}: We use a fixed FOV of 60 and fixed image sizes for Cityscapes, COCO, and 3D-FRONT. Hence the estimated 3D scene can only provide a rough ordering estimation of things and stuff in terms of distance to the camera plane. We use a single light source for the 3D-FRONT image rendering, which results in artificial lighting for the training images. Therefore, the generalization capability for the models trained using this dataset might not be strong. We expect the model to generalize better under more natural lighting conditions, which is to be verified in the next step with a new dataset. \section{Acknowledgments} Part of the work was done during Sainan Liu's internship at Intel. {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-12-01T02:08:52', 'yymm': '2111', 'arxiv_id': '2111.03039', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03039'}
arxiv
\section{Evidence indicating transfer to real-world} Due to the scope of the problem and the ongoing pandemic, we limit our experiments to be in simulation. However, we provided evidence indicating that the learned policies can be transferred to the real world in the future in the paper. We summarize this evidence as follows. \paragraph{Convex decomposition} The objects after the convex decomposition still have geometrically different and complex geometries as shown in \figref{fig:convex_decomp}. The objects in the EGAD dataset are 3D printable. The YCB objects are available in the real world. \paragraph{Action space} We control the finger joints via relative position control as explained in \secref{sec:learn_teacher}. This suffers less sim-to-real gap compared to using torque control on the joints directly. \paragraph{Student policies} We designed two student policies and both of them use the observation data that can be readily acquired from the real world. The first student policy only requires the joint positions and the object pose. Object pose can be obtained using a pose estimation system or a motion capture system in the real world. Our second student policy only require the point cloud of the scene and the joint positions. We can get the point cloud in the real world by using RGBD cameras such as Realsense D415, Azure Kinect, etc. \paragraph{Domain randomization} We also trained and tested our policies with domain randomization. We randomized object mass, friction, joint damping, tendon damping, tendon stiffness, etc. \tblref{tbl:dyn_ran_params} lists all the parameters we randomized in our experiments. We also add noise to the state observation and action commands as shown in \tblref{tbl:dyn_ran_params}. For the vision experiments, we also added noise (various ways of data augmentation including point position jittering, color jiterring, dropout, etc.) to the point cloud observation in training and testing as explained in \secref{app_subsec:vision_noise}. The results in \tblref{tbl:up_success_rate}, \tblref{tbl:down_air_success_rate}, and \tblref{tbl:vision_pol_noise} show that even after adding randomization/noise, we can still get good success rates with the trained policies. Even though we cannot replicate the true real-world setups in the simulation, our results with domain randomization indicates a high possibility that our policies can be transferred to the real Shadow hand. Prior works~\cite{andrychowicz2020learning} have also shown the domain randomization can effectively reduce the sim-to-real gap. \paragraph{Torque analysis} We also conducted torque analysis as shown in \secref{app_subsec:torque_analysis}. We can see that the peak torque values remain in an reasonable and affordable range for the Shadow hand. This indicates that our learned policies are less likely to cause motor overload on the real Shadow hand. \newpage \section{Environment Setup} \begin{figure}[!h] \centering \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/upward/egad_1.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/upward/egad_2.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/upward/ycb_3.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/upward/ycb_4.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/upward/ycb_2.png} \end{subfigure}% \\ \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down_table/egad_5.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down_table/egad_6.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down_table/ycb_1.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down_table/ycb_2.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down_table/ycb_6.png} \end{subfigure}% \\ \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down/egad_5.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down/egad_7.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down/ycb_4.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down/ycb_5.png} \end{subfigure} \begin{subfigure}[t]{0.18\textwidth} \centering \includegraphics[width=\linewidth]{figures/teaser/down/ycb_6.png} \end{subfigure} \caption{We learn policies that can reorient many objects in three scenarios respectively: (1) hand faces upward, (2) hand faces downward with a table below the hand, (3) hand faces downward without any table. The extra object in each figure shows the desired orientation.} \label{fig:reorient_examples} \end{figure} \subsection{State definition} \label{app_subsec:state_def} The full state space $\mathbb{S}^\expsymbol$ includes joint, fingertip, object and goal information detailed in \tblref{tbl:state_def}. To compute the angle difference between two quaternion orientations $\alpha_1$ and $\alpha_2$, we first compute the difference rotation quaternion: $\beta=\alpha_1\alpha_2^{-1}$. Then the angle difference (distance between two rotations) $\Delta\theta$ is computed as the angle of $\beta$ from the axis-angle representation of $\beta$. \renewcommand{\arraystretch}{1.3} \begin{table}[!htb] \small{ \caption{Full state $s_t^\mathcal{E}\in\mathbb{R}^{134}$ information. Orientations are in the form of quaternions.} \label{tbl:state_def} \centering \setlength\tabcolsep{3pt} \begin{tabular}{ll|ll|ll} \hline Parameter & Description & Parameter & Description & Parameter & Description \\ \hline $q_t\in\mathbb{R}^{24}$ & joint positions & $v^f_t\in\mathbb{R}^{15}$ & fingertip linear velocities & $\alpha^g\in\mathbb{R}^{4}$ & object goal orientation \\ $\dot{q}_t\in\mathbb{R}^{24}$ & joint velocities & $w^f_t\in\mathbb{R}^{15}$& fingertip angular velocities & $v^o_t\in\mathbb{R}^{3}$ & object linear velocity \\ $p^f_t\in\mathbb{R}^{15}$ & fingertip positions & $p^o_t\in\mathbb{R}^{3}$ & object position & $w^o_t\in\mathbb{R}^{3}$ & object angular velocity \\ $\alpha^f_t\in\mathbb{R}^{20}$ & fingertip orientation & $\alpha^o_t\in\mathbb{R}^{4}$ & object orientation & $\beta_t\in\mathbb{R}^{4}$ & $\alpha^o_t(\alpha^g)^{-1}$ \\ \hline \end{tabular} } \end{table} \renewcommand{\arraystretch}{1} \subsection{Dataset} \label{app_subsec:dataset} We use two object datasets (EGAD and YCB) in our paper. To further increase the diversity of the datasets, we create $5$ variants for each object mesh by randomly scaling the mesh. The scaling ratios are randomly sampled such that the longest side of the objects' bounding boxes $l_{\max}$ lies in $[0.05, 0.08]$m for EGAD objects, and $l_{\max} \in [0.05, 0.12]$m for YCB objects. The mass of each object is randomly sampled from $[0.05, 0.15]$kg. When we randomly scale YCB objects, some objects become very small and/or thin, making the reorientation task even more challenging. In total, we use $11410$ EGAD object meshes and $390$ YCB object meshes for training. \figref{fig:egad_ycb_dataset} shows examples from the EGAD and YCB dataset. We can see that these objects are geometrically different and have complex shapes. We also use V-HACD~\citep{mamou2016volumetric} to perform an approximate convex decomposition on the object meshes for fast collision detection in the simulator. \figref{fig:convex_decomp} shows the object shapes before and after the decomposition. After the decomposition, the objects are still geometrically different. \begin{figure}[!htb] \centering \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/A2_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/A4_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/B5_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/B6_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/F6_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/G2_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/C4_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/D4_v.jpeg} \end{subfigure} \\\vspace{0.02cm} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/003_cracker_box.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/025_mug.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/065-d_cups.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/011_banana.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/072-b_toy_airplane.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/073-c_lego_duplo.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/004_sugar_box.jpeg} \end{subfigure} \begin{subfigure}[t]{0.11\textwidth} \centering \includegraphics[width=\linewidth]{figures/ycb/048_hammer.jpeg} \end{subfigure}% \caption{First row: examples of EGAD objects. Second row: examples of YCB objects.} \label{fig:egad_ycb_dataset} \end{figure} \begin{figure}[!htb] \centering \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/A2_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/A4_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/B5_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/B6_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/C4_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/C6_v.jpeg} \end{subfigure}% \\\vspace{0.02cm} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/A2_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/A4_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/B5_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/B6_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/C4_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/C6_c.jpeg} \end{subfigure}% \\ \vspace{0.4cm} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/D4_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/D5_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/E3_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/F6_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/G2_v.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/G3_v.jpeg} \end{subfigure}% \\\vspace{0.02cm} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/D4_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/D5_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/E3_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/F6_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/G2_c.jpeg} \end{subfigure} \begin{subfigure}[t]{0.16\textwidth} \centering \includegraphics[width=\linewidth]{figures/vhacd/egad/G3_c.jpeg} \end{subfigure}% \caption{Examples of EGAD objects. The first and third row shows the visual mesh of the objects. The second and fourth row show the corresponding collision mesh (after V-HACD decomposition).} \label{fig:convex_decomp} \end{figure} \subsection{Camera setup} \label{subsec:camera_setup} We placed two RGBD cameras above the hand, as shown in \figref{fig:camera_pos}. In ISAAC gym, we set the camera pose by setting its position and focus position. The two cameras' positions are shifted from the Shadow hand's base origin by $[-0.6, -0.39, 0.8]$ and $[0.45, -0.39, 0.8]$ respectively. And their focus points are the points shifted from the Shadow hand's base origin by $[-0.08, -0.39, 0.15]$ and $[0.045, -0.39, 0.15]$ respectively. \begin{figure}[!htb] \centering \includegraphics[height=0.3\linewidth]{figures/camera/cam1.png} \includegraphics[angle=90,height=0.3\linewidth]{figures/camera/cam2.png} \caption{Camera positions} \label{fig:camera_pos} \end{figure} \section{Experiment Setup} \label{app_sec:exp_setup} \subsection{Network architecture} \label{app_subsec:network_arch} For the non-vision policies, we experimented with two architectures: The MLP policy $\pi_M$ consists of $3$ hidden layers with $512, 256, 256$ neurons respectively. The RNN policy $\pi_R$ has $3$ hidden layers ($512 - 256 - 256$), followed by a $256$-dim GRU layer and one more $256$-dim hidden layer. We use the exponential linear unit (ELU)~\citep{clevert2015fast} as the activation function. For our vision policies, we design a sparse convolutional network architecture (\textit{Sparse3D-IMPALA-Net}). As shown in \figref{fig:vision_policy_arch}, the point cloud $W_t$ is processed by a series of sparse CNN residual modules and projected into an embedding vector. $q_t$ and $a_{t-1}$ are concatenated together and projected into an embedding vector via an MLP. Both embedding vectors from $W_t$ and $(q_t, a_{t-1})$ are concatenated and passed through a recurrent network to output the action $a_t$. \subsection{Training details} \label{app_sec:training_details} All the experiments in the paper were run on at most $2$ GPUs with a $32$GB memory. We use PPO~\citep{schulman2017proximal} to learn $\pi^\expsymbol$. \tblref{tbl:hyper_params} lists the hyperparameters for the experiments. We use 40K parallel environments for data collection. We update the policy with the rollout data for $8$ epochs after every $8$ rollout steps for the MLP policies and $50$ rollout steps for the RNN policies. A rollout episode is terminated (reset) if the object is reoriented to the goal orientation successfully, or the object falls, or the maximum episode length is reached. To learn the student policies $\pi^\stusymbol$, we use Dagger\citep{ross2011reduction}. While Dagger typically keep all the state-action pairs for training the policy, we do Dagger in an online fashion where $\pi^\stusymbol$ only learns from the latest rollout data. For the vision experiments, the number of parallel environments is 360 and we update policy after every $50$ rollout steps from all the parallel environments. The batch size is 30. We sample 15000 points from the reconstructed point cloud of the scene from 2 cameras for the scene point cloud $W_t^s$ and sample 5000 points from the object CAD mesh model for the goal point cloud $W^g$. We use Horovod~\citep{sergeev2018horovod} for distributed training and Adam~\citep{kingma2014adam} optimizer for neural network optimization. \textbf{Reward function for reorientation}: For training $\pi^\expsymbol$ for the reorientation task, we modified the reward function proposed in \citep{makoviychuk2021isaac} to be: \begin{align} \label{eqn:rot_reward} r(s_t, a_t) = c_{\theta_1}\frac{1}{|\Delta \theta_t|+\epsilon_\theta}+c_{\theta_2}\mathds{1}(|\Delta \theta_t| < \Bar{\theta}) + c_3\left\Vert a_t\right\Vert_2^2 \end{align} where $c_{\theta_1}>0$, $c_{\theta_2}>0$ and $c_3<0$ are the coefficients, $\Delta\theta_t$ is the difference between the current object orientation and the target orientation, $\epsilon_\theta$ is a constant, $\mathds{1}$ is an indicator function that identifies whether the object is in the target orientation. The first two reward terms encourage the policy to reorient the object to the desired orientation while the last term suppresses large action commands. \textbf{Reward function for object lifting}: To train the lifting policy, we use the following reward function: \begin{align} r(s_t, a_t) &= c_{h_1}\frac{1}{|\Delta h_t|+\epsilon_h}+c_{h_2}\mathds{1}(|\Delta h_t| < \Bar{h}) + c_3\left\Vert a_t\right\Vert_2^2 \end{align} where $\Delta h_t=\max(p_t^{b,z} - p_t^{o,z}, 0)$ and $p_t^{b,z}$ is the height ($z$ coordinate) of the Shadow Hand base frame, $p_t^{o,z}$ is the height of the object, $\Bar{h}$ is the threshold of the height difference. The objects have randomly initialized poses and are dropped onto the table. \textbf{Goal specification for vision policies}: We obtain $W^g$ by sampling $5000$ points from the object's CAD mesh using the Barycentric coordinate, rotating the points by the desired orientation, and translating them so that these points are next to the hand. Note that one can also put the object in the desired orientation right next to the hand in the simulator and render the entire scene altogether to remove the need for CAD models. We use CAD models for $W^g$ just to save the computational cost of rendering another object while we still use RGBD cameras to get $W_t^s$. \renewcommand{\arraystretch}{1.2} \begin{table}[!htb] \centering \caption{Hyperparameter Setup} \label{tbl:hyper_params} \resizebox{\columnwidth}{!}{ \begin{tabular}{cccccc} \hline Hyperparameter & Value & Hyperparameter & Value & Hyperparameter & Value \\ \hline Num. batches & 5 & Entropy coeff. & 0. & Num. pts sampled from $W_t^s$ & 15000 \\ Actor learning rate & 0.0003 & GAE parameter & 0.95 & Num. pts sampled from $W^g$ & 5000 \\ Critic learning rate & 0.001 & Discount factor & 0.99 & Num. envs & 40000 \\ Num. epochs & 8 & Episode length & 300 & \begin{tabular}[c]{@{}c@{}}Num. rollout steps per \\policy update (MLP/RNN)\end{tabular} & 8/50 \\ Value loss coeff. & 0.0005 & PPO clip range & 0.1 & $c_{\theta_1} $ & 1 \\ $c_{\theta_2}$ & 800 & $c_3$ & 0.1 & $\epsilon_\theta$ & 0.1\\ $\Bar{\theta}$ & 0.1\si{\radian} & $c_{h_1}$ & 0.05 & $\epsilon_h$ & 0.02 \\ $\Bar{h}$ & 0.04 & $c_{h_2}$ & 800 & &\\ \hline \end{tabular} } \end{table} \renewcommand{\arraystretch}{1.} \begin{table} \centering \caption{Mesh Parameters} \label{tbl:mesh_params} \begin{tabular}{ll} \hline Parameter & Range \\ \hline longest side of the bounding box of EGAD objects & {[}0.05, 0.08]m \\ longest side of the bounding box of YCB objects & {[}0.05, 0.12]m \\ mass of each object & {[}0.05, 0.15]kg \\ No. of EGAD meshes & 2282 \\ No. of YCB meshes & 78 \\ No. of variants per mesh & 5 \\ Voxelization resolution & 0.003 m \\ \hline \end{tabular} \end{table} \subsection{Dynamics randomization} \tblref{tbl:dyn_ran_params} list all the randomized parameters as well the state observation noise and action command noise. \renewcommand{\arraystretch}{1.2} \begin{table}[!htb] \centering \caption{Dynamics Randomization and Noise} \label{tbl:dyn_ran_params} \resizebox{\columnwidth}{!}{ \begin{tabular}{cccccc} \hline Parameter & Range & Parameter & Range & Parameter & Range \\ \hline state observation & $+\mathcal{U}(-0.001, 0.001)$ & action & $+\mathcal{N}(0, 0.01)$ & joint stiffness & $\times\mathcal{E}(0.75, 1.5)$ \\ object mass & $\times\mathcal{U}(0.5, 1.5)$ & joint lower range & $+\mathcal{N}(0, 0.01)$ & tendon damping & $\times\mathcal{E}(0.3, 3.0)$ \\ object static friction & $\times\mathcal{U}(0.7, 1.3)$ & joint upper range & $+\mathcal{N}(0, 0.01)$ & tendon stiffness & $\times\mathcal{E}(0.75, 1.5)$ \\ finger static friction & $\times\mathcal{U}(0.7, 1.3)$ & joint damping & $\times\mathcal{E}(0.3, 3.0)$ & & \\ \hline \multicolumn{6}{l}{\begin{tabular}[c]{@{}l@{}}$\mathcal{N}(\mu, \sigma)$: Gaussian distribution with mean $\mu$ and standard deviation $\sigma$.\\ $\mathcal{U}(a, b)$: uniform distribution between $a$ and $b$. $\mathcal{E}(a, b)=\exp^{\mathcal{U}(\log(a), \log(b))}$.\\ $+$: the sampled value is added to the original value of the variable. $\times$: the original value is scaled by the sampled value.\end{tabular}} \\ \hline \end{tabular} } \end{table} \renewcommand{\arraystretch}{1} Comparing the Column 1 and Column 2 in \tblref{tbl:up_success_rate}, we can see that if we directly deploy the policy trained without domain randomization into an environment with different dynamics, the performance drops significantly. If we train policies with domain randomization (Column 3), the policies are more robust and the performance only drops slightly compared to Column 1 in most cases. The exceptions are on C3 and H3. In these two cases, the $\pi_M^\stusymbol$ policies collapsed in training during the policy distillation along with the randomized dynamics. \subsection{Gravity curriculum} \label{subsec:grav_curr} We found building a curriculum on gravity helps improve the policy learning for YCB objects when the hand faces downward. \algoref{alg:grav} illustrates the process of building the gravity curriculum. In our experiments, we only test on the training objects once (one random initial and goal orientation) to get the surrogate average success rate $w$ on all the objects during training. $\Bar{w}=0.8, g_0=\SI{1}{\meter\per\second^2}, \Delta g = \SI{-0.5}{\meter\per\second^2}, K=3, L=20, \Delta T_{\min}=40$. \begin{algorithm} \caption{Gravity Curriculum}\label{alg:grav} \begin{algorithmic}[1] \State Initialize an empty FIFO queue $Q$ of size $K$, $\Delta T = 0, g=g_{0}$ \For{$i \gets 1$ to $M$} \State $\tau$ = \texttt{rollout\_policy($\pi_\theta$)} \Comment{get rollout trajectory} \State $\pi_\theta$ = \texttt{optimize\_policy($\pi_\theta$, $\tau$)} \Comment{update policy} \State $\Delta T = \Delta T + 1$ \If{$ i \mod L = 0$} \State $w$ = \texttt{evaluate\_policy($\pi_\theta$)} \Comment{evaluate the policy, get the success rate $w$} \State append $w$ to the queue $Q$ \If{\texttt{avg}$(Q) > \Bar{w}$ and $\Delta T> \Delta T_{\min}$} \State $g=\max(g-\Delta g, -9.81) $ \State $\Delta T = 0$ \EndIf \EndIf \EndFor \end{algorithmic} \end{algorithm} \section{Supplementary Results} \subsection{Hand faces upward} \label{app_subsec:hand_up} \paragraph{Learning curves} \figref{fig:egad_learn_upward} shows the learning curve of the RNN and MLP policies on the EGAD and YCB datasets. Both policies learn well on the EGAD and YCB datasets. The YCB dataset requires much more environment interactions for the policies to learn. We can also see that using the full-state information can speed up the learning and give a higher final performance. \begin{figure}[!htb] \centering \includegraphics[width=0.32\linewidth]{figures/upward/egad.pdf} \includegraphics[width=0.32\linewidth]{figures/upward/ycb_0_14.pdf} \includegraphics[width=0.32\linewidth]{figures/upward/ycb_0_14_full_reduced_rnn.pdf} \caption{Learning curves of the MLP and RNN policies on the EGAD (\textbf{Left}) and YCB datasets (\textbf{Middle}). The \textbf{Right} plot shows that using the full state information speeds up the policy learning compared to only using the reduced state information.} \label{fig:egad_learn_upward} \end{figure} \paragraph{Testing performance - Teacher} The testing results in \tblref{tbl:up_success_rate} show that both the MLP and RNN policies are able to achieve a success rate greater than 90\% on the EGAD dataset (entries A1, B1) and greater than 70\% on the YCB dataset (entries F1, G1) without any explicit knowledge of the object shape. This result is surprising because intuitively, one would assume that information about the object shape is important for in-hand reorientation. \paragraph{Testing performance - Student} We experimented with the following three combinations: (1) distill $\pi_M^\expsymbol$ into $\pi_M^\stusymbol$, (2) distill $\pi_M^\expsymbol$ into $\pi_R^\stusymbol$, (3) distill $\pi_R^\expsymbol$ into $\pi_R^\stusymbol$. The student policy state is $s_t^\mathcal{S}\in\mathbb{R}^{31}$. In \tblref{tbl:up_success_rate} (entries C1-E1, H1-J1), we can see that $\pi_R^\expsymbol\rightarrow\pi_R^\stusymbol$ gives the highest success rate on $\pi^\stusymbol$, while $\pi_M^\expsymbol\rightarrow\pi_M^\stusymbol$ leads to much worse performance ($36\%$ drop of success rate in EGAD, and $47\%$ drop in YCB). This shows that $\pi^\stusymbol$ requires temporal information due to reduced state space. The last two columns in \tblref{tbl:up_success_rate} also show that the policy is more robust to dynamics variations and observation/action noise after being trained with domain randomization. \renewcommand{\arraystretch}{1.1} \begin{table}[!tb] \vspace{-0.5cm} \centering \caption{Success rates (\%) of policies tested on different dynamics distribution. $\Bar{\theta}=0.1$\si{\radian}. DR stands for domain randomization and observation/action noise. X$\rightarrow$Y: distill policy X into policy Y.} \label{tbl:up_success_rate} \resizebox{0.9\columnwidth}{!}{ \begin{tabular}{cccc|ccc} \hline \multicolumn{4}{c}{} & 1 & 2 & 3 \\ \hline \multirow{2}{*}{Exp. ID} & \multirow{2}{*}{Dataset} & \multirow{2}{*}{State} & \multicolumn{1}{c}{\multirow{2}{*}{Policy}} & \multicolumn{2}{c}{Train without DR} & Train with DR \\ \cline{5-7} & & & \multicolumn{1}{c}{} & \multicolumn{1}{l}{Test without DR} & Test with DR & Test with DR \\ \hline A & \multirow{5}{*}{EGAD} & \multirow{2}{*}{Full state} & MLP & 92.55 $\pm$ 1.3 & 78.24 $\pm$ 2.4 & \textbf{91.92} $\pm$ \textbf{0.4} \\ B & & & RNN & \textbf{95.95} $\pm$ \textbf{0.8} & \textbf{84.27} $\pm$ \textbf{1.0} & 88.04 $\pm$ 0.6 \\ C & & \multirow{3}{*}{Reduced state} & MLP$\rightarrow$MLP & 55.55 $\pm$ 0.2 & 25.09 $\pm$ 3.0 & 23.77 $\pm$ 1.8 \\ D & & & MLP$\rightarrow$RNN & 85.32 $\pm$ 1.2 & 68.31 $\pm$ 2.6 & \textbf{81.05} $\pm$ \textbf{1.2} \\ E & & & RNN$\rightarrow$RNN & \textbf{91.96} $\pm$ \textbf{1.5} & \textbf{78.30} $\pm$ \textbf{1.2} & 80.29 $\pm$ 0.9 \\ \hline F & \multirow{5}{*}{YCB} & \multirow{2}{*}{Full state} & MLP & 73.40 $\pm$ 0.2 & 54.57 $\pm$ 0.6 & 66.00 $\pm$ 2.7 \\ G & & & RNN & \textbf{80.40} $\pm$ \textbf{1.6} & \textbf{65.16} $\pm$ \textbf{1.0} & \textbf{72.34} $\pm$ \textbf{0.9} \\ H & & \multirow{3}{*}{Reduced state} & MLP$\rightarrow$MLP & 34.08 $\pm$ 0.9 & 12.08 $\pm$ 0.4 & \ \ 5.41 $\pm$ 0.3 \\ I & & & MLP$\rightarrow$RNN & 69.30 $\pm$ 0.8 & 47.38 $\pm$ 0.6 & 53.07 $\pm$ 0.9 \\ J & & & RNN$\rightarrow$RNN & \textbf{81.04} $\pm$ \textbf{0.5} & \textbf{64.93} $\pm$ \textbf{0.2} & \textbf{65.86} $\pm$ \textbf{0.7} \\ \hline \end{tabular} } \vspace{-0.5cm} \end{table} \renewcommand{\arraystretch}{1} \paragraph{Failure cases} \figref{fig:failure_cases_up} shows some example failure cases. If the objects are too small, thin, or big, the objects are likely to fall. If objects are initialized close to the hand border, it is much more difficult for the hand to catch the objects. Another failure mode is that the objects are reoriented close to the goal orientation but not close enough to satisfy $\Delta \theta\leq \Bar{\theta}$. \begin{figure}[!htb] \centering \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[trim=300 240 80 200, clip, width=\linewidth]{figures/failures/upv2/1.png} \caption{} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[trim=300 240 80 200, clip,width=\linewidth]{figures/failures/upv2/2.png} \caption{} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[trim=300 240 80 200, clip,width=\linewidth]{figures/failures/upv2/3.png} \caption{} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[trim=300 240 80 200, clip,width=\linewidth]{figures/failures/upv2/4.png} \caption{} \end{subfigure}% \caption{Examples of failure cases. (a) and (b): objects are too small. (c): the object is reoriented close to the target orientation, but not close enough. (d): the object is too big and initialized around the palm border.} \label{fig:failure_cases_up} \end{figure} \subsection{Hand faces downward (in the air)} \label{app_subsec:hand_down} \paragraph{Testing performance} For the case of reorienting objects in the air with the hand facing downward \tblref{tbl:down_air_success_rate} lists the success rates of different policies trained with/without domain randomization, and tested with/without domain randomization. \renewcommand{\arraystretch}{1.2} \begin{table}[!htb] \caption{Success rates (\%) of policies trained with hand facing downward and to reorient objects in the air. Due to the large number of environment steps required in this setup, we fine-tune the model trained without DR with randomized dynamics instead of training models with DR from scratch. } \label{tbl:down_air_success_rate} \centering \resizebox{\columnwidth}{!}{ \begin{tabular}{cccc|ccc} \hline \multicolumn{4}{c}{} & 1 & 2 & 3 \\ \hline \multirow{2}{*}{Exp. ID} & \multirow{2}{*}{Dataset} & \multirow{2}{*}{State} & \multicolumn{1}{c}{\multirow{2}{*}{Policy}} & \multicolumn{2}{c}{Train without DR} & Finetune with DR \\ \cline{5-7} & & & \multicolumn{1}{c}{} & Test without DR & Test with DR & Test with DR \\ \hline K & \multirow{4}{*}{EGAD} & \multirow{2}{*}{Full state} & MLP & \textbf{84.29} $\pm$ \textbf{0.9} &\textbf{38.42} $\pm$ \textbf{1.5} & \textbf{71.44} $\pm$ \textbf{1.3} \\ L & & & RNN & 82.27 $\pm$ 3.3 & \begin{tabular}[c]{@{}c@{}}36.55 $\pm$ 1.4\\\end{tabular} & 67.44 $\pm$ 2.1 \\ M & & \multicolumn{1}{l}{\multirow{2}{*}{Reduced state}} & MLP$\rightarrow$RNN & \textbf{77.05} $\pm$ \textbf{1.6} & 29.22 $\pm$ 2.6 & 59.23 $\pm$ 2.3 \\ N & & \multicolumn{1}{l}{} & RNN$\rightarrow$RNN & 74.10 $\pm$ 2.3 & \textbf{37.01} $\pm$ \textbf{1.5} & \textbf{62.64} $\pm$ \textbf{2.9} \\ \hline O & \multirow{6}{*}{YCB} & \multirow{3}{*}{Full state} & MLP & 58.95 $\pm$ 2.0 & 26.04 $\pm$ 1.9 & 44.84 $\pm$ 1.3 \\ P & & & RNN & 52.81 $\pm$ 1.7 &\textbf{26.22} $\pm$ \textbf{1.0} & 40.44 $\pm$ 1.5 \\ Q & & & RNN + $g$-curr & \textbf{74.74} $\pm$ \textbf{1.2} & 25.56 $\pm$ 2.9 & \textbf{54.24} $\pm$ \textbf{1.4} \\ R & & \multirow{3}{*}{Reduced state} & MLP$\rightarrow$RNN & 46.76 $\pm$ 2.5 & \textbf{25.49} $\pm$ \textbf{1.4} & 34.14 $\pm$ 1.3 \\ S & & & RNN$\rightarrow$RNN & 45.22 $\pm$ 2.1 & 24.45 $\pm$ 1.2 & 31.63 $\pm$ 1.6 \\ T & & & RNN + $g$-curr$\rightarrow$ RNN & \textbf{67.33} $\pm$ \textbf{1.9} & 19.77 $\pm$ 2.8 & \textbf{48.58} $\pm$ \textbf{2.3} \\ \hline \end{tabular} } \end{table} \renewcommand{\arraystretch}{1} \paragraph{Example visualization} We show an example of reorienting a cup in \figref{fig:down_reorient_cup} and an example of reorienting a sponge in \figref{fig:down_reorient_sponge}. More examples are available at \url{https://taochenshh.github.io/projects/in-hand-reorientation}. \begin{figure}[!htb] \centering \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000000.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000004.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000008.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000012.png} \end{subfigure}% \\ \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000016.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000020.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000024.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000028.png} \end{subfigure}% \\ \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000032.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000036.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000040.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb1/000045.png} \end{subfigure}% \caption{An example of reorienting a cup with the hand facing downward. From left to right, top to bottom, we show the some moments in an episode.} \label{fig:down_reorient_cup} \end{figure} \begin{figure}[!htb] \centering \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000001.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000009.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000016.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000024.png} \end{subfigure}% \\ \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000032.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000040.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000048.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000056.png} \end{subfigure}% \\ \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000064.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000072.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000080.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000088.png} \end{subfigure}% \\ \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000092.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000096.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000104.png} \end{subfigure} \begin{subfigure}[t]{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/episode/ycb2/000113.png} \end{subfigure}% \caption{An example of reorienting a sponge with the hand facing downward. From left to right, top to bottom, we show the some moments in an episode.} \label{fig:down_reorient_sponge} \end{figure} \subsection{Success rate on each type of YCB objects} We also analyzed the success rates on each object type in the YCB dataset. Using the same evaluation procedure described in \secref{sec:env_setup}, we get the success rates of each object using $\pi_R^\expsymbol$. \figref{fig:success_rate_ycb_up} shows the distribution of the success rates on YCB objects with the hand facing upward while \figref{fig:success_rate_ycb_down} corresponds to the case of reorienting the objects in the air with the hand facing downward. We can see that sphere-like objects such as tennis balls and orange are easiest to reorient. Long or thin objects such as knives and forks are the hardest ones to manipulate. \begin{figure}[!htb] \centering \includegraphics[width=0.95\linewidth]{figures/analysis/ycb_up.pdf} \caption{Reorientation success rates for each object in the YCB dataset when the hand faces upward.} \label{fig:success_rate_ycb_up} \end{figure} \begin{figure}[!htb] \centering \includegraphics[width=0.95\linewidth]{figures/analysis/ycb_down.pdf} \caption{Reorientation success rates for each object in the YCB dataset when the hand faces downward without a table.} \label{fig:success_rate_ycb_down} \end{figure} \subsection{Torque analysis} \label{app_subsec:torque_analysis} We randomly sampled $100$ objects from the YCB dataset, and use our RNN policy trained without domain randomization with the hand facing downward to reorient each of these objects $200$ times. We record the joint torque values for each finger joint at each time step. Let the joint torque value of $i^{th}$ joint at time step $j$ in $k^{th}$ episode be $J_{ij}^k$. We plot the distribution of $\{\max_{i=[\![1,24]\!]}|J_{ij}^k| \mid j\in[\![ 1, T]\!], k=[\![ 1,20000]\!]\}$, where $[\![a, b]\!]$ represents $\{x\mid x\in[a,b], x\in\mathbb{Z}\}$. \figref{fig:torque} shows that the majority of the maximum torque magnitude is around \SI{0.2}{\newton\meter}. \begin{figure}[!htb] \centering \includegraphics[width=\linewidth]{figures/analysis/max_torque.pdf} \caption{Distribution of the \textit{maximum} absolute joint torque values on all joints for all the time steps. We exclude a few outliers in the plot, i.e., we only plot the data distributions up to $99\%$ quantile.} \label{fig:torque} \end{figure} \subsection{Vision experiments with noise} \label{app_subsec:vision_noise} We also trained our vision policies with noise added to the point cloud input. We added the following transformations to the point cloud input. We applied four types of transformations on the point cloud: \begin{itemize}[leftmargin=*] \item \textit{RandomTrans}: Translate the point cloud by $[\Delta x, \Delta y, \Delta z]$ where $\Delta x, \Delta y, \Delta z$ are all uniformly sampled from $[-0.04, 0.04]$. \item \textit{JitterPoints}: Randomly sample $10\%$ of the points. For each sampled point $i$, jitter its coordinate by $[\Delta x_i, \Delta y_i, \Delta z_i]$ where $\Delta x_i, \Delta y_i, \Delta z_i$ are all sampled from a Normal distribution $\mathcal{N}(0, 0.01)$ (truncated at $-0.015$m and $0.015$m). \item \textit{RandomDropout}: Randomly dropout points with a dropout ratio uniformly sampled from $[0, 0.4]$. \item \textit{JitterColor}: Jitter the color of points with the following 3 transformations: (1) jitter the brightness and rgb values, (2) convert the color of $30\%$ of the points into gray, (3) jitter the color contrast. Each of this transformation can be applied independently with a probability of $30\%$ if \textit{JitterColor} is applied. \end{itemize} Each of these four transformations is applied independently with a probability of $40\%$ for each point cloud at every time step. \tblref{tbl:vision_pol} shows the success rates of the vision policies trained with the aforementioned data augmentations until policy convergence and tested with the same data augmentations. We found that adding the data augmentation in training actually helps improve the data efficiency of the vision policy learning even though the final performance might be a bit lower. As a reference, we show the policy performance trained and tested without data augmentation in \tblref{tbl:vision_pol}. For the mug object, adding data augmentation in training improves the final testing performance significantly. Without data augmentation, the learned policy reorients the mug to a pose where the body of the mug matches how the mug should look in the goal orientation, but the cup handle does not match. Adding the data augmentation helps the policy to get out of this local optimum. \renewcommand{\arraystretch}{1.2} \begin{table}[!htb] \centering \centering \caption{Vision policy success rates when the policy is trained and tested with/without data augmentation ($\Bar{\theta}=\SI{0.2}{\radian}, \Bar{d}_C=0.01$)} \label{tbl:vision_pol} \begin{tabular}{clcc} \hline \multicolumn{2}{c}{Object} & Without data augmentation (noise) & With data augmentation (noise) \\ \hline \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/025_mug.jpeg} \end{minipage} & 025\_mug & $36.51 \pm 2.8$ & $89.67 \pm 1.2$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/065-d_cups.jpeg} \end{minipage}& 065-d\_cups & $79.17\pm 2.3$ & $68.32\pm 1.9$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/072-b_toy_airplane.jpeg} \end{minipage}&072-b\_toy\_airplane & $90.25 \pm 3.7$ & $84.52 \pm 1.4$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/073-a_lego_duplo.jpeg} \end{minipage}& 073-a\_lego\_duplo & $62.16 \pm 3.7$ & $58.16 \pm 3.1$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/073-c_lego_duplo.jpeg} \end{minipage} &073-c\_lego\_duplo & $58.21 \pm 3.9$ & $50.21 \pm 3.7$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/073-e_lego_duplo.jpeg} \end{minipage}&073-e\_lego\_duplo & $76.57\pm 3.6$ & $66.57\pm 3.1$ \\ \hline \end{tabular} \end{table} \renewcommand{\arraystretch}{1} \end{appendices} \section{Introduction} \vspace{-0.15cm} A common maneuver in many tasks of daily living is to pick an object, reorient it in hand and then either place it or use it as a tool. Consider three simplified variants of this maneuver shown in Figure~\ref{fig:teaser}. The task in the top row requires an upward-facing multi-finger hand to manipulate an \textit{arbitrary} object in a random orientation to a goal configuration shown in the rightmost column. The next two rows show tasks where the hand is facing downward and is required to reorient the object either using the table as a support or without the aid of any support surface respectively. The last task is the hardest because the object is in an intrinsically unstable configuration owing to the downward gravitational force and lack of support from the palm. Additional challenges in performing such manipulation with a multi-finger robotic hand stem from the control space being high-dimensional and reasoning about the multiple transitions in the contact state between the finger and the object. Due to its practical utility and several unsolved issues, in-hand object reorientation remains an active area of research. Past work has tackled the in-hand reorientation problem via several approaches: (i) The use of analytical models with powerful trajectory optimization methods~\cite{mordatch2012contact,bai2014dexterous,kumar2014real}. While these methods demonstrated remarkable performance, the results were largely in simulation with simple object geometries and required detailed knowledge of the object model and physical parameters. As such, it remains unclear how to scale these methods to real-world and generalize to new objects. Another line of work has employed (ii) model-based reinforcement learning~\cite{kumar2016optimal,nagabandi2020deep}; or (iii) model-free reinforcement learning with~\cite{gupta2016learning,kumar2016learning,rajeswaran2017learning,radosavovic2020state} and without expert demonstrations~\cite{mudigonda2018investigating,andrychowicz2020learning,akkaya2019solving,zhu2019dexterous}. While some of these works demonstrated learned skills on real robots, it required use of additional sensory apparatus not readily available in the real-world (e.g., motion capture system) to infer the object state, and the learned policies did not generalize to diverse objects. Furthermore, most prior methods operate in the simplified setting of the hand facing upwards. The only exception is pick-and-place, but it does not involve any in-hand re-orientation. A detailed discussion of prior research is provided in Section~\ref{sec:related}. In this paper, our goal is to study the object reorientation problem with a multi-finger hand in its general form. We desire (a) manipulation with hand facing upward or downward; (b) the ability of using external surfaces to aid manipulation; (c) the ability to reorient objects of novel shapes to arbitrary orientations; (d) operation from sensory data that can be easily obtained in the real world such as RGBD images and joint positions of the hand. While some of these aspects have been individually demonstrated in prior work, we are unaware of any published method that realizes all four. Our main contribution is building a system that achieves the desiderata. The core of our framework is a model-free reinforcement learning with three key components: teacher-student learning, gravity curriculum, and stable initialization of objects. Our system requires no knowledge of object or manipulator models, contact dynamics or any special pre-processing of sensory observations. We experimentally test our framework using a simulated Shadow hand. Due to the scope of the problem and the ongoing pandemic, we limit our experiments to be in simulation. However, we provide evidence indicating that the learned policies can be transferred to the real world in the future. \noindent{\textbf{A Surprising Finding}:} While seemingly counterintuitive, we found that policies that have no access to shape information can manipulate a large number of previously unseen objects in all the three settings mentioned above. At the start of the project, we hypothesized that developing visual processing architecture for inferring shape while the robot manipulates the object would be the primary research challenge. On the contrary, our results show that it is possible to learn control strategies for general in-hand object re-orientation that are shape-agnostic. Our results, therefore, suggest that visual perception may be less important for in-hand manipulation than previously thought. Of course, we still believe that the performance of our system can be improved by incorporating shape information. However, our findings suggest a different framework of thinking: a lot can be achieved without vision, and that vision might be the icing on the cake instead of the cake itself. \section{Method} \label{sec:method} We found that \textit{simple} extensions to existing techniques in robot learning can be used to construct a system for general object reorientation. First, to avoid explicit modeling of non-linear and frequent changes in the contact state between the object and the hand, we use model-free reinforcement learning (RL). An added advantage is that model-free RL is amenable to direct operation from raw point cloud observations, which is preferred for real-world deployment. We found that better policies can be trained faster using \textit{privileged} state information such as the velocities of the object/fingertips that is easily available in the simulator but not in the real world. To demonstrate the possibility of transferring learned policies to the real world in the future, we overcome the need for privileged information using the idea of \textit{teacher-student training}~\citep{lee2020learning, chen2020learning}. In this framework, first, an expert or \textit{teacher} policy ($\pi^\expsymbol$) is trained using privileged information. Next, the \textit{teacher} policy guides the learning of a \textit{student} policy ($\pi^\stusymbol$) that only uses sensory inputs available in the real world. Let the state space corresponding to $\pi^\expsymbol$ and $\pi^\stusymbol$ be $\mathbb{S}^\expsymbol$ and $\mathbb{S}^\stusymbol$ respectively. In general, $\mathbb{S}^\expsymbol\neq \mathbb{S}^\stusymbol$. We first trained the teacher policy to reorient more than two thousand objects of diverse shapes (see \secref{sec:learn_teacher}). Next, we detail the method for distilling $\pi^\expsymbol$ to a student policy using a reduced state space consisting of only the joint positions of the hand, the object position, and the difference in orientation from the goal configuration (see \secref{subsec:student_nonvision}). However, in the real world, even the object position and relative orientation must be inferred from sensory observation. Not only does this process require substantial engineering effort (e.g., a motion capture or a pose estimation system), but also inferring the pose of a symmetric object is prone to errors. This is because a symmetric object at multiple orientations looks exactly the same in sensory space such as RGBD images. To mitigate these issues, we further distill $\pi^\expsymbol$ to operate directly from the point cloud and position of all the hand joints (see \secref{subsec:student_vision_policy}). We propose a simple modification that generalizes an existing 2D CNN architecture~\citep{espeholt2018impala} to make this possible. The procedure described above works well for manipulation with the hand facing upwards and downwards when a table is available as support. However, when the hand faces downward without an underlying support surface, we found it important to initialize the object in a stable configuration. Finally, because gravity presents the primary challenge in learning policies with a downward-facing hand, we found that training in a curriculum where gravity is slowly introduced (i.e., \textit{gravity curriculum}) substantially improves performance. These are discussed in Section~\ref{subsec: hand_down}. \vspace{-0.2cm} \subsection{Learning the teacher policy} \label{sec:learn_teacher} \vspace{-0.1cm} We use model-free RL to learn the teacher policy ($\pi^\expsymbol$) for reorienting an object ($\{O_i | i=1, ..., N\}$) from an initial orientation $\alpha^o_0$ to a target orientation $\alpha^g$ ($\alpha^o_0\neq\alpha^g$). At every time step $t$, the agent observes the state $s_t$, executes the action $a_t$ sampled from the policy $\pi^\expsymbol$, and receives a reward $r_t$. $\pi^\expsymbol$ is optimized to maximize the expected discounted return: $\pi=\arg\max_{\pi^\expsymbol}\mathbb{E} \big[ \sum^{T-1}_{t=0} \gamma^{t} r_t\big]$, where $\gamma$ is the discount factor. The task is successful if the angle difference $\Delta\theta$ between the object's current ($\alpha^o_t$) and the goal orientation ($\alpha^g$) is smaller than the threshold value $\Bar{\theta}$, \textit{i.e.}\xspace, $\Delta\theta\leq \Bar{\theta}$. To encourage the policy to be smooth, the previous action is appended to the inputs to the policy (\textit{i.e.}\xspace, $a_t=\pi^\expsymbol(s_t, a_{t-1})$) and large actions are penalized in the reward function. We experiment with two architectures for $\pi^\expsymbol$: (1) an MLP policy $\pi_M$, (2) an RNN policy $\pi_R$. We use PPO~\citep{schulman2017proximal} to optimize $\pi^\expsymbol$. More details about the training are in \secref{app_subsec:network_arch} and \secref{app_sec:training_details} in the appendix. \textbf{Observation and action space}: We define $\mathbb{S}^\expsymbol$ to include joint, fingertip, object, and goal information as detailed in \tblref{tbl:state_def} in the appendix. Note that $\mathbb{S}^\expsymbol$ does not include object shape or information about friction, damping, contact states between the fingers and the object, etc. We control the joint movements by commanding the relative change in the target joint angle ($q_{t}^{target}$) on each actuated joint (action $a_t\in\mathbb{R}^{20}$): $q_{t+1}^{target} = q_{t}^{target} + a_t\times \Delta t$, where $\Delta t$ is the control time step. We clamp the action command if necessary to make sure $|\Delta q_t^{target}|\leq\SI{0.33}{\radian}$. The control frequency is \SI{60}{\hertz}. \textbf{Dynamics randomization}: Even though we do not test our policies on a real robot, we train and evaluate policies with domain randomization~\citep{tobin2017domain} to provide evidence that our work has the potential to be transferred to a real robotic system in the future. We randomize the object mass, friction coefficient, joint damping and add noise to the state observation $s_t$ and the action $a_t$. More details about domain randomization are provided in \tblref{tbl:dyn_ran_params} in the appendix. \subsection{Learning the student policy} \label{subsec:student_pol} We distill the teacher $\pi^\expsymbol$ into the student policy $\pi^\stusymbol$ using Dagger~\citep{ross2011reduction}, a learning-from-demonstration method that overcomes the covariate shift problem. We optimize $\pi^\stusymbol$ by minimizing the KL-divergence between $\pi^\stusymbol$ and $\pi^\expsymbol$: $\pi^\stusymbol=\arg\min_{\pi^\stusymbol}D_{KL}\left(\pi^\expsymbol(s^\mathcal{E}_t, a_{t-1}) || \pi^\stusymbol(s^\mathcal{S}_t, a_{t-1}))\right)$. Based on observation data available in real-world settings, we investigate two different choices of $\mathbb{S}^\stusymbol$. \subsubsection{Training student policy from low-dimensional state} \label{subsec:student_nonvision} In the first case, we consider a non-vision student policy $\pi^\stusymbol(s_t^\mathcal{S}, a_{t-1})$. $s_t^\mathcal{S}\in\mathbb{R}^{31}$ includes the joint positions $q_t\in\mathbb{R}^{24}$, object position $p^o_t\in\mathbb{R}^3$, quaternion difference between the object's current and target orientation $\beta_t\in\mathbb{R}^4$. In this case, $\mathbb{S}^\stusymbol\subset\mathbb{S}^\expsymbol$, and we assume the availability of object pose information, but do not require velocity information. We use the same MLP and RNN network architectures used for $\pi^\expsymbol$ on $\pi^\stusymbol$ except the input dimension changes as the state dimension is different. \subsubsection{Training student policy from vision} \label{subsec:student_vision_policy} In the second case, $\mathbb{S}^\stusymbol$ only uses direct observations from RGBD cameras and the joint position ($q_t$) of the robotic hand. We convert the RGB and Depth data into a colored point cloud using a pinhole camera model~\cite{andrew2001multiple}. Our vision policy takes as input the voxelized point cloud of the scene $W_t$, $q_t$, and previous action command $a_{t-1}$, and outputs the action $a_t$, \textit{i.e.}\xspace, $a_t=\pi^\stusymbol(W_t, q_t, a_{t-1})$. \textbf{Goal specification}: To avoid manually defining per-object coordinate frame for specifying the goal quaternion, we provide the goal to the policy as an object point cloud rotated to the desired orientation $W^g$, \textit{i.e.}\xspace, we only show the policy how the object should look like in the end (see the top left of \figref{fig:vision_policy_arch}). The input to $\pi^\stusymbol$ is the point cloud $W_t = W^s_t\cup W^g$ where $W_t^s$ is the actual point cloud of the current scene obtained from the cameras. Details of obtaining $W_g$ are in \secref{app_sec:training_details}. \begin{figure}[!tb] \centering \includegraphics[width=\linewidth]{figures/architecture/architecture_v5.pdf} \caption{Visual policy architecture. MK stands for Minkowski Engine. $q_t$ is the joint positions and $a_t$ is the action at time step $t$.} \label{fig:vision_policy_arch} \end{figure} \textbf{Sparse3D-IMPALA-Net}: To convert a voxelized point cloud into a lower-dimensional feature representation, we use a sparse convolutional neural network. We extend the IMPALA policy architecture~\citep{espeholt2018impala} for processing RGB images to process colored point cloud data using 3D convolution. Since many voxels are unoccupied, the use of regular 3D convolution substantially increases computation time. Hence, we use Minkowski Engine~\citep{choy20194d}, a PyTorch library for sparse tensors, to design a 3D version of IMPALA-Net with sparse convolutions (\textit{Sparse3D-IMPALA-Net})\footnote{We also experimented with a 3D sparse convolutional network based on ResNet18, and found that 3D IMPALA-Net works better.}. The Sparse3D-IMPALA network takes as input the point cloud $W_t$, and outputs an embedding vector which is concatenated with the embedding vector of $(q_t, a_{t-1})$. Afterward, a recurrent network is used and outputs the action $a_t$. The detailed architecture is illustrated in \figref{fig:vision_policy_arch}. \textbf{Mitigating the object symmetry issue}: $\pi^\expsymbol$ is trained with the the ground-truth state information $s_t^\mathcal{E}$ including the object orientation $\alpha_t^o$ and goal orientation $\alpha^g$. % The vision policy does not take any orientation information as input. If an object is symmetric, the two different orientations of the object may correspond to the same point cloud observation. This makes it problematic to use the difference in orientation angles ($\Delta\theta\leq \Bar{\theta}$) as the stopping and success criterion. To mitigate this issue, we use Chamfer distance~\citep{fan2017point} to compute the distance between the object point cloud in $\alpha^o_t$ and the goal point cloud (i.e., the object rotated by $\alpha^g$) as the evaluation criterion. The Chamfer distance is computed as $d_{C}=\sum_{a\in W_t^o}\min_{b\in W^g} \left\Vert a-b\right\Vert_2^2 + \sum_{b\in W^g}\min_{a\in W_t^o} \left\Vert a-b\right\Vert_2^2$, where $W_t^o$ is the object point cloud in its current orientation. Both $W_t^o$ and $W^g$ are scaled to fit in a unit sphere for computing $d_C$. We check Chamfer distance in each rollout step. If $d_C\leq \Bar{d}_C$ ($\Bar{d}_C$ is a threshold value for $d_C$), we consider the episode to be successful. Hence, the success criterion is $(\Delta\theta\leq\Bar{\theta}) \lor (d_C\leq \Bar{d}_C)$. In training, if the success criterion is satisfied, the episode is terminated and used for updating $\pi^\stusymbol$. \section{Experimental Setup} \label{sec:env_setup} We use the simulated Shadow Hand\xspace~\citep{shadowhand} in NVIDIA Isaac Gym\xspace~\citep{makoviychuk2021isaac}. Shadow Hand\xspace is an anthropomorphic robotic hand with 24 degrees of freedom (DoF). We assume the base of the hand to be fixed. Twenty joints are actuated by agonist–antagonist tendons and the remaining four are under-actuated. \textbf{Object datasets}: We use the EGAD dataset~\citep{morrison2020egad} and YCB dataset~\citep{calli2015ycb} that contain objects with diverse shapes (see \figref{fig:egad_ycb_dataset}) for in-hand manipulation experiments. EGAD contains $2282$ geometrically diverse textureless object meshes, while the YCB dataset includes textured meshes for objects of daily life with different shapes and textures. We use the $78$ YCB object models collected with the Google scanner. Since most YCB objects are too big for in-hand manipulation, we proportionally scale down the YCB meshes. To further increase the diversity of the datasets, we create $5$ variants for each object mesh by randomly scaling the mesh. More details of the object datasets are in \secref{app_subsec:dataset}. \begin{figure}[!tb] \vspace{-0.5cm} \centering \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/exp_scene/up_crop.png} \caption{} \label{fig:up} \end{subfigure}% \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/exp_scene/down_random_crop.png} \caption{} \label{fig:down_random} \end{subfigure}% \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/exp_scene/down_table_crop.png} \caption{} \label{fig:down_table} \end{subfigure}% \begin{subfigure}{0.24\textwidth} \centering \includegraphics[width=\linewidth]{figures/exp_scene/down_pregrasp_crop.png} \caption{} \label{fig:down_pregrasp} \end{subfigure}\\ \caption{Examples of initial poses of the hand and object. \textbf{(a)}: hand faces upward. \textbf{(b)}, \textbf{(c)}, \textbf{(d)}: hand faces downward. \textbf{(b)}: both the hand and the object are initialized with random poses . \textbf{(c)}: there is a table below the hand. \textbf{(d)}: the hand and the object are initialized from the lifted poses. } \label{fig:exp_setup} \end{figure} \textbf{Setup for visual observations}: For the vision experiments, we trained policies for the scenario of hand facing upwards. We place two RGBD cameras above the hand (\figref{fig:camera_pos}). The data from these cameras is combined to create a point cloud observation of the scene~\citep{andrew2001multiple}. For downstream computation, the point cloud is voxelized with a resolution of \SI{0.003}{\meter}. \textbf{Setup with the upward facing hand}: We first consider the case where the Shadow Hand\xspace faces upward and is required to reorient objects placed in the hand (see \figref{fig:up}). We use the coordinate system where the $z$-axis points vertically upward and the $xy$-plane denotes the horizontal plane. The object pose is initialized with the following procedure: $xy$ position of the object's center of mass (COM) $p_{0,xy}^o$ is randomly sampled from a square region of size $\SI{0.09}{\meter}\times\SI{0.09}{\meter}$. The center of this square is approximately located on the intersection of the middle finger and the palm so that the sampling region covers both the fingers and the palm. The $z$ position of the object is fixed to \SI{0.13}{\meter} above the base of the hand to ensure that the object does not collide with the hand at initialization. The initial and goal orientations are randomly sampled from the full $SO(3)$ space. \textbf{Setup with the downward facing hand}: Next, we consider the cases where the hand faces downward. We experiment with two scenarios: with and without a table below the hand. In the first case, we place a table with the tabletop being \SI{0.12}{\meter} below the hand base. We place objects in a random pose between the hand and the table so that the objects will fall onto the table. We will describe the setup for the second case (without a table) in \secref{subsec:reorient_air}. \textbf{Evaluation criterion}: For non-vision experiments, a policy rollout is considered a success if $\theta\leq\Bar{\theta}$. $\Bar{\theta}=\SI{0.1}{\radian}$. For vision experiments, we also check $d_C\leq \Bar{d}_C$ as another criterion and $\Bar{\theta}=\SI{0.2}{\radian}, \Bar{d}_C=0.01$. The initial and goal orientation are randomly sampled from $SO(3)$ space in all the experiments. We report performance as the percentage of successful episodes when the agent is tasked to reorient each training object $100$ times from arbitrary start to goal orientation. We report the mean and standard deviation of success rate from $3$ seeds. \section{Results} \label{sec:results} We evaluate the performance of reorientation policies with the hand facing upward and downward. Further we analyze the generalization of the learned policies to unseen object shapes. \subsection{Reorient objects with the hand facing upward} \label{subsec: result_hand_up} \paragraph{Train a teacher policy with full-state information} We train our teacher MLP and RNN policies using the full state information using all objects in the EGAD and YCB datasets separately. The progression of success rate during training is shown in \figref{fig:egad_learn_upward} in \appref{app_subsec:hand_up} . \figref{fig:egad_learn_upward} also shows that using privileged information substantially speeds up policy learning. Results reported in \tblref{tbl:up_success_rate_short} indicate that the RNN policies achieve a success rate greater than 90\% on the EGAD dataset (entry B1) and greater than 80\% on the YCB dataset (entry G1) without any explicit knowledge of the object shape\footnote{More quantitative results on the MLP policies are available in \tblref{tbl:up_success_rate} in the appendix.}. This result is surprising because apriori one might believe that shape information is important for in-hand reorientation of diverse objects. The visualization of policy rollout reveals that the agent employs a clever strategy that is invariant to object geometry for re-orienting objects. The agent throws the object in the air with a spin and catches it at the precise time when the object's orientation matches the goal orientation. Throwing the object with a spin is a dexterous skill that automatically emerges! One possibility for the emergence of this skill is that we used very light objects. This is not true because we trained with objects in the range of 50-150g which spans many hand-held objects used by humans (e.g., an egg weighs about 50g, a glass cup weighs around 100g, iPhone 12 weighs 162g, etc.). To further probe this concern, we evaluated zero-shot performance on objects weighing up to 500g\footnote{We change the mass of the YCB objects to be in the range of $[0.3, 0.5]$kg, and test $\pi_R^\expsymbol$ from the YCB dataset on these new objects. The success rate is around $75\%$.} and found that the learned policy can successfully reorient them. We provide further analysis in the appendix showing that forces applied by the hand for such manipulation are realistic. While there is still room for the possibility that the learned policy is exploiting the simulator to reorient objects by throwing them in the air, our analysis so far indicates otherwise. Next, to understand the failure modes, we collected one hundred unsuccessful trajectories on YCB dataset and manually analyzed them. The primary failure is in manipulating long, small, or thin objects, which accounts for $60\%$ of all errors. In such cases, either the object slips through the fingers and falls, or is hard to be manipulated when the objects land on the palm. Another cause of failures ($19\%$) is that objects are reoriented close to the goal orientation but not close enough to satisfy $\Delta\theta<\Bar{\theta}$. Finally, the performance on YCB is lower than EGAD because objects in the YCB dataset are more diverse in their aspect ratios. Scaling these objects by constraining $l_{\max} \in[0.05, 0.12]$m (see \secref{sec:env_setup}) makes some of these objects either too small, too big, or too thin and consequently results in failure (see \figref{fig:failure_cases_up}). A detailed object-wise quantitative analysis of performance is reported in appendix \figref{fig:success_rate_ycb_up}. Results confirm that sphere-like objects such as tennis balls and orange are easiest to reorient, while long/thin objects such as knives and forks are the hardest to manipulate. \renewcommand{\arraystretch}{1.1} \begin{table} \centering \caption{\small{Success rates (\%) of policies tested on different dynamics distribution. $\Bar{\theta}=0.1$\si{\radian}. DR: domain randomization and observation/action noise. X$\rightarrow$Y: distill policy X into policy Y. The full table is in \tblref{tbl:up_success_rate}.}} \label{tbl:up_success_rate_short} \resizebox{\columnwidth}{!}{ \begin{tabular}{cccc|ccc} \hline \multicolumn{4}{c}{} & 1 & 2 & 3 \\ \hline \multirow{2}{*}{Exp. ID} & \multirow{2}{*}{Dataset} & \multirow{2}{*}{State} & \multicolumn{1}{c}{\multirow{2}{*}{Policy}} & \multicolumn{2}{c}{Train without DR} & Train with DR \\ \cline{5-7} & & & \multicolumn{1}{c}{} & \multicolumn{1}{l}{Test without DR} & Test with DR & Test with DR \\ \hline B & \multirow{2}{*}{EGAD} & Full state & RNN & 95.95 $\pm$ 0.8 & 84.27 $\pm$ 1.0 & 88.04 $\pm$ 0.6 \\ E & & Reduced state & RNN$\rightarrow$RNN & 91.96 $\pm$ 1.5 & 78.30 $\pm$ 1.2 & 80.29 $\pm$ 0.9 \\ \hline G & \multirow{2}{*}{YCB} & Full state & RNN & 80.40 $\pm$ 1.6 & 65.16 $\pm$ 1.0 & 72.34 $\pm$ 0.9 \\ J & & Reduced state & RNN$\rightarrow$RNN & 81.04 $\pm$ 0.5 & 64.93 $\pm$ 0.2 & 65.86 $\pm$ 0.7 \\ \hline \end{tabular} } \end{table} \renewcommand{\arraystretch}{1} \vspace{-0.2cm} \paragraph{Train a student policy with a reduced state space} The student policy state is $s_t^\mathcal{S}\in\mathbb{R}^{31}$. In \tblref{tbl:up_success_rate_short} (entries E1 and J1), we can see that $\pi_R^\stusymbol$ can get similarly high success rates as $\pi_R^\expsymbol$. The last two columns in \tblref{tbl:up_success_rate_short} also show that the policy is more robust to dynamics variations and observation/action noise after being trained with domain randomization. \subsection{Reorient objects with the hand facing downward} \label{subsec: hand_down} The results above demonstrate that when the hand faces upwards, RL can be used to train policies for reorienting a diverse set of geometrically different objects. A natural question to ask is, does this still hold true when the hand is flipped upside down? Intuitively, this task is much more challenging because the objects will immediately fall down without specific finger movements that stabilize the object. Because with the hand facing upwards, the object primarily rests on the palm, such specific finger movements are not required. Therefore, the hand facing downwards scenario presents a much harder exploration challenge. To verify this hypothesis, we trained a policy with the downward-facing hand, objects placed underneath the hand (see \figref{fig:down_random}), and using the same reward function (\equaref{eqn:rot_reward}) as before. Unsurprisingly, the success rate was $0\%$. The agent's failure can be attributed to policy needing to learn to both stabilize the object under the effect of gravity and simultaneously reorient it. Deploying this policy simply results in an object falling down, confirming the hard-exploration nature of this problem. \subsubsection{Reorient objects on a table} \label{subsec:reorient_table} To tackle the hard problem of reorienting objects with the hand facing downward, we started with a simplified task setup that included a table under the hand (see \figref{fig:down_table}). Table eases exploration by preventing the objects from falling. We train $\pi_M^\expsymbol$ using the same reward function \equaref{eqn:rot_reward} on objects sampled from the EGAD and YCB datasets. The success rate using an MLP policy using full state information for EGAD and YCB is $95.31\%\pm 0.9\%$ and $81.59\%\pm 0.7\%$ respectively. Making use of external support for in-hand manipulation has been a challenging problem in robotics. Prior work approach this problem by building analytical models and constructing motion cones~\citep{chavan2018hand}, which is challenging for objects with complex geometry. Our experiments show that model-free RL provides an effective alternative for learning manipulation strategies capable of using external support surfaces. \subsubsection{Reorient objects in air with hand facing downward} \label{subsec:reorient_air} To enable the agent to operate in more general scenarios, we tackled the re-orientation problem with the hand facing downwards and without any external support. In this setup, one might hypothesize that object shape information (e.g., from vision) is critical because finding the strategy in \secref{subsec: result_hand_up} is not easy when the hand needs to overcome gravity and stabilize the object while reorienting it. We experimentally verify that even in this case, the policies achieve a reasonably high success rate without any knowledge of object shape. \textbf{A good pose initialization is what you need}: The difficulty of directly training the RL policies when the hand faces downward is mainly because of the hard-exploration issue in learning to catch the objects that are moving downward. However, catching is not necessary for the reorientation. Even for human, we only reorient the object after we grasp it. More specifically, we first train an object-lifting policy to lift objects from the table, collect the ending state (joint positions $q_T$, object position $p^o_T$ and orientation $\alpha^o_T$) in each successful lifting rollout episode, and reset the hand and objects to these states (velocities are all $0$) for the pose initialization in training the reorientation policy. The objects have randomly initialized poses and are dropped onto the table. We trained a separate RNN policy for each dataset using the reward function in \secref{app_sec:training_details}. The success rate on the EGAD dataset is $97.80\%$, while the success rate on the YCB dataset is $90.11\%$. Note that objects need to be grasped first to be lifted. Our high success rates on object lifting also indicate that using an anthropomorphic hand makes object grasping an easy task, while many prior works~\citep{mousavian2019graspnet, mahler2017dex} require much more involved training techniques to learn grasping skills with parallel-jaw grippers. After we train the lifting policy, we collect about $250$ ending states for each object respectively from the successful lifting episodes. In every reset during the reorientation policy training, ending states are randomly sampled and used as the initial pose of the fingers and objects. With a good pose initialization, policies are able to learn to reorient objects with high success rates. $\pi_R^\expsymbol$ trained on EGAD dataset gets a success rate more than $80\%$ while $\pi_R^\expsymbol$ trained on YCB dataset gets a success rate greater than $50\%$. More results on the different policies with and without domain randomization are available in \tblref{tbl:down_air_success_rate} in the appendix. This setup is challenging because if at any time step in an episode the fingers take a bad action, the object will fall. \textbf{Improving performance using gravity curriculum}: Since the difficulty of training the re-orientation policy with the hand facing downward is due to the gravity, we propose to build a gravity curriculum to learn the policy $\pi^\expsymbol$. Since $\pi^\expsymbol$ already performs very well on EGAD objects, we apply gravity curriculum to train $\pi^\expsymbol$ on YCB objects. Our gravity curriculum is constructed as follows: we start the training with $g=\SI{1}{\meter\per\second^2}$, then we gradually decrease $g$ in a step-wise fashion if the evaluation success rate ($w$) is above a threshold value ($\Bar{w}$) until $g=-\SI{9.81}{\meter\per\second^2}$. More details about gravity curriculum are in \secref{subsec:grav_curr}. In \tblref{tbl:down_air_success_rate} (Exp Q and T) in the appendix, we can see that adding gravity curriculum ($g$-curr) significantly boost the success rates on the YCB dataset. \renewcommand{\arraystretch}{1.1} \begin{table} \centering \caption{Performance of the student policy when the hand faces upward and downward} \label{tbl:summary_up_down} \small{ \begin{tabular}{cccc} \hline Dataset & Upward & Downward (air) & Downward (air, $g$-curr) \\ \hline EGAD & 91.96 $\pm$ 1.5 & 74.10 $\pm$ 2.3 & $\diagup$ \\ YCB & 81.04 $\pm$ 0.5 & 45.22 $\pm$ 2.1 & 67.33 $\pm$ 1.9 \\ \hline \end{tabular}} \end{table} \renewcommand{\arraystretch}{1} \subsection{Zero-shot policy transfer across datasets} \label{subsec:zero_shot} We have shown the testing performance on the same training dataset so far. How would the policies work on a different dataset? To answer this, we test our policies across datasets: policies trained with EGAD objects are now tested with YCB objects and vice versa. We used the RNN policies trained with full-state information and reduced-state information respectively (without domain randomization) and tested them on the other dataset with the hand facing upward and downward. In the case of the hand facing downward, we tested the RNN policy trained with gravity curriculum. \tblref{tbl:zero_shot} shows that policies still perform well on the untrained dataset. \begin{table}[!tb] \begin{minipage}[t]{.47\linewidth} \vspace{-0.5cm} \caption{\small{Zero-shot RNN policy transfer success rates (\%) across datasets. \textbf{U.} (\textbf{D.}) means hand faces upward (downward). \textbf{FS} (\textbf{RS}) means using full-state (reduced-state) information. }} \label{tbl:zero_shot} \centering \renewcommand{\arraystretch}{1.1} \resizebox{\columnwidth}{!}{ \begin{tabular}{c|ccc} \cline{1-3} \multicolumn{1}{c}{} & EGAD~$\rightarrow$~YCB & YCB~$\rightarrow$~EGAD & \\ \cline{1-3} \textbf{U.FS} & $68.82\pm1.7$ & $96.41\pm 1.2$ & \\ \textbf{U.RS} & $59.64\pm 1.8$ & $96.38\pm 1.3$ & \\ \textbf{D.FS} & $62.73\pm 2.2$ & $85.45\pm 2.9$ & \\ \textbf{D.RS} & $55.30\pm 1.3$ & $77.91\pm 2.1$ & \\ \cline{1-3} \multicolumn{1}{c}{} & & & \\ \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} & \multicolumn{1}{l}{} \end{tabular} } \renewcommand{\arraystretch}{1} \end{minipage}% \hfill \begin{minipage}[t]{.48\linewidth} \vspace{-0.5cm} \centering \caption{\small{Vision policy success rate ($\Bar{\theta}=\SI{0.2}{\radian}, \Bar{d}_C=0.01$)}} \label{tbl:vision_pol_noise} \resizebox{0.95\columnwidth}{!}{ \renewcommand{\arraystretch}{1.1} \begin{tabular}{clc} \hline \multicolumn{2}{c}{Object} & Success rate (\%) \\ \hline \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/025_mug.jpeg} \end{minipage} & 025\_mug & $89.67 \pm 1.2$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/065-d_cups.jpeg} \end{minipage}& 065-d\_cups & $68.32\pm 1.9$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/072-b_toy_airplane.jpeg} \end{minipage}&072-b\_toy\_airplane & $84.52 \pm 1.4$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/073-a_lego_duplo.jpeg} \end{minipage}& 073-a\_lego\_duplo & $58.16 \pm 3.1$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/073-c_lego_duplo.jpeg} \end{minipage} &073-c\_lego\_duplo & $50.21 \pm 3.7$ \\ \begin{minipage}{.06\textwidth} \includegraphics[width=\linewidth]{figures/ycb/073-e_lego_duplo.jpeg} \end{minipage}&073-e\_lego\_duplo & $66.57\pm 3.1$ \\ \hline \end{tabular} \renewcommand{\arraystretch}{1.} } \end{minipage} \vspace{-1.cm} \end{table} \subsection{Object Reorientation with RGBD sensors} \label{subsec:vision_exp} In this section, we investigate whether we can train a vision policy to reorient objects with the hand facing upward. As vision-based experiments require much more compute resources, we train one vision policy for each object individually on six objects shown in \tblref{tbl:vision_pol_noise}. We leave training a single vision policy for all objects to future work. We use the expert MLP policy trained in \secref{subsec: result_hand_up} to supervise the vision policy. We also performed data augmentation on the point cloud input to the policy network at each time step in both training and testing. The data augmentation includes the random translation of the point cloud, random noise on the point positions, random dropout on the points, and random variations on the point color. More details about the data augmentation are in \secref{app_subsec:vision_noise}. We can see from \tblref{tbl:vision_pol_noise} that reorienting the non-symmetric objects including the toy and the mug has high success rates (greater than $80\%$). While training the policy for symmetric objects is much harder, \tblref{tbl:vision_pol_noise} shows that using $d_C$ as an episode termination criterion enables the policies to achieve a success rate greater than $50\%$. \section{Related Work} \label{sec:related} Dexterous manipulation has been studied for decades, dating back to \citep{salisbury1982articulated, mason1989robot}. In contrast to parallel-jaw grasping, pushing, pivoting~\citep{karayiannidis2016adaptive}, or pick-and-place, dexterous manipulation typically involves continuously controlling force to the object through the fingertips of a robotic hand~\citep{dafle2014extrinsic}. Some prior works used analytical kinematics and dynamics models of the hand and object, and used trajectory optimization to output control policies~\citep{mordatch2012contact, bai2014dexterous, sundaralingam2019relaxed} or employed kinodynamic planning to find a feasible motion plan~\citep{rus1999hand}. However, due to the large number of active contacts on the hand and the objects, model simplifications such as simple finger and object geometries are usually necessary to make the optimization or planning tractable. \citet{sundaralingam2019relaxed} moved objects in hand but assumes that there is no contact breaking or making between the fingers and the object. \citet{furukawa2006dynamic} achieved a high-speed dynamic regrasping motion on a cylinder using a high-speed robotic hand and a high-speed vision system. Prior works have also explored the use of a vision system for manipulating an object to track a planned path~\citep{calli2018path}, detecting manipulation modes~\citep{calli2018learning}, precision manipulation~\citep{calli2017vision} with a limited number of objects with simple shapes using a two-fingered gripper. Recent works have explored the application of reinforcement learning to dexterous manipulation. Model-based RL works learned a linear ~\citep{kumar2016optimal, kumar2016learning} or deep neural network~\citep{nagabandi2020deep} dynamics model from the rollout data, and used online optimal control to rotate a pen or Baoding balls on a Shadow hand. However, when the system is unstable, collecting informative trajectories for training a good dynamics model that generalizes to different objects remains challenging. Another line of works uses model-free RL algorithms to learn a dexterous manipulation policy. For example, \citet{andrychowicz2020learning} and \citet{akkaya2019solving} learned a controller to reorient a block or a Rubik's cube. \citet{van2015learning} learned the tactile informed policy via RL for a three-finger manipulator to move an object on the table. To reduce the sample complexity of model-free learning, \citep{radosavovic2020state, zhu2019dexterous, rajeswaran2017learning, jeong2020learning, gupta2016learning} combined imitation learning with RL to learn to reorient a pen, open a door, assemble LEGO blocks, etc. However, collecting expert demonstration data from humans is expensive, time-consuming, and even incredibly difficult for contact-rick tasks~\citep{rajeswaran2017learning}. Our method belongs to the category of model-free learning. We use the teacher-student learning paradigm to speed up the deployment policy learning. Our learned policies also generalize to new shapes and show strong zero-shot transfer performance. To the best of our knowledge, our system is the first work that demonstrates the capabilities of reorienting a diverse set of objects that have complex geometries with both the hand facing upward and downward. A recent work~\citep{huang2021geometry} (after our CoRL submission) learns a shape-conditioned policy to reorient objects around $z$-axis with an upward-facing hand. Our work tackles more general tasks (more diverse objects, any goal orientation in $SO(3)$, hand faces upward and downward) and shows that even without knowing any object shape information, the policies can get surprisingly high success rates in these tasks. \section{Discussion and Conclusion} Our results show that model-free RL with simple deep learning architectures can be used to train policies to reorient a large set of geometrically diverse objects. Further, for learning with the hand facing downwards, we found that a good pose initialization obtained from a lifting policy was necessary, and the gravity curriculum substantially improved performance. The agent also learns to use an external surface (i.e., the table). The most surprising observation is that information about shape is not required despite the fact that we train a single policy to manipulate multiple objects. Perhaps in hindsight, it is not as surprising -- after all, humans can close their eyes and easily manipulate novel objects into a specific orientation. % Our work can serve a strong baseline for future in-hand object reorientation works that incorporate object shape in the observation space.% While we only present results in simulation, we also provide evidence that our policies can be transferred to the real world. The experiments with domain randomization indicate that learned policies can work with noisy inputs. Analysis of peak torques during manipulation (see \figref{fig:torque} in the appendix) also reveals that generated torque commands are feasible to actuate on an actual robotic hand. Finally, \figref{fig:success_rate_ycb_up} and \figref{fig:success_rate_ycb_down} in the appendix show that the success rate varies substantially with object shape. This suggests that in the future, a training curriculum based on object shapes can improve performance. Another future work is to directly train one vision policy for a diverse set of objects. A major bottleneck in vision-based experiments is the demand for much larger GPU memory. Learning visual representations of point cloud data that can ease the computational bottleneck is, therefore, an important avenue for future research. \acknowledgments{ We thank the anonymous reviewers for their helpful comments in revising the paper. We thank the members of Improbable AI lab for providing valuable feedback on research idea formulation and manuscript. This research is funded by Toyota Research Institute, Amazon Research Award, and DARPA Machine Common Sense Program. We also acknowledge the MIT SuperCloud and Lincoln Laboratory Supercomputing Center for providing HPC resources that have contributed to the research results reported within this paper.}
{'timestamp': '2021-11-05T01:22:22', 'yymm': '2111', 'arxiv_id': '2111.03043', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03043'}
arxiv
\section{Introduction} This document is a model and instructions for \LaTeX. Please observe the conference page limits. \section{Ease of Use} \subsection{Maintaining the Integrity of the Specifications} The IEEEtran class file is used to format your paper and style the text. All margins, column widths, line spaces, and text fonts are prescribed; please do not alter them. You may note peculiarities. For example, the head margin measures proportionately more than is customary. This measurement and others are deliberate, using specifications that anticipate your paper as one part of the entire proceedings, and not as an independent document. Please do not revise any of the current designations. \section{Prepare Your Paper Before Styling} Before you begin to format your paper, first write and save the content as a separate text file. Complete all content and organizational editing before formatting. Please note sections \ref{AA}--\ref{SCM} below for more information on proofreading, spelling and grammar. Keep your text and graphic files separate until after the text has been formatted and styled. Do not number text heads---{\LaTeX} will do that for you. \subsection{Abbreviations and Acronyms}\label{AA} Define abbreviations and acronyms the first time they are used in the text, even after they have been defined in the abstract. Abbreviations such as IEEE, SI, MKS, CGS, ac, dc, and rms do not have to be defined. Do not use abbreviations in the title or heads unless they are unavoidable. \subsection{Units} \begin{itemize} \item Use either SI (MKS) or CGS as primary units. (SI units are encouraged.) English units may be used as secondary units (in parentheses). An exception would be the use of English units as identifiers in trade, such as ``3.5-inch disk drive''. \item Avoid combining SI and CGS units, such as current in amperes and magnetic field in oersteds. This often leads to confusion because equations do not balance dimensionally. If you must use mixed units, clearly state the units for each quantity that you use in an equation. \item Do not mix complete spellings and abbreviations of units: ``Wb/m\textsuperscript{2}'' or ``webers per square meter'', not ``webers/m\textsuperscript{2}''. Spell out units when they appear in text: ``. . . a few henries'', not ``. . . a few H''. \item Use a zero before decimal points: ``0.25'', not ``.25''. Use ``cm\textsuperscript{3}'', not ``cc''.) \end{itemize} \subsection{Equations} Number equations consecutively. To make your equations more compact, you may use the solidus (~/~), the exp function, or appropriate exponents. Italicize Roman symbols for quantities and variables, but not Greek symbols. Use a long dash rather than a hyphen for a minus sign. Punctuate equations with commas or periods when they are part of a sentence, as in: \begin{equation} a+b=\gamma\label{eq} \end{equation} Be sure that the symbols in your equation have been defined before or immediately following the equation. Use ``\eqref{eq}'', not ``Eq.~\eqref{eq}'' or ``equation \eqref{eq}'', except at the beginning of a sentence: ``Equation \eqref{eq} is . . .'' \subsection{\LaTeX-Specific Advice} Please use ``soft'' (e.g., \verb|\eqref{Eq}|) cross references instead of ``hard'' references (e.g., \verb|(1)|). That will make it possible to combine sections, add equations, or change the order of figures or citations without having to go through the file line by line. Please don't use the \verb|{eqnarray}| equation environment. Use \verb|{align}| or \verb|{IEEEeqnarray}| instead. The \verb|{eqnarray}| environment leaves unsightly spaces around relation symbols. Please note that the \verb|{subequations}| environment in {\LaTeX} will increment the main equation counter even when there are no equation numbers displayed. If you forget that, you might write an article in which the equation numbers skip from (17) to (20), causing the copy editors to wonder if you've discovered a new method of counting. {\BibTeX} does not work by magic. It doesn't get the bibliographic data from thin air but from .bib files. If you use {\BibTeX} to produce a bibliography you must send the .bib files. {\LaTeX} can't read your mind. If you assign the same label to a subsubsection and a table, you might find that Table I has been cross referenced as Table IV-B3. {\LaTeX} does not have precognitive abilities. If you put a \verb|\label| command before the command that updates the counter it's supposed to be using, the label will pick up the last counter to be cross referenced instead. In particular, a \verb|\label| command should not go before the caption of a figure or a table. Do not use \verb|\nonumber| inside the \verb|{array}| environment. It will not stop equation numbers inside \verb|{array}| (there won't be any anyway) and it might stop a wanted equation number in the surrounding equation. \subsection{Some Common Mistakes}\label{SCM} \begin{itemize} \item The word ``data'' is plural, not singular. \item The subscript for the permeability of vacuum $\mu_{0}$, and other common scientific constants, is zero with subscript formatting, not a lowercase letter ``o''. \item In American English, commas, semicolons, periods, question and exclamation marks are located within quotation marks only when a complete thought or name is cited, such as a title or full quotation. When quotation marks are used, instead of a bold or italic typeface, to highlight a word or phrase, punctuation should appear outside of the quotation marks. A parenthetical phrase or statement at the end of a sentence is punctuated outside of the closing parenthesis (like this). (A parenthetical sentence is punctuated within the parentheses.) \item A graph within a graph is an ``inset'', not an ``insert''. The word alternatively is preferred to the word ``alternately'' (unless you really mean something that alternates). \item Do not use the word ``essentially'' to mean ``approximately'' or ``effectively''. \item In your paper title, if the words ``that uses'' can accurately replace the word ``using'', capitalize the ``u''; if not, keep using lower-cased. \item Be aware of the different meanings of the homophones ``affect'' and ``effect'', ``complement'' and ``compliment'', ``discreet'' and ``discrete'', ``principal'' and ``principle''. \item Do not confuse ``imply'' and ``infer''. \item The prefix ``non'' is not a word; it should be joined to the word it modifies, usually without a hyphen. \item There is no period after the ``et'' in the Latin abbreviation ``et al.''. \item The abbreviation ``i.e.'' means ``that is'', and the abbreviation ``e.g.'' means ``for example''. \end{itemize} An excellent style manual for science writers is \cite{b7}. \subsection{Authors and Affiliations} \textbf{The class file is designed for, but not limited to, six authors.} A minimum of one author is required for all conference articles. Author names should be listed starting from left to right and then moving down to the next line. This is the author sequence that will be used in future citations and by indexing services. Names should not be listed in columns nor group by affiliation. Please keep your affiliations as succinct as possible (for example, do not differentiate among departments of the same organization). \subsection{Identify the Headings} Headings, or heads, are organizational devices that guide the reader through your paper. There are two types: component heads and text heads. Component heads identify the different components of your paper and are not topically subordinate to each other. Examples include Acknowledgments and References and, for these, the correct style to use is ``Heading 5''. Use ``figure caption'' for your Figure captions, and ``table head'' for your table title. Run-in heads, such as ``Abstract'', will require you to apply a style (in this case, italic) in addition to the style provided by the drop down menu to differentiate the head from the text. Text heads organize the topics on a relational, hierarchical basis. For example, the paper title is the primary text head because all subsequent material relates and elaborates on this one topic. If there are two or more sub-topics, the next level head (uppercase Roman numerals) should be used and, conversely, if there are not at least two sub-topics, then no subheads should be introduced. \subsection{Figures and Tables} \paragraph{Positioning Figures and Tables} Place figures and tables at the top and bottom of columns. Avoid placing them in the middle of columns. Large figures and tables may span across both columns. Figure captions should be below the figures; table heads should appear above the tables. Insert figures and tables after they are cited in the text. Use the abbreviation ``Fig.~\ref{fig}'', even at the beginning of a sentence. \begin{table}[htbp] \caption{Table Type Styles} \begin{center} \begin{tabular}{|c|c|c|c|} \hline \textbf{Table}&\multicolumn{3}{|c|}{\textbf{Table Column Head}} \\ \cline{2-4} \textbf{Head} & \textbf{\textit{Table column subhead}}& \textbf{\textit{Subhead}}& \textbf{\textit{Subhead}} \\ \hline copy& More table copy$^{\mathrm{a}}$& & \\ \hline \multicolumn{4}{l}{$^{\mathrm{a}}$Sample of a Table footnote.} \end{tabular} \label{tab1} \end{center} \end{table} \begin{figure}[htbp] \centerline{\includegraphics{fig1.png}} \caption{Example of a figure caption.} \label{fig} \end{figure} Figure Labels: Use 8 point Times New Roman for Figure labels. Use words rather than symbols or abbreviations when writing Figure axis labels to avoid confusing the reader. As an example, write the quantity ``Magnetization'', or ``Magnetization, M'', not just ``M''. If including units in the label, present them within parentheses. Do not label axes only with units. In the example, write ``Magnetization (A/m)'' or ``Magnetization \{A[m(1)]\}'', not just ``A/m''. Do not label axes with a ratio of quantities and units. For example, write ``Temperature (K)'', not ``Temperature/K''. \section*{Acknowledgment} The preferred spelling of the word ``acknowledgment'' in America is without an ``e'' after the ``g''. Avoid the stilted expression ``one of us (R. B. G.) thanks $\ldots$''. Instead, try ``R. B. G. thanks$\ldots$''. Put sponsor acknowledgments in the unnumbered footnote on the first page. \section*{References} Please number citations consecutively within brackets \cite{b1}. The sentence punctuation follows the bracket \cite{b2}. Refer simply to the reference number, as in \cite{b3}---do not use ``Ref. \cite{b3}'' or ``reference \cite{b3}'' except at the beginning of a sentence: ``Reference \cite{b3} was the first $\ldots$'' Number footnotes separately in superscripts. Place the actual footnote at the bottom of the column in which it was cited. Do not put footnotes in the abstract or reference list. Use letters for table footnotes. Unless there are six authors or more give all authors' names; do not use ``et al.''. Papers that have not been published, even if they have been submitted for publication, should be cited as ``unpublished'' \cite{b4}. Papers that have been accepted for publication should be cited as ``in press'' \cite{b5}. Capitalize only the first word in a paper title, except for proper nouns and element symbols. For papers published in translation journals, please give the English citation first, followed by the original foreign-language citation \cite{b6}. \section{Introduction} Every year fire causes severe damage to persons and property all over the world. Artificial intelligence can play an important role to battle the fire incidents by early detection and localization of the fire spots. Many methods have already been proposed for detection of fire and smoke on images and videos in different scenarios such as wildfires. Traditional methods were based on handcrafted features extracted mostly from individual pixel colors \cite{celik2009fire, chen2004early}. Recently, analogously to many other computer vision areas, the state-of-the-art results have been achieved for fire detection using features from Convolutional Neural Networks (CNN). Methods were mainly proposed for classification of fire in images \cite{dunnings2018experimentally, barmpoutis2019fire}. Some methods consider the localization of fire in images as well \cite{zhang2016deep, chaoxia2020information}. Localization of fire is important for determining the exact spot of the fire in images which has applications in autonomous systems and geo-referencing of the fire location. Like \cite{harkat2021fire, frizzi2021convolutional}, we consider pixel-wise segmentation for fire localization, which corresponds to the binary semantic segmentation to detect fire in images. Although bounding boxes can be used for localization, pixel-wise segmentation has advantages e.g. it can be used as input for fire propagation models. However, most segmentation methods are localized and do not consider global contextual information in images. In the case of fire detection, even recent well-known segmentation methods produce many incorrect false positive pixel segmentations for fire-like images due to these localized predictions (see Fig. \ref{fig:falsepositives}). This false positive prediction is an important issue in fire detection as it may lead to false alarms. Recently, self-attention mechanisms have attracted lots of interest in computer vision. The purpose of self-attention methods is to use long range information and increase the receptive field sizes of current deep neural networks \cite{wang2018non}. Self-attention tends to capture the correlation between different image regions by computing a weighted average of all features in different locations in which the weights are computed based on the similarities between their corresponding embeddings. Some works consider deep architecture composed of only self-attention layers as a replacement for the convolutional networks \cite{bello2019attention}. Apart from self-attention, which uses the input features itself to compute the attention coefficients, some methods proposed to use attention based on the features extracted from other parts of the network \cite{oktay2018attention}. Multi-task learning methods learn simultaneously multiple correlated computer vision tasks (e.g. semantic segmentation and depth estimation) in a unified network through learning common features \cite{jafari2017analyzing, dharmasiri2017joint, zhang2018joint}. It has been shown that this multi-task learning leads to improvement in performance and reduction of training complexity compared to using separate networks for each task . In our application, the features in the higher layers of a CNN contain both localization and classification informations \cite{long2015fully, zhou2016learning}. Consequently, in \cite{le2019multitask}, a method is proposed for joint classification and segmentation of medical images, in which a classification network is applied to the features of the last layer of the encoder (the coarsest layer) in a encoding-decoding segmentation CNN. In this paper, we propose a new CNN that jointly classifies and segments fire in images with improved segmentation performance. We propose an attention mechanism that uses the classification output as the channel attention coefficient of the segmentation output. This allows the overall network to consider the global classification information on the segmentation masks. Furthermore, we use a self-attention model to capture the long-range spatial correlations within each channel. Experiments show that the proposed method with the attention mechanism outperforms other methods in the segmentation metrics. It reduces the false positive results in the segmentation masks, while at the same time, is able to identify small scale fires in images, resulting in state-of-the-art results among fire segmentation methods. In the following sections, we first mention related works for segmentation, multi-task learning, and self-attention. We then describe our proposed method in detail, and finally compare our method with other segmentation, and multitask classification-segmentation methods. \section{Related works} Traditional methods for fire detection mainly use hand-crafted features such as color features \cite{celik2009fire}, \cite{chen2004early}, covariance-based features \cite{habibouglu2012covariance}, wavelet coefficients \cite{toreyin2006computer}, and then classify the obtained features using a vector classifier e.g. a Support Vector Machine (SVM). Recently, methods based on CNN have improved the performance of fire and smoke detection noticeably. The method in \cite{dunnings2018experimentally} uses simplified structures of the Alexnet \cite{krizhevsky2012imagenet} and Inception networks \cite{szegedy2015going} for fire image classification. In \cite{barmpoutis2019fire}, Faster Region-CNN (R-CNN) \cite{ren2015faster} is used to extract fire candidate regions, and is further processed by multidimensional texture analysis using Linear Dynamical Systems (LDS) to classify the fire images. Some works consider localization of fire in images, beyond classification. In \cite{zhang2016deep}, a method for classification and patch-wise localization was proposed in which the last convolutional layer of the classification network is used for the patch classification. In \cite{chaoxia2020information}, a combination of color features, and Faster R-CNN is used to increase the efficiency of the algorithm by disregarding some anchors of R-CNN based on some color features. Some methods consider pixel-wise segmentation for fire images as well. In \cite{harkat2021fire}, deep-lab semantic segmentation is adapted for pixel segmentation of fire. In \cite{frizzi2021convolutional}, a new CNN architecture is proposed for segmentation of fire in images. In computer vision, single end-to-end multi-task networks have shown promising results for the tasks that have cross-dependency such as semantic segmentation and depth estimation \cite{jafari2017analyzing, dharmasiri2017joint}. They benefit from learning common features. It has been shown that exploiting the cross-dependency between the tasks lead to to improvement in performance compared to the networks independently trained for the two tasks \cite{dharmasiri2017joint}. It has other benefits such as reducing the training time. It is known that the features in the last convolutional layer in CNNs trained for classification have also spatial information for localization \cite{long2015fully, zhou2016learning}. Le et. al. \cite{le2019multitask} proposed a method for joint classification and segmentation for cancer diagnosis in mammography, in which the last convolution layer of the encoder in the segmentation network is used for the global classification. Self-attention models have recently demonstrated improved results in many computer vision tasks \cite{wang2018non, bello2019attention, fu2019dual}. Self-attention models compute attention coefficients based on the similarities between input features. New features are then obtained by a weighted average of the input features with the self-attention coefficients. Beyond self-attention, there are also attention mechanisms proposed for image classification \cite{wang2017residual, jetley2018learn}, and semantic segmentation \cite{oktay2018attention}, in which the attention weights are computed using the features in other parts of the CNN. \section{Proposed method} A simple approach to learn a joint classification and segmentation in a unified CNN is to classify images based on the features after global pooling of the coarsest layer (last encoding layer) of the encoder-decoder segmentation network. The network can be jointly trained with the classification and segmentation labels through a weighted loss. This approach has been previously proposed in \cite{le2019multitask} for medical imaging application. \begin{figure*} \centering \includegraphics[width=.8\textwidth, frame]{Attention_cnn} \caption{Proposed CNN architecture for joint classification and segmentation; for the segmentation backbone deeplab v3 \cite{chen2017rethinking} is used. } \label{fig:network} \end{figure*} In this paper we add two attention modules to consider both global classification score and correlation in the spatial locations, in the segmentation predictions. As the first attention module, we propose to use a channel attention in the segmented output. As shown in Fig. \ref{fig:network}, it multiplies the attention weight to the output channel, in which the weight is the probability assigned by the classification branch of the network. The channel is then added to the resulting features, similar to self-attention approaches \cite{wang2018non}. Let, $\mathbf{x} \in \mathbb{R}^{W \times H \times 3}$ be the RGB image, and let $s(\mathbf{x}) \in \mathbb{R}$ and $\mathbf{A}(\mathbf{x}) \in \mathbb{R}^{W \times H \times 1}$ be the classification probability and segmentation features extracted by the CNN, respectively. $\mathbf{A}(\mathbf{x})$ could be the output of any segmentation network. In this paper, we use deeplab v3+ encoder and decoder \cite{chen2018encoder} to extract the features. $s(\mathbf{x}) \in [0,1]$ is computed by the sigmoid function of the classification scores obtained by the classification branch (see Fig. \ref{fig:network}). Following \cite{fu2019dual}, we compute the channel attention model as \begin{equation} \mathbf{A}'({\mathbf{x}})=\mathbf{A}(\mathbf{x})+\alpha s(\mathbf{x}) \mathbf{A}(\mathbf{x}) \label{eq:module} \end{equation} where $\mathbf{A}'$ indicates the features after applying the attention module, and $\alpha$ is a parameter which is initialized to zero and learnt during training \cite{fu2019dual}. The method in \cite{fu2019dual} used a channel attention model for the segmentation in which the channel weights are obtained by the features themselves using a self-attention approach. However in our method, the weight $s(\mathbf{x})$ is the classification probability which is computed in the classification branch. This approach is supposed to reduce the false positive results as the correct classification output $s(\mathbf{x})$ for a non-fire image is close to zero, so it attenuates the activation of the segmentation output $\mathbf{A}'$. In the case of fire, a value of $s(\mathbf{x})$ close to one helps to recognize even small portions fire in images. This also encourages the consistency of the results between the segmentation and classification outputs. \begin{figure} \centering \includegraphics[width=.45\textwidth, frame]{self_attention} \caption{Spatial self-attention module used on our method to capture long range spatial dependency which is proposed in \cite{wang2018non}. The rounded boxes indicate the convolution operator. } \label{fig:att} \end{figure} Although the above global attention scheme considers the image label information, the performance of the method can be further improved by considering the correlation between the features. To achieve this, besides the classification attention model, we also apply spatial attention model to consider the correlation between features in different locations within each channel. This attention model is exactly the same as proposed in non-local neural networks of \cite{wang2018non}, in which each feature is replaced by a weighted average of all features based on the similarities between their corresponding embeddings. The general structure of the spatial attention module as shown in Fig. \ref{fig:att} is to apply two $1\times1$ convolution layers to the input features, and reshape the result to obtain the similarity embeddings $\mathbf{B} \in \mathbb{R}^{N \times C}$ and $\mathbf{C} \in \mathbb{R}^{N \times C}$, where $N=H \times W$, and $C$ is the number of channels. The two matrices are used to compute a similarity matrix $\mathbf{S}=\mathbf{B}\mathbf{C}^T$. The row-wise softmax of the matrix $\mathbf{S}$ is multiplied to the matrix $\mathbf{D}$, which results from another $1 \times 1$ convolution to the input. The resulting is added to the input. Figure \ref{fig:att} shows the self-attention module in our method. Spatial and channel attentions have been used for segmentation of general images in \cite{fu2019dual}. However, our method uses completely different channel attention module based on the classification probabilities, while \cite{fu2019dual} uses a self-attention module. Following the common approach in multitask learning, we use a weighted sum of the classification and segmentation losses. Let $L_S$, and $L_C$, be the segmentation and classification losses, respectively. The training loss is computed by \begin{equation} L=\lambda L_S+ (1-\lambda) L_C \end{equation} where $\lambda \in [0, 1]$ is an appropriate regularization parameter. We use binary cross-entropy loss for both $L_C$, and $L_S$. \section{Experimental results} In this section, We evaluate our proposed method and compare it to other segmentation methods and multitask methods for joint segmentation and classification. In order to evaluate the performance for false positive segmentation, we compute the label inferred from the segmented image by $\mathbf{1}(\sum_{i,j} \mathbf{M}_{i,j})$ where $ \mathbf{M}_{i,j}$ indicates the output mask at pixel $i,j$, and $\mathbf{1}$ is the indicator function. It is considered zero if all pixels in the output mask are zero, and one otherwise. We use the accuracy between the segmented label and the image label in our comparisons which is called average consistency in Table \ref{tab:results}. We create a dataset by combining RGB images and their associated segmentation masks in the Corsican fire dataset \cite{toulouse2017computer}, and non-fire images in \cite{chino2015bowfire}, containing some images which are likely to cause false positive results. We divided the dataset into train, validation, and test groups with 60, 20 and 20 percent, respectively. \begin{figure*} \centering \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{grphical_model/none/sample_img_53} \end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{grphical_model/none/sample_mask_53} \end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{seg_class_model/pred_53}\end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{deep_lab_att_2_053}\end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{grphical_model/none/pred_53}\end{subfigure} \medskip \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth, height=\textwidth]{037} \end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth, height=\textwidth]{037_gt}\end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{unet_037} \end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{deeplab_v3_037}\end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{deeplab_v3_037_1}\end{subfigure} \medskip \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{grphical_model/none/sample_img_54} \caption{Original image \\ \hfill} \end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{grphical_model/none/sample_mask_54} \caption{ground-truth \\}\end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{seg_class_model/pred_54}\caption{U-net}\end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{deep_lab_att_2_054}\caption{Deeplab \\}\end{subfigure} \begin{subfigure}[b]{0.18\textwidth} \includegraphics[width=\textwidth]{grphical_model/none/aff_pred_54}\caption{Proposed }\end{subfigure} \caption{Examples of the segmentation of fire in images in our proposed method compared to other methods.} \label{fig:segmented} \end{figure*} \begin{figure*} \centering \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth, height=\textwidth]{not_fire002} {\\} \end{subfigure} \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth]{unet_not_fire002}{\\}\end{subfigure} \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth]{deeplab_not_fire002}{\\}\end{subfigure} \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth]{deep_lab_att_not_fire002} {\\} \end{subfigure} \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth, height=\textwidth]{not_fire008} {\\ Original image \hfill} \end{subfigure} \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth]{unet_not_fire008}{\\ U-net \cite{ronneberger2015u}}\end{subfigure} \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth]{deeplab_not_fire008}{\\ Deeplab \cite{harkat2021fire}}\end{subfigure} \begin{subfigure}[b]{0.2\textwidth} \includegraphics[width=\textwidth]{deep_lab_att_not_fire002} {\\ Proposed} \end{subfigure} \caption{Examples of segmentation of fire part for images that are likely to produce false positive results.} \label{fig:falsepositives} \end{figure*} \begin{table*}[] \centering \begin{tabular}{|l|l|l|l|l|l|} \hline & \multicolumn{1}{l|}{Classification metrics} & \multicolumn{2}{l|}{Segmentation Metrics} & Consistency \\ \hline & Accuracy & mean Accuracy & mean IOU & Avg. Consistency \\ \hline U-net \cite{ronneberger2015u} & - & 96.88 & 87.45 & .8521 \\ \hline Deeplab \cite{harkat2021fire} & .- & 97.18 & 88.34 & .8876 \\ \hline Fire segmentation in \cite{frizzi2021convolutional}& - & 97.06 & 88.02 & .8623 \\ \hline multi-task network in \cite{le2019multitask}& {98.75} & {96.55} & {87.22} & {.8912} \\ \hline Naive multi-task& {98.75} & {97.21} & {90.02} & {.9654} \\ \hline Proposed& {99.12} & \textbf{98.02} & \textbf{92.53} & \textbf{.9823} \\ \hline \end{tabular} \caption{Comparison of the proposed method with the baseline for classification-segmentation, and U-net for segmentation.} \label{tab:results} \end{table*} In this section, our proposed segmentation method is compared to U-net \cite{ronneberger2015u}, deeplab adapted for fire segmentation \cite{harkat2021fire}, and the method in \cite{frizzi2021convolutional} which proposed a new architecture for fire segmentation. We also compare our proposed method with other joint classification-segmentation methods. Inspired by \cite{le2019multitask}, we consider a multi-task approach, which applies a classification network to the output of the encoder of the segmentation network. This method corresponds to our proposed method in which all attention blocks are removed. We also consider a simple approach for removing false positives in segmentation in which the segmentation mask is set to zero if the classification output is zero (without using any attention). This basically relies on the classification output for segmentation. We call this method the naive approach. The proposed method is implemented in the following settings. The encoder of Deeplab-v3+ is used as the encoder backbone for the segmentation network. The network is then initialized by pre-trained ImageNet weights for the segmentation backbone, and i.i.d normal random weights with mean zero and standard deviation of $.05$ for the classification branch. The weights are learned during the training by the ADAM algorithm \cite{kingma2014adam} with initial learning rate of $5 \times 10^{-4}$, and a weight decay of $10^{-5}$. The loss regularization parameter $\lambda$ is set to $.6$, empirically, to achieve the best performance in terms of the overall validation loss. All other methods were trained in our dataset with ADAM algorithm with the parameters which performs the best in the validation set. For fire segmentation method in \cite{frizzi2021convolutional}, we trained our own implementation as the source codes are not available online. We report the result of our proposed method and other mentioned methods, on the test set, in Table \ref{tab:results}. The main metric for assessing the performance of semantic segmentation methods is intersection over union (IOU). This value is computed in this table for the classes of background and fire. In the classification metric, we compare the accuracy between the ground truth image labels and the predicted labels. This metric is obviously valid for multitask networks that have the image classification branch. In the segmentation metrics, the pixel accuracy (averaged over all tests images) and mean IOU are reported. As it can be seen, in the IOU segmentation metric, the proposed method outperforms segmentation methods of U-net, Deeplab adapted for fire segmentation in \cite{harkat2021fire}, and the fire segmentation method in \cite{frizzi2021convolutional}. IOU is also improved over the joint segmentation and classification method of \cite{le2019multitask}, and the naive approach described above. Some examples of fire segmentation on test dataset are shown in Fig. \ref{fig:segmented}. In the first row, it can be seen that our method could capture small portion of fire in the image. Besides that, based on the results on the table, the proposed method performs better in the consistency metric which is defined in the first paragraph of this section (the accuracy between the inferred label from the segmentation output and the ground truth label). This metric shows that the segmented image better corresponds to the image label in our method, i.e. reducing the cases in which some pixels are assigned as fire in non-fire images. This is a common problem in fire segmentation as illustrated in Fig. \ref{fig:falsepositives} for two images which are prone to false positive outputs. As it can be seen, other methods mistakenly select some parts of both images as fire, while the proposed method correctly does not segment any pixel as fire. \section{Conclusion} In this paper, we proposed a method for joint classification and segmentation of fire in images based on CNN using attention. We used a channel attention mechanism in which the weight is based on the output in the classification branch. A self-attention mechanism is used for spatial attention. Our method shows improved segmentation results over other fire segmentation methods, and other multitask CNN structures.
{'timestamp': '2021-11-08T02:03:35', 'yymm': '2111', 'arxiv_id': '2111.03129', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03129'}
arxiv
\section{Introduction} \label{sec:intro} Suppose we wish to build a hospital in some big city with millions of citizens. The challenge which we first face is to compute an optimal location $x^*$ in the city for the hospital, based on the 2-dimensional home address of the citizens, such that: \begin{enumerate*}[(i)] \item $x^*$ is simultaneously as close as possible to all the citizens of the city, \item $x^*$ is a valid construction site, in terms of restricted zones or occupied spaces, and \item it is close to main routs, and (possibly) many more constraints that may depend on the location of the citizens. \end{enumerate*} If we represent each citizen using a point $p \in \ensuremath{\mathbb{R}}^2$ that describes the citizen's house address on the 2D map of the city, then the problem above reduces to finding a vector $x^* \in \ensuremath{\mathbb{R}}^2$ that minimizes the sum of its squared Euclidean distance (SSD) $\norm{p_i-x^*}^2$ to each of the citizens in $P = \br{p_1,\cdots,p_n}$, under some constraints on $x^*$. Formally, we wish to solve \[ x^* \in \argmin_{x\in \mathbb{X}} \sum_{i=1}^n\norm{p_i-x}^2, \] where $|P|=n$ is the number of citizens, and $\mathbb{X}$ represents the feasible $x$ locations (which satisfy our constraints). The left hand side then denotes a query from the set of optimal solutions. In some cases, it is more important for some of the citizens to be closer to the hospital than others. For example, it is probably more important for citizens with health issues to be nearer to the hospital compared to healthy citizens. In this case, we might introduce a weights vector $w = (w_1,\cdots,w_{n})^T \in [0,\infty)^{n}$, where the $i$th entry $w_i$ denotes the importance of the $i$th citizen being close to the hospital. In this case, we wish to compute \begin{equation} \label{eq:1mean} x^* \in \argmin_{x\in \mathbb{X}} \sum_{i=1}^{n}w_i\norm{p_i-x}^2. \end{equation} If there are no constraints, i.e., $\mathbb{X}=\ensuremath{\mathbb{R}}^d$, the solution to~\eqref{eq:1mean} is simply the weighted mean $x^* = \sum_{i=1}^n w_ip_i$ of $P$. This is the reason the problem is called the ``mean'' problem. \paragraph{Generalizations.} If we wish to find the optimal location for a new highway (that is represented by a straight line) passing through the city, which is close as possible to all of the citizens, then this is the \emph{line mean} problem, where the goal is to compute a line (or in general, a $j$-dimensional affine subspace of $\ensuremath{\mathbb{R}}^d$) instead of a point, that minimizes the sum of squared Euclidean distances (SSD) to the citizens (points in $\ensuremath{\mathbb{R}}^d$); see e.g.~\cite{maalouf2019fast}. Those problems, where $j\geq1$, are natural generalizations of the mean problem in~\eqref{eq:1mean} where the dimension of the center is $j=0$, and are closely related to the singular value decomposition~\cite{klema1980singular}, principal component analysis (PCA)~\cite{wold1987principal}, linear regression, and many more problems in machine learning and computational geometry. To this end, this works, which is the second work in a series of surveys to come, solely handles the mean problem, which we believe is the foundation for all the complex optimization problems mentioned above. With the increase of input points (data size) and data acquisition models, the computational load for finding the best location for a facility under some constraints, or computing the SVD of the data matrix becomes computationally infeasible in real-time, especially when applied on small IoT devices and huge databases. Beside computing the optimal location, we might need to evaluate, in real-time, the cost of some given potential hospital location. To mitigate the above problems and handle simultaneously various data models, we suggest to utilize a relatively new paradigm called a \emph{coreset}, which has been gaining popularity in the past decade. This paradigm suggests to provably summarize the input data instead of improving the existing solvers, while allowing to evaluate any query (potential location), on the compressed data. \paragraph{A coreset }is a modern problem-dependent data summarization scheme that approximates the original (big) dataset $P$ in some provable sense with respect to a (usually infinite) set of questions / queries $\mathcal{X}$ defined by the problem at hand, and an objective loss/cost function $f_\mathrm{loss}$. If we indeed succeed to provably compress the data, in this sense, then we can then compute the query that minimizes the given objective cost function on the compressed coreset instead of the original data, thus saving time, energy and space without compromising the accuracy by more than a small multiplicative factor. Coresets are especially useful for learning big data since an off-line and possibly inefficient coreset construction for ``small data" implies constructions that maintains coreset for streaming, dynamic (including deletions) and distributed data in parallel. This is via a simple and easy to implement framework that is often called merge-reduce trees; see~\cite{bentley1980decomposable, indyk2014composable,agarwal2013mergeable}. The fact that a strong coreset approximates every query (and not just the optimal one for some criterion) implies that we may solve hard optimization problems with non-trivial and non-convex constraints by running a possibly inefficient algorithm such as exhaustive search on the coreset, or running existing heuristics numerous times on the small coreset instead of once on the original data. Similarly, parameter tuning, model selection, or cross validation can be applied on a coreset that is computed once for the original data as explained in~\cite{maalouf2019fast}. In recent years, coresets were applied to many machine learning algorithms e.g. logistic regression~\cite{huggins2016coresets,munteanu2018coresets,karnin2019discrepancy}, \emph{SVM}~\cite{har2007maximum,tsang2006generalized,tsang2005core,tsang2005very,tukan2020coresets}, clustering problems~\cite{feldman2011scalable,gu2012coreset,jubran2020sets,bachem2018one,lucic2015strong, schmidt2019fair,sohler2018strong}, matrix approximation~\cite{feldman2013turning, maalouf2019fast,feldman2010coresets,sarlos2006improved,maalouf2020faster}, $\ell_z$-regression~\cite{cohen2015lp, dasgupta2009sampling, sohler2011subspace}, and others~\cite{huang2021novel,cohen2021improving,huang2020coresets,mirzasoleiman2020coresets}; see surveys~\cite{feldman2020core,phillips2016coresets,jubran2019introduction}. There are many types of coresets and coreset constructions. In this survey we focus on what is sometimes called strong and weak coresets. Informally, a \emph{strong coreset} $C$ guarantees that for \emph{every} query $x\in \mathcal{X}$, the value of the cost function $f_\mathrm{loss}(C,x)$ when applied on the coreset $C$ is approximately the same as $f_\mathrm{loss}(P,x)$ when applied on the original full data; see e.g.~\cite{lucic2015strong,feng2019strong}. A \emph{weak coreset} $C$ (usually) only guarantees that the optimal query for $C$, $x_C^* \in \argmin_{x\in \mathcal{X}} f_\mathrm{loss}(C,x)$ and the optimal query for $P$, $x_P^* \in \argmin_{x\in \mathcal{X}} f_\mathrm{loss}(P,x)$ yield approximately the same cost on the full data, i.e., $f_\mathrm{loss}(P,x_P^*) \sim f_\mathrm{loss}(P,x_C^*)$; see e.g.~\cite{feldman2007ptas}. Since a strong coreset $C$ approximates every query $x\in \mathcal{X}$, we can also minimize $f_\mathrm{loss}$ on $C$ given further (previously unknown) constraints $\mathbb{X}$, since the query set under the assumptions $\mathbb{X} \cap \mathcal{X} \subseteq \mathcal{X}$ is also contained in $\mathcal{X}$. We would usually prefer to compute a coreset $C$ which is a (possibly weighted) \emph{subset} $C \subseteq P$ of the input $P$. Such a \emph{subset coreset} has multiple advantages over a non-subset coreset, which are \begin{enumerate*}[(i)] \item preserved sparsity of the input, \item interpretable, \item may be used (heuristically) for other problems, and \item less numerical issues that occur when non-exact linear combination of points are used. \end{enumerate*} Unfortunately, not all problems admit such a subset coreset. For further discussion and examples see e.g.~\cite{maalouf2020tight,feldman2020core}. \paragraph{Why coreset for the mean problem?} While the mean problem in~\eqref{eq:1mean} is a relatively simple problem, it lies at the basis of more involved and very common problems in machine learning, e.g., the classic $k$-means clustering. In particular, we can always improve a given $k$-clustering, by replacing the center of each cluster by its mean (if this is not already the case). This is indeed the idea behind the classic Lloyd's heuristic~\cite{lloyd1982least} and also behind some coresets for $k$-means~\cite{barger2020deterministic}. Most coreset construction algorithms for those hard problems usually borrow or generalize tricks and techniques used in coreset constructions for the (simpler) mean problem. Furthermore, other works, which seem unrelated at first glance, require at their foundations an algorithm for computing a mean coreset. Such problems include coresets for Kernel Density Estimates (KDE) of Euclidean kernels~\cite{phillips2020near}, least squares problems, e.g., coresets for linear regression and the singular value decomposition~\cite{maalouf2019fast}, and coresets for signals~\cite{rosman2014coresets}. For example in~\cite{maalouf2019fast} it was shown that in order to compute a lossless SVD (or linear regression) coreset for an $n\times d$ matrix $A$, it is sufficient to compute a smaller $m\times d$ matrix $C$ such that $A^TA=C^TC$. The scatter matrix $A^TA$ of an input matrix $A = (a_1 \mid \cdots \mid a_n)^T \in \ensuremath{\mathbb{R}}^{n\times d}$ is the sum $A^TA = \sum_{i=1}^n a_ia_i^T$ over $n$ $d\times d$ matrices. Each such matrix can be "flatten" to a vector in $\ensuremath{\mathbb{R}}^{d^2}$. Hence, we can compute a smaller subset of these $d^2$-dimensional vectors, which accurately estimate their original sum. We thus obtain a weighted subset of the rows of $A$ whose scatter matrix is the desired $A^TA$, with no additional error~\cite{jubran2019introduction}. A coreset that introduces multiplicative $1+\varepsilon$ error for this problem (SVD/linear regression) was suggested in~\cite{feldman2016dimensionality}, also here the authors suggested a reduction to the problem of computing a mean coreset with multiplicative $1+\varepsilon$ error for a set of point in a higher dimensional space. Another example is in the context of $k$-means, where~\cite{barger2020deterministic} showed that in order to compute a $k$-means coreset for a set of points $P$ it is suffices to cluster these points to a large number of clusters, and compute a mean coreset for each cluster, then take the union of these coresets to a single unite set, which is proven to be a $k$-means coreset for $P$. Not only are the mean-related results scattered across numerous papers and books dating from the last century and till today, but some of those constructions and proofs are not formally stated elsewhere, and can only be inferred by combining many different results. \paragraph{Main goal. }To this end, in this work we aim to review the wide range of techniques and methodologies behind the constructions of mean coresets, ranging from loss-less to lossy, from deterministic to randomized, and from greedy to non-greedy constructions. Examples include accurate coresets via computational geometry, random sampling-based coresets via Bernstein inequality, and greedy deterministic coresets via the Frank-Wolfe algorithm~\cite{clarkson2010coresets}. We provide in-depth proofs, under a unified notation, for all the suggested approaches, and guide the reader through them. We also analyze and compare all the presented results based on their construction time, size, and the properties discussed above; see Table~\ref{table:ourContrib}. Both to help readers outside the theoretical computer science community, and to encourage the usage and generalization of the presented algorithms, we provide full open source code for all the presented results~\cite{opencode}. \begin{table}[ht] \centering \begin{adjustbox}{width=\textwidth} \small \begin{tabular}{ | c | c | c | c | c | c | c | c |} \hline \textbf{\makecell{Coreset\\type}} & \textbf{\makecell{Input\\weights}} & \textbf{\makecell{Probability\\of failure}} & \textbf{\makecell{Multiplicative\\error}} & \textbf{Coreset size $|c|$} & \textbf{Properties} & \textbf{\makecell{Construction\\time}} & \textbf{\makecell{Formal\\statement}}\\ \hline Strong & \makecell{$w\in(0,\infty)^n$} & $\delta = 0$ & $\varepsilon = 0$ & $O(1)$ & \makecell{Not a subset,\\requires a different\\mathrm{cost_S} function} & $O(nd)$ & Section~\ref{sec:Accurate1mean}\\ \hline Strong & \makecell{$w\in(0,\infty)^n$} & $\delta = 0$ & $\varepsilon = 0$ & $d+2$ & \makecell{Subset\\$u\in\ensuremath{\mathbb{R}}^n$\\$\sum_{i=1}^n u_i = \sum_{i=1}^n w_i$} & $O(nd^2)$ & Section~\ref{sec:Accurate1mean}\\ \hline Strong & \makecell{$w\in(0,\infty)^n$} & $\delta = 0$ & $\varepsilon = 0$ & $d+3$ & \makecell{Subset\\$u\in[0,\sum_{p\in P}w(p)]^n$\\$\sum_{i=1}^n u_i = \sum_{i=1}^n w_i$} & $O(nd+d^4\log{n})$ & Section~\ref{sec:Accurate1mean}\\ \hline \hline Strong & $w \equiv \frac{1}{n}$ & $\delta \in (0,1)$ & $\varepsilon \in (0,1)$ & $O\left(\frac{d+\log(1/\delta)}{\varepsilon^2}\right)$ & \makecell{Subset\\$u\in\ensuremath{\mathbb{R}}^n$} & $O(nd)$ & Lemma~\ref{tightSens}\\ \hline Weak & $w \equiv \frac{1}{n}$ & $\delta \in (0,1)$ & $\varepsilon \in (0,1)$ & $O\left(\frac{d+\log(1/\delta)}{\varepsilon}\right)$ & \makecell{Subset\\$u\in\ensuremath{\mathbb{R}}^n$} & $O(nd)$ & Lemma~\ref{tightSensWeak}\\ \hline Strong & $w\in(0,\infty)^n$ & $\delta \in (0,1)$ & $\varepsilon \in (0,1)$ & $O\left(\frac{\log(d/\delta)}{\varepsilon^2}\right)$ & \makecell{Subset\\$u\in\ensuremath{\mathbb{R}}^n$} & $O(nd)$ & Theorem~\ref{strong-coreset-theorem-bern}\\ \hline Weak & $w\in(0,\infty)^n$ & $\delta \in (0,1)$ & $\varepsilon \in (0,1)$ & $O\left(\frac{\log(d/\delta)}{\varepsilon}\right)$ & \makecell{Subset\\$u\in\ensuremath{\mathbb{R}}^n$} & $O(nd)$ & Theorem~\ref{weak-coreset-theorem-bern}\\ \hline \hline Strong & $w\in(0,\infty)^n$ & $\delta =0$ & $\varepsilon \in (0,1)$ & $O\left(\frac{1}{\varepsilon^2}\right)$ & \makecell{Subset\\$u\in[0,(1+\varepsilon)\sum_{i=1}^n w_i]^n$\\ $\abs{\sum_{i=1}^n w_i -\sum_{i=1}^n u_i}\leq \varepsilon \sum_{i=1}^n w_i $} & $O\left(\frac{nd}{\varepsilon^2}\right)$ & Theorem~\ref{strong-coreset-theorem}\\ \hline Weak & $w\in(0,\infty)^n$ & $\delta =0$ & $\varepsilon \in (0,1)$ & $O\left(\frac{1}{\varepsilon}\right)$ & \makecell{Subset\\$u\in[0,(1+\sqrt{\varepsilon})\sum_{i=1}^n w_i]^n$\\ $\abs{\sum_{i=1}^n w_i -\sum_{i=1}^n u_i}\leq \sqrt{\varepsilon} \sum_{i=1}^n w_i $} & $O\left(\frac{nd}{\varepsilon}\right)$ & Theorem~\ref{weak-coreset-theorem}\\ \hline \hline Weak & $w \equiv \frac{1}{n}$ & $\delta \in (0,1)$ & $\varepsilon \in (0,1)$ & $O\left(\frac{1}{\varepsilon \delta}\right)$ & \makecell{Subset\\$u\in[0,1]^n$\\$\sum_{i=1}^n u_i = 1$} & $O(\frac{1}{\varepsilon \delta})$ & Lemma~\ref{weak_coreset_markov}\\ \hline Weak & $w \equiv \frac{1}{n}$ & $\delta \in (0,1)$ & $\varepsilon \in (0,1)$ & $O\left(\frac{1}{\varepsilon}\right)$ & \makecell{Subset\\$u\in[0,1]^n$\\$\sum_{i=1}^n u_i = 1$} & $O\left(d\cdot\left(\log^2(\frac{1}{\delta}) +\frac{\log(\frac{1}{\delta})}{\varepsilon}\right)\right)$ & Lemma~\ref{weak-probabilistic-coreset-theorem}\\ \hline \end{tabular} \end{adjustbox} \caption{\textbf{Summary of mean coresets.} This table presents various coresets for the mean problem, both $\varepsilon$-coresets from this work and accurate coresets from~\cite{jubran2019introduction}. The input for all algorithms is a set $P = \br{p_1,\cdots,p_n} \subseteq \ensuremath{\mathbb{R}}^d$ and a weights vector $w \in \ensuremath{\mathbb{R}}^n$. See Section~\ref{sec:intro} and Definitions~\ref{def:strongeCoreset} and~\ref{def:weakCoreset} for the different coreset types. $\delta$ represents the probability of failure of the corresponding algorithm, i.e., a deterministic algorithm has $\delta=0$. The measured error $\varepsilon$ is a multiplicative error, i.e., $\varepsilon = \displaystyle\argmax_{x\in \ensuremath{\mathbb{R}}^d}\frac{f_\mathrm{loss}((P,w),x) - f_\mathrm{loss}((P,u),x)}{f_\mathrm{loss}((P,w),x)}$. } \label{table:ourContrib} \end{table} \section{Paper Overview} This survey is part of a series of surveys that aim to give introduction to coresets; see~\cite{feldman2019core} and~\cite{jubran2019introduction}. This work is organized as follows. We first introduce the notations and definitions in Section~\ref{sec:notations}. In Section~\ref{sec:Accurate1mean}, we briefly summarize a first type of mean coresets constructions. Those coresets are often called \emph{accurate coresets}, as they do not introduce any error when compressing the data, unlike most of the other coresets when such an approximation error is unavoidable for obtaining a small ($o(n)$) coreset. In Section~\ref{sec:probred} we present a reduction between the problem of computing a (strong and weak) mean coreset for an arbitrary set of input point $Q \subset \ensuremath{\mathbb{R}}^d$ to the problem of computing a mean coreset to a corresponding, yet much simpler, set of points $P$ which we call a ``normalized weighted set''. This set satisfies a set of properties (e.g., zero mean) that will simplify the analysis later on; see Observation~\ref{to_0_mean} and Corollary~\ref{cor:reduction}. In Sections~\ref{sec:strong-coreset-red} and~\ref{sec:weak-coreset-red}, we continue and simplify the definition of coreset for a normalized weighted set $P$ by explaining what (sufficient) properties should hold for a set $C$ in order to be a strong/weak coreset for $P$. Through Section~\ref{sec:strondelta}, we show how to compute, with a high probability, a (strong and weak) coreset for such a normalized set $P$ based on two different approaches: \begin{enumerate*}[(i)] \item in Subsection~\ref{sec:sensitivityCoresets} we present a random coreset construction which utilizes the well known sensitivity sampling framework~\cite{DBLP:journals/corr/BravermanFL16,feldman2011unified}, \item then in Section~\ref{sec:bernstein} we show how to utilize the Bernstein inequality to obtain smaller coresets in the same running time. \end{enumerate*} The two approaches above are very similar, and basically differ in their analysis. We then present, in Section~\ref{sec:detcore}, a deterministic coreset construction algorithm (zero probability of failure) for an input normalized weighted set; see Theorem~\ref{weak-coreset-theorem} and Theorem~\ref{strong-coreset-theorem}. The main technique in this section is to normalize the data in a way that enables the use of the classic Frank-Wolfe algorithm~\cite{frank1956algorithm} from 1956 (that was re-discovered only recently by~\cite{clarkson2010coresets}). Finally, in Section~\ref{sec:weaksublinear}, we present two algorithms for computing, with high probability, a weak coreset in time that is sublinear in the input size. Table~\ref{table:ourContrib} summarizes all the results that are written in this paper. \section{Notations and assumptions}\label{sec:notations} In this section we first we first introduce our notations that will be used through the paper, and then give our main definitions. \begin{paragraph}{Notations.} For a pair of integers $d,n\geq 1$, we denote by $\ensuremath{\mathbb{R}}^{n\times d}$ the union over every $n\times d$ real matrix and $[n] = \br{1,\cdots, n}$. The $\ell_2$, $\ell_1$ and $\ell_0$ norm of a vector $v=(v_1,\cdots,v_d)\in\ensuremath{\mathbb{R}}^d$ are denoted, respectively, by $\norm{v}=\sqrt{\sum_{i=1}^{d} v_i^2}$, $\norm{v}_1 =\sum_{i=1}^{d} \abs{v_i}$, and $\norm{v}_0$, where and $\norm{v}_0$ is the number of non-zero entries in $v$. For a matrix $A\in\ensuremath{\mathbb{R}}^{n\times d}$ the \emph{Frobenius norm} $\norm{A}_F$ is the squared root of its sum of squared entries, and $tr(A)$ denotes its trace. A vector $w\in [0,1]^n$ is called a \emph{distribution vector} if its entries sum up to one. For an event $B$ we use $\Pr(B)$ as the probability that event $B$ occurs. A \textit{weighted set} is a pair $P'=(P,w)$ where $P=\br{p_1,\cdots,p_n} \subseteq \ensuremath{\mathbb{R}}^d$ is a set of $n$ \emph{points}, and $w=(w_1,\cdots,w_n)^T \in (0,\infty)^n$ is called a \emph{weights vector} that assigns every $p_i\in P$ a weight $w_i \in \ensuremath{\mathbb{R}}$. The size of $P'$ is $|P| = n$ and the cardinality of $P'$ is the number of non zero entries $\norm{w}_0$ of $w$. Finally the \emph{weighted sum} of a weighted set $(P,w)$ is defined as $\sum_{i=1}^n w_ip_i$, and its weighted mean is $\sum_{i=1}^n \frac{w_i}{\norm{w}_1}p_i$. \end{paragraph} \begin{definition} [Normalized weighted set]\label{defNormalize} A \emph{normalized weighted set} is a weighted set $(P,w)=(\br{p_1,\cdots,p_n},(w_1,\cdots,w_n)^T)$ that satisfies the following three properties \begin{enumerate}[(a)] \item Weights sum to one: $\sum_{i=1}^n w_i = 1$, \label{a} \item The weighted sum is the origin: $\sum_{i=1}^n w_ip_i=\mathbf{0}_d$, and\label{b} \item The weighted sum of squared norms is $1$: $\sum_{i=1}^n w_i\norm{p_i}^2=1$. \label{c} \end{enumerate} \end{definition} In what follows is the definition of a strong $\varepsilon$-coreset for the mean problem. A coreset for a weighted set $(P,w)$ is nothing but a re-weighting of the points in $P$ by a new weights vector $u$, such that \emph{every} query $x\in \ensuremath{\mathbb{R}}^d$ will yield approximately the same cost when applied to either $(P,w)$ or $(P,u)$. We usually aim to compute a weighted set $(P,u)$ of cardinality $\norm{u}_0 \ll \norm{w}_0$. \begin{definition} [Strong mean $(\varepsilon,\delta)$-coreset] \label{def:strongeCoreset} Let $(P,u)$ and $(P,w)$ be two weighted sets in $\ensuremath{\mathbb{R}}^d$ such that $|P| = n$, and let $\varepsilon, \delta \in [0,1)$. We say that $(P,u)$ is a \emph{strong mean $(\varepsilon,\delta)$-coreset} for $(P,w)$ of cardinality $\norm{u}_0$ if, with probability at least $1-\delta$, for every $x\in \ensuremath{\mathbb{R}}^d$, \[ \left|\sum_{i=1}^n w_i\norm{p_i-x}^2 - \sum_{i=1}^n u_i\norm{p_i-x}^2 \right| \leq \varepsilon \sum_{i=1}^n w_i\norm{p_i-x}^2. \] If $\varepsilon = 0$, we say that $(P,u)$ is a strong mean \emph{accurate coreset} for $(P,w)$, and if $\delta = 0$ we say that the coreset is deterministic and simply call it a strong $\varepsilon$-coreset. \end{definition} A weak mean $\varepsilon$-coreset for $(P,w)$ is a weighted set $(P,u)$ such that solving for the optimal query $x\in\ensuremath{\mathbb{R}}^d$ on the coreset $(P,u)$ and applying it on $(P,w)$ yields approximately the same result as if computing the optimal solution of the original set $(P,w)$. \begin{definition} [Weak mean $(\varepsilon,\delta)$-coreset] \label{def:weakCoreset} Let $(P,u)$ and $(P,w)$ be a pair of weighted sets, and let $n=|P|$. Let $\bar{p} \in \argmin_{x\in \ensuremath{\mathbb{R}}^d}\sum_{i=1}^{n}w_i\norm{p_i-x}^2$, $\bar{s} \in \argmin_{x\in \ensuremath{\mathbb{R}}^d} \sum_{i=1}^{n}u_i\norm{p_i-x}^2,$ and put $\varepsilon, \delta \in [0,1)$. Then $(P,u)$ is a \emph{weak mean $(\varepsilon,\delta)$-coreset} (or weak $(\varepsilon,\delta)$-coreset in short) for $(P,w)$ of cardinality $\norm{u}_0$ if with probability at least $1-\delta$, we have: \[ \left| \sum_{i=1}^n w_i\norm{p_i-\bar{p}}^2 - \sum_{i=1}^n w_i\norm{p_i-\bar{s}}^2\right| \leq \varepsilon \cdot \sum_{i=1}^n w_i\norm{p_i-\bar{p}}^2. \] If $\varepsilon = 0$, we say that $(P,u)$ is a weak mean \emph{accurate coreset} for $(P,w)$, and if $\delta = 0$ we say that the coreset is deterministic and simply call it a weak $\varepsilon$-coreset. \end{definition} \section{Accurate mean coresets} \label{sec:Accurate1mean} Before going into the more involved coresets for the mean problem, in this section we will briefly summarize the most simple coresets which are the accurate coresets; see Definition~\ref{def:strongeCoreset}. Those coresets do not introduce any error when compressing the data, i.e., $\varepsilon = 0$. The coresets presented in this section are explained in detail in~\cite{jubran2019introduction}. Let $(P,w)$ be a weighted set (input set) of size $|P| = n$ and $x\in \ensuremath{\mathbb{R}}^d$ be a vector (query). \paragraph{Simple statistics. }We first make the following simple observation: \begin{equation} \label{eqStatistics} \sum_{i=1}^n w_i\norm{p_i-x}^2=\sum_{i=1}^n w_i\norm{p_i}^2 -2x^T\sum_{i=1}^n w_ip_i + \norm{x}^2\sum_{i=1}^n w_i. \end{equation} By this observation, we notice that $\sum_{i=1}^n w_i\norm{p_i-x}^2$ is equal to the sum of the following $3$ terms: (i) $\sum_{i=1}^n w_i\norm{p_i}^2$, (ii) $-2x^T\sum_{i=1}^n w_ip_i$, and (iii) $\norm{x}^2\sum_{i=1}^n w_i$. Notice that the first term is independent of the query $x$, the second depends on $\norm{x}^2$ and $\sum_{i=1}^n w_i$, the third term depends on $x^T$ and $\sum_{i=1}^n w_ip_i$. Therefore, by pre-computing in $O(n)$ time and storing in memory the following statistics: $\sum_{i=1}^n w_i\norm{p_i}^2$, $\sum_{i=1}^n w_ip_i$, and $\sum_{i=1}^n w_i$, for any (new) given query $x$ we can evaluate $\sum_{i=1}^n w_i\norm{p_i-x}^2$ in $O(1)$ time by simply evaluating the $3$ terms from~\eqref{eqStatistics} using $x$ and the stored statistics. We note that this ``coreset'' is different than other coresets presented in this paper, since it is not a subseteq of the input and requires evaluating a different cost function on the coreset than on the original data. \paragraph{Subset coreset. } We now aim to compute a mean coreset $(P,u)$ of cardinality $\norm{u}_0 << n$. From~\eqref{eqStatistics}, we know that if a weighted set $(P,u)$ satisfies: (i) $\sum_{i=1}^n w_i\norm{p_i}^2 = \sum_{i=1}^n u_i\norm{p_i}^2$, (ii) $\sum_{i=1}^n w_ip_i = \sum_{i=1}^n u_ip_i$, and (iii) $\sum_{i=1}^n w_i = \sum_{i=1}^n u_i$, then clearly $ \sum_{i=1}^n u_i \norm{p_i-x}_2^2 = \sum_{i=1}^n w_i \norm{p_i-x}_2^2$ for every $x\in \ensuremath{\mathbb{R}}^d$. Therefore, to compute an accurate strong mean coreset $(P,u)$ for $(P,w)$, we simply need to ensure that (i)--(iii) holds. It turns out that we can compute in $O(nd^2)$ time a coreset $(P,u)$ of cardinality $\norm{u}_0 \leq d+2$ where $u \in \ensuremath{\mathbb{R}}^{n}$ that satisfies the conditions above. Furthermore, if the input weights $w$ are non-negative, i.e., $w\in [0,\infty)^n$, we can compute in $O(nd + d^4\log{n})$ a coreset $(P,u)$ of cardinality $\norm{u}_0 \leq d+3$ where $u \in [0,\sum_{p\in P}w(p)]^{d+3}$ is both non-negative and bounded; see full details in~\cite{jubran2019introduction}. \section{Problem Reduction for $\varepsilon$-Coresets}\label{sec:probred} In this section, we argue that in order to compute a strong (weak) $\varepsilon$-coreset for an input weighted set $(Q,m)$, it suffices to compute a strong (weak) $\varepsilon$-coreset for its corresponding normalized (and much simpler) weighted set $(P,w)$ as in Definition~\ref{defNormalize}; see Corollary~\ref{cor:reduction}. Note that we do not actually normalize the given input data. The normalization is used only in the analysis and coresets proof of correctness. \subsection{Reduction To Normalized Weighted Set} \observation \label{to_0_mean} Let $Q=\{q_1,\cdots,q_n\}$ be a set of $n\geq2$ points in $\ensuremath{\mathbb{R}}^d$, $m\in(0,\infty)^n$, $w \in(0,1]^n$ be a distribution vector such that $w=\frac{m}{\norm{m}_1}$, ${\mu=\sum_{i=1}^n{w_i q_i}}$ and $\sigma=\sqrt{\sum_{i=1}^n w_i\norm{q_i - \mu}^2 }$. Let $P=\br{p_1,\cdots,p_n}$ be a set of $n$ points in $\ensuremath{\mathbb{R}}^d$, such that for every $j\in [n]$ we have $p_j=\frac{q_j - \mu}{\sigma}$. Then, $(P,w)$ is the corresponding normalized weighted set of $(Q,m)$, i.e., (i)-(iii) hold as follows:\label{obs1} \begin{enumerate}[(i)] \item $\sum_{i=1}^n w_i = 1$, \label{sumw_it} \item $\sum_{i=1}^n w_ip_i=\mathbf{0}$, and \label{first_it} \item $\sum_{i=1}^n w_i\norm{p_i}^2=1$. \label{sec_it} \end{enumerate} \begin{proof} \begin{align*} &{\textit{~\ref{sumw_it} }} \sum_{i=1}^n w_i = 1\text{ immediately holds by the definition of $w$.}\\ &{\textit{~\ref{first_it} }} \sum_{i=1}^n w_ip_i = \sum_{i=1}^n w_i \cdot \frac{q_i - \mu} {\sigma} = \frac{1}{\sigma} \left( \sum_{i=1}^n w_iq_i - \sum_{i=1}^nw_i\mu \right) = \frac{1}{\sigma} \left( \mu - \sum_{i=1}^nw_i \mu \right) = \frac{1}{\sigma} \mu \left(1 - \sum_{i=1}^nw_i \right) = 0, \intertext{where the first equality holds by the definition of $p_i$, the third holds by the definition of $\mu$, and the last is since $w$ is a distribution vector.} &{\textit{~\ref{sec_it} }} \sum_{i=1}^n w_i\norm{p_i}^2 = \sum_{i=1}^n w_i\norm{ \frac{q_i - \mu}{\sigma} }^2=\frac{1}{\sigma^2}\sum_{i=1}^n w_i\norm{{q_i - \mu}}^2 =\frac{\sum_{i=1}^n w_i\norm{{q_i - \mu}}^2}{\sum_{i=1}^n w_i\norm{q_i - \mu}^2} =1, \end{align*} where the first and third equality hold by the definition of $p_i$ and $\sigma$, respectively. \end{proof} \begin{corollary} \label{cor:reduction} Let $(Q,m)$ be a weighted set, and let $(P,w)$ be its corresponding normalized weighted set as computed in Observation~\ref{to_0_mean}. Let $(P,u)$ be a strong (weak) $\varepsilon$-coreset for $(P,w)$ and let $u' = \norm{m}_1 \cdot u$. Then $(Q,u')$ is a strong (weak) $\varepsilon$-coreset for $(Q,m)$. \end{corollary} \begin{proof} Put $x \in \ensuremath{\mathbb{R}}^d$ and let $y=\frac{x - \mu}{\sigma}$. Now, for every $j\in [n]$, we have that \begin{align}\label{keyobs} \norm{q_j - x}^2 =\norm{ \sigma p_j + \mu- (\sigma y + \mu) }^2 = \norm{ \sigma p_j - \sigma y }^2 = \sigma^2 ||p_j-y||^2, \end{align} {where the first equality is by the definition of $y$ and $p_j$.} We prove Corollary~\ref{cor:reduction} first for the case of a strong $\varepsilon$-coreset, and then for the case of a weak $\varepsilon$-coreset. \noindent\textbf{Proof for a strong $\varepsilon$-coreset.} Let $(P,u)$ be a strong $\varepsilon$-coreset for $(P,w)$. We prove that $(Q,u')$ is a strong $\varepsilon$-coreset for $(Q,m)$. Observe that \begin{align} \label{firstoneneeded} \abs{\sum_{i=1}^n (m_i-u'_i)\norm{q_i-x}^2 } = \abs{\sum_{i=1}^n (m_i-u'_i) \sigma^2 \norm{p_i-y}^2 } = \abs{\sum_{i=1}^n \norm{m}_1 \sigma^2 (w_i-u_i) \norm{p_i-y}^2 }, \end{align} where the first equality holds by~\eqref{keyobs}, and the second holds by the definition of $w$ and $u'$. Since $(P,u)$ is a strong $\varepsilon$-coreset for $(P,w)$ \begin{align} \label{secondoneneeded} \abs{\sum_{i=1}^n \norm{m}_1 \sigma^2 (w_i-u_i) \norm{p_i-y}^2} \leq\varepsilon {\sum_{i=1}^n \norm{m}_1 \sigma^2 w_i \norm{p_i-y}^2} = \varepsilon {\sum_{i=1}^n m_i \norm{q_i-x}^2 }, \end{align} where the equality holds by~\eqref{keyobs} and since $ w=\frac{m}{\norm{m}_1} $. The proof for the case of a strong $\varepsilon$-coreset concludes by combining~\eqref{firstoneneeded} and~\eqref{secondoneneeded} as $$\abs{\sum_{i=1}^n (m_i-u'_i)\norm{q_i-x}^2 }\leq \varepsilon \sum_{i=1}^n m_i \norm{q_i-x}^2.$$ \newcommand{\tilde{\mu}}{\tilde{\mu}} \noindent\textbf{Proof for a weak $\varepsilon$-coreset.} Let $(P,u)$ be a weak $\varepsilon$-coreset for $(P,w)$. We prove that $(Q,u')$ is a weak $\varepsilon$-coreset for $(Q,m)$. First, we observe the following equalities \begin{equation}\label{reductiontop} \begin{split} &\sum_{i=1}^n m_i \norm{q_i-\frac{\sum_{i=1}^n u_i q_i}{\norm{u}_1} }^2 =\sigma^2 \sum_{i=1}^n m_i \norm{p_i-\frac{\frac{\sum_{i=1}^n u_i q_i}{\norm{u}_1} - \mu }{\sigma}}^2 \\&= \sigma^2 \sum_{i=1}^n m_i\norm{p_i-\frac{\frac{\sum_{i=1}^n u_i (\sigma p_i + \mu )}{\norm{u}_1} - \mu }{\sigma}}^2 =\sigma^2 \sum_{i=1}^n m_i \norm{p_i-\frac{\sum_{i=1}^n u_i \sigma p_i }{\norm{u}_1\sigma}+ \frac{\sum_{i=1}^n u_i \mu}{\norm{u}_1 \sigma} -\frac{\mu }{\sigma}}^2 \\&=\sigma^2 \sum_{i=1}^n m_i \norm{p_i-\frac{\sum_{i=1}^n u_i p_i }{\norm{u}_1}+ \frac{ \mu}{ \sigma} -\frac{\mu }{\sigma}}^2 =\sigma^2 \norm{m}_1 \sum_{i=1}^n w_i \norm{p_i-\frac{\sum_{i=1}^n u_i p_i }{\norm{u}_1}}^2, \end{split} \end{equation} where the first equality holds by~\eqref{keyobs}, the second holds by the definition of $p_i$ for every $i\in [n]$, the third and fourth are just a rearrangements, and the last holds by the definition of $w$. Since $(P,u)$ is a weak $\varepsilon$-coreset for $(P,w)$, we get that \begin{equation}\label{backtoq} \begin{split} \sigma^2 \norm{m}_1 \sum_{i=1}^n w_i \norm{p_i-\frac{\sum_{i=1}^n u_i p_i }{\norm{u}_1}}^2 &\leq \sigma^2 \norm{m}_1 (1+\varepsilon)\sum_{i=1}^n w_i \norm{p_i- \vec{0}}^2 \\&= \sigma^2 (1+\varepsilon)\sum_{i=1}^n m_i \norm{p_i- \vec{0}}^2 = (1+\varepsilon)\sum_{i=1}^n m_i \norm{q_i- \mu}^2, \end{split} \end{equation} where the inequality holds since the mean of $(P,w)$ is $\vec{0}$, the first equality holds since $w=\frac{m}{\norm{m}_1} $, and the second holds by~\eqref{keyobs}. Hence, combining~\eqref{reductiontop} with~\eqref{backtoq} proves the lemma. \end{proof} \subsection{Strong Coreset for a Normalized Weighted Set}\label{sec:strong-coreset-red} Given a normalized weighted set $(P,w)$ as in Definition~\ref{defNormalize}, in the following lemma we prove that a weighted set $(P,u)$ is a strong $(\varepsilon,\delta)$-coreset for $(P,w)$ if some three properties related to the mean, variance, and weights of $(P,u)$ hold with probability at least $1-\delta$. \begin{lemma}\label{strong_coreset_lema} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\varepsilon,\delta \in (0,1)$, and $u\in \ensuremath{\mathbb{R}}^n$ such that with probability at least $1-\delta$, \begin{enumerate} \item $\norm {\sum_{i=1}^n u_i p_i} \leq \varepsilon $,\label{1} \item $\abs{1- \sum_{i=1}^n u_i } \leq \varepsilon$, and \label{2} \item $\abs{ 1- \sum_{i=1}^n u_i \cdot \norm {p_i}^2} \leq \varepsilon$. \label{3} \end{enumerate} Then, $(P,u)$ is a strong $(2\varepsilon,\delta)$-coreset for $(P,w)$, i.e., with probability at least $1-\delta$, for every $x\in\ensuremath{\mathbb{R}}^d$ we have that \begin{align} \bigg| \sum_{i=1}^n (w_i - u_i ) \norm{p_i-x}^2 \bigg| \leq 2\varepsilon \sum_{i=1}^n w_i\norm{p_i-x}^2. \label{res} \end{align} \end{lemma} \begin{proof} First we have that, \begin{align} \sum_{i=1}^n w_i \norm{p_i-x}^2 =\sum_{i=1}^n w_i\norm{p_i}^2 -2x^T\sum_{i=1}^n w_i p_i + \norm{x}^2\sum_{i=1}^n w_i = 1+\norm{x}^2, \label{1+x2} \end{align} where the last equality holds by the attributes~\eqref{a}--\eqref{c} of the normalized weighted set $(P,w)$. By rearranging the left hand side of~\eqref{res} we get, \begin{align} &\left|\sum_{i=1}^n (w_i-u_i)\norm{p_i - x}^2 \right| = \left |\sum_{i=1}^n (w_i-u_i) (\norm{p_i}^2 - 2p_i^Tx + \norm{x}^2 )\right| \\ &\leq \left| \sum_{i=1}^n (w_i-u_i)\norm{p_i}^2 \right| + \left| \norm{x}^2 \sum_{i=1}^n (w_i-u_i) \right| + \left| 2x^T\sum_{i=1}^n (w_i-u_i)p_i \right| \label{triangle inequality}\\ &=\left| 1- \sum_{i=1}^n u_i\norm{p_i}^2 \right| +\norm{x}^2 \left| 1- \sum_{i=1}^n u_i \right| + \left| 2x^T\sum_{i=1}^n u_ip_i \right| \label{w_i is distribution and rerranging} \\ &\leq \varepsilon +\varepsilon\norm{x}^2 + 2\norm{x} \norm{ \sum_{i=1}^n u_ip_i } \label{almost done}, \end{align} where~\eqref{triangle inequality} holds by the triangle inequality,~\eqref{w_i is distribution and rerranging} holds by attributes~\eqref{a}--\eqref{c}, and~\eqref{almost done} holds by combining assumptions~\eqref{2},~\eqref{3}, and the Cauchy-Schwarz inequality respectively. We also have for every $a,b\geq 0$ that $2ab \leq a^2 + b^2$, hence, \begin{align} 2ab = 2\sqrt{\varepsilon}a\frac{b}{\sqrt{\varepsilon}} \leq \varepsilon a^2 + \frac{b^2}{\varepsilon}. \label{2ab bound} \end{align} By~\eqref{2ab bound} and assumption~\eqref{1} we get that, \begin{align} 2\norm{x} \norm{ \sum_{i=1}^n u_ip_i } \leq \varepsilon \norm{x}^2 + \frac{\norm{ \sum_{i=1}^n u_ip_i }^2}{\varepsilon} \leq \varepsilon \norm{x}^2 + \frac{\varepsilon^2}{\varepsilon} =\varepsilon \norm{x}^2 + \varepsilon. \label{eps(x +4)} \end{align} Lemma~\ref{strong_coreset_lema} now holds by plugging~\eqref{eps(x +4)} in~\eqref{almost done} as, \begin{align} \bigg|\sum_{i=1}^n (w_i-u_i)\norm{p_i - x}^2 \bigg| &\leq \varepsilon +\varepsilon\norm{x}^2 + \varepsilon \norm{x}^2 + \varepsilon = 2\varepsilon +2\varepsilon \norm{x}^2\\ & = 2\varepsilon(1+ \norm{x}^2) = 2\varepsilon \sum_{i=1}^n {w_i \norm{p_i-x}^2} \label{eqFinal}, \end{align} where the last equality holds by~\eqref{1+x2}. Observe that if assumptions~\eqref{1},~\eqref{2} and~\eqref{3} hold with probability at least $1-\delta$, then~\eqref{eqFinal} hold also with probability $1-\delta$. We therefore obtain an $(2\varepsilon,\delta)$-coreset. \end{proof} \subsection{Weak Coreset for a Normalized Weighted Set}\label{sec:weak-coreset-red} Given a normalized weighted set $(P,w)$ as in Definition~\ref{defNormalize}, in the following lemma we prove that a weighted set $(P,u)$ is a weak $(\varepsilon,\delta)$-coreset for $(P,w)$ if and only if with probability at least $1-\delta$ the squared $\ell_2$-norm of the weighted mean of $(P,u)$ is smaller that $\varepsilon$. \begin{lemma}\label{weak_coreset_lema} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\varepsilon\in (0,1)$, and $u\in \ensuremath{\mathbb{R}}^n$ be a weight vector. Let $\displaystyle{\overline{p} =\sum_{i=1}^n w_i p_i}$ and $\displaystyle{\overline{s} = \sum_{i=1}^n \frac{u_i}{\norm{u}_1}p_i}$. Then, $(P,u)$ is a weak $\varepsilon$-coreset for $(P,w)$, i.e., \[ \sum_{i=1}^n w_i \norm{p_i-\overline{s}}^2 \leq (1+ \varepsilon)\sum_{i=1}^n w_i \norm{p_i-\overline{p}}^2 \] if and only if \[ \norm{\overline{s}}^2 \leq\varepsilon. \]\label{first} \end{lemma} \begin{proof} Observe that $\overline{p}$ is the weighted mean of the points in $P$, since it minimizes the sum of the squared distances from the points in $P$ to it, thus, \begin{align}\label{mup} &\sum_{i=1}^n w_i\norm{p_i - \overline{p}}^2 =\sum_{i=1}^n w_i \norm{p_i - \sum_{j =1}^n w_j p_j }^2 = \sum_{i=1}^n w_i \norm{p_i-0}^2 = 1, \end{align} where the second equality holds by Assumption~\ref{b} of a normalized weighted set and the last holds by Assumption~\ref{c} of a normalized weighted set. We also have that, \begin{align}\label{mus} &\sum_{i=1}^n w_i \norm{p_i-\overline{s}}^2 = \sum_{i=1}^n w_i \norm{p_i}^2 -2\overline{s}^T\sum_{i=1}^n w_i p_i +\norm{\overline{s}}^2\sum_{i=1}^n w_i = 1+ \norm{\overline{s}}^2, \end{align} where the last equality holds by Assumptions~\ref{a}--\ref{c} of a normalized weighted set. Using~\eqref{mup} and~\eqref{mus} we finish the proof by looking at the following two cases: if $\norm{\overline{s}}^2 >\varepsilon$ then $$\sum_{i=1}^n w_i \norm{p_i-\overline{s}}^2 =1+ \norm{\overline{s}}^2 > 1+\varepsilon > (1+\varepsilon) \sum_{i=1}^n w_i\norm{p_i - \overline{p}}^2,$$ if $\norm{\overline{s}}^2 \leq\varepsilon$ then $$\sum_{i=1}^n w_i \norm{p_i-\overline{s}}^2 =1+ \norm{\overline{s}}^2 \leq 1+\varepsilon \leq (1+\varepsilon) \sum_{i=1}^n w_i\norm{p_i - \overline{p}}^2.$$ \end{proof} \subsection{From Strong to Weak Coreset Constructions} \label{sec:strongToWeak} The following lemma proves that any strong $\sqrt{\varepsilon}$-coreset for the mean problem is also a week $\varepsilon$-coreset for the mean problem. \begin{lemma}\label{strongToWeek} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\varepsilon\in (0,\frac{1}{36})$ and let $(P,u)$ be a strong $\sqrt{\varepsilon}$-coreset for $(P,w)$. Then $(P,u)$ is also a weak $(36\varepsilon)$-coreset for $(P,w)$, i.e., \begin{equation} \label{eqtoProve} \sum_{i=1}^n w_i \norm{p_i-\bar{s}}^2 \leq (1+36\varepsilon)\min_{x\in\ensuremath{\mathbb{R}}^d} \sum_{i=1}^n w_i\norm{p_i-x}^2, \end{equation} where $\bar{s} = \sum_{i=1}^n \frac{u_i}{\norm{u}_1}p_i$ is the weighted mean of $(P,u)$. \end{lemma} \begin{proof} First, observe that if $\norm{\bar{s}} = 0$, then by Lemma~\ref{weak_coreset_lema}, \eqref{eqtoProve} holds immediately. We therefore assume that $\norm{\bar{s}} \neq 0$. Since $(P,u)$ is a strong $\sqrt{\varepsilon}$-coreset for $(P,w)$, for every $x\in \ensuremath{\mathbb{R}}^d$ we have that \begin{equation} \label{eq:prop1} \left|\sum_{i=1}^n w_i\cdot \norm{p_i-x}^2 - \sum_{i=1}^n u_i\cdot \norm{p_i-x}^2\right| \leq \sqrt{\varepsilon} \sum_{i=1}^n w_i\cdot \norm{p_i-x}^2, \end{equation} and \begin{equation}\label{eq:forEveryx} \sum_{i=1}^n w_i\cdot \norm{p_i-x}^2 = \sum_{i=1}^n w_i\norm{p_i}^2 -2x^T\sum_{i=1}^n w_ip_i +\sum_{i=1}^n w_i \norm{x}^2 = 1+\norm{x}^2, \end{equation} where the last equality holds by the properties of $(P,w)$ in Definition~\ref{defNormalize}. Therefore, for every $x\in \ensuremath{\mathbb{R}}^d$ we have that \begin{equation}\label{eq:forEveryx2} \begin{split} & \left|\sum_{i=1}^n w_i\cdot \norm{p_i-x}^2 - \sum_{i=1}^n u_i\cdot \norm{p_i-x}^2\right| = \left|1+\norm{x}^2 - \sum_{i=1}^n u_i\cdot \norm{p_i-x}^2\right|\\ & = \left|1+\norm{x}^2 - \sum_{i=1}^n u_i \norm{p_i}^2 +2x^T \sum_{i=1}^n u_i p_i -\sum_{i=1}^n u_i\norm{x}^2\right|, \end{split} \end{equation} where the first equality is by~\eqref{eq:forEveryx}. Combining~\eqref{eq:prop1},~\eqref{eq:forEveryx} and~\eqref{eq:forEveryx2} yields that for every $x\in \ensuremath{\mathbb{R}}^d$ the following holds \begin{equation}\label{eq:forEveryx3} \left|1+\norm{x}^2 - \sum_{i=1}^n u_i \norm{p_i}^2 +2x^T \sum_{i=1}^n u_i p_i -\sum_{i=1}^n u_i\norm{x}^2\right| \leq \sqrt{\varepsilon}(1+\norm{x}^2). \end{equation} We now prove that $\norm{\sum_{i=1}^n u_ip_i} \leq 6\sqrt{\varepsilon}$ using the following case analysis: \textbf{Case (i): }$d=1$, and \textbf{Case (ii): }$d \geq 2$. \textbf{Case (i): } $d=1$. Plugging $x = 0$ in~\eqref{eq:forEveryx3} yields \begin{equation}\label{eqx0} \left|1 - \sum_{i=1}^n u_i p_i^2 \right| \leq \sqrt{\varepsilon}. \end{equation} Plugging $x=1$ in~\eqref{eq:forEveryx3} and combining with~\eqref{eqx0} yields \begin{equation} \label{eqx1} \abs{1+2\sum_{i=1}^n u_i p_i-\sum_{i=1}^n u_i} \leq 3\sqrt{\varepsilon}. \end{equation} Plugging $x=-1$ in~\eqref{eq:forEveryx3} and combining with~\eqref{eqx0} yields \begin{equation} \label{eqx-1} \abs{1-2\sum_{i=1}^n u_i p_i-\sum_{i=1}^n u_i} \leq 3\sqrt{\varepsilon}. \end{equation} Combining~\eqref{eqx1} and~\eqref{eqx-1} implies that \begin{enumerate} \item $\abs{\sum_{i=1}^n u_ip_i} \leq 3\sqrt{\varepsilon},$ \label{need1} \item and $\abs{1-1\sum_{i=1}^n u_i} \leq 3\sqrt{\varepsilon}.$\label{need11} \end{enumerate} Hence, Combining~\eqref{need1} and~\eqref{need11} proves Case (i) as \[ \sum_{i=1}^n \frac{u_i}{\norm{u}_1}p_i=\abs{\frac{\sum_{i=1}^n u_ip_i}{\sum_{i=1}^n u_i}}\leq \frac{3\sqrt{\varepsilon}}{1-3\sqrt{\varepsilon}}\leq \frac{3\sqrt{\varepsilon}}{1/2} = 6\sqrt{\varepsilon}, \] where the second inequality is since $\varepsilon\in(0,\frac{1}{36})$. \textbf{Case (ii): }$d\geq 2$. We prove Case (ii) by proving the following $3$ properties \begin{enumerate}[(a)] \item $\left|1 - \sum_{i=1}^n u_i\cdot \norm{p_i}^2\right| \leq \sqrt{\varepsilon}$ \label{toProve1} \item $\left|1 -\sum_{i=1}^n u_i\right| \leq 3\sqrt{\varepsilon}$ \label{toProve2} \item $\norm{\sum_{i=1}^n u_ip_i} \leq 3\sqrt{\varepsilon}$ \label{toProve3} \end{enumerate} \textbf{Proof of~\eqref{toProve1}: }This step holds immediately by plugging $x = \textbf{0}_d$ in~\eqref{eq:forEveryx3}. \textbf{Proof of~\eqref{toProve2}: }Let $s^\bot \in \ensuremath{\mathbb{R}}^d$ be an arbitrary vector that is perpendicular to $\bar{s}$ and let $y = \frac{s^\bot}{\norm{s^\bot}}$. Such a vector $s^\bot$ exists due to our assumption that $\norm{\bar{s}} \neq 0$. We now have that \begin{equation}\label{eshieshi} \left|\left(1 - \sum_{i=1}^n u_i \norm{p_i}^2\right) + \left(1 -\sum_{i=1}^n u_i\right)\right| = \left|1+\norm{y}^2 - \sum_{i=1}^n u_i \norm{p_i}^2 +2y^T \sum_{i=1}^n u_i p_i -\sum_{i=1}^n u_i\norm{y}^2\right| \leq 2\sqrt{\varepsilon}, \end{equation} where the first derivation holds by combining that $y$ is perpendicular to $\sum_{i=1}^n u_i p_i$ (by definition) and that $\norm{y}^2=1$, and the second derivation holds by plugging $x=y$ in~\eqref{eq:forEveryx3}. Combining~\eqref{eshieshi} with Property~\eqref{toProve1} proves Property~\eqref{toProve2} as \[ -3\sqrt{\varepsilon} \leq \left(1 -\sum_{i=1}^n u_i\right) \leq 3\sqrt{\varepsilon}. \] \textbf{Proof of~\eqref{toProve3}: }Let $z = \frac{\bar{s}}{\norm{\bar{s}}} = \frac{\sum_{i=1}^n u_i p_i}{\norm{\sum_{i=1}^n u_i p_i}}$. We now have that \begin{align} & \left|\left(1 - \sum_{i=1}^n u_i \norm{p_i}^2\right) + \left(1-\sum_{i=1}^n u_i\norm{z}^2\right) +2\norm{\sum_{i=1}^n u_i p_i} \right| \nonumber\\ &= \left|\left(1 - \sum_{i=1}^n u_i \norm{p_i}^2\right) + \left(1-\sum_{i=1}^n u_i\norm{z}^2\right) +2z^T \sum_{i=1}^n u_i p_i \right| \label{defZ}\\ & =\left|1+\norm{z}^2 - \sum_{i=1}^n u_i \norm{p_i}^2 +2z^T \sum_{i=1}^n u_i p_i -\sum_{i=1}^n u_i\norm{z}^2\right|\label{defZ2} \leq 2\sqrt{\varepsilon}, \end{align} where~\eqref{defZ} holds by the definition of $z$, the first derivation in \eqref{defZ2} holds since $\norm{z}=1$, and the second derivation in~\eqref{defZ2} holds by plugging $x=z$ in~\eqref{eq:forEveryx2}. Therefore, \begin{equation}\label{eqAlmostThere} \left|\left(1 - \sum_{i=1}^n u_i \norm{p_i}^2\right) + \left(1-\sum_{i=1}^n u_i\norm{z}^2\right) +2\norm{\sum_{i=1}^n u_i p_i} \right| \leq 2\sqrt{\varepsilon}. \end{equation} Property~\ref{toProve3} now holds by combining~\eqref{eqAlmostThere} with Properties~\ref{toProve1}--\ref{toProve2} as \[ 2\norm{\sum_{i=1}^n u_i p_i} \leq 6\sqrt{\varepsilon}. \] Hence, combining Property~\ref{toProve2} with~\ref{toProve3} satisfies Case (ii) as \[ \sum_{i=1}^n \frac{u_i}{\norm{u}_1}p_i=\norm{\frac{\sum_{i=1}^n u_i p_i}{\sum_{i=1}^n u_i}}\leq \frac{3\sqrt{\varepsilon}}{1-3\sqrt{\varepsilon}}\leq 6\sqrt{\varepsilon}, \] where the last inequality holds since $\varepsilon \in(0,\frac{1}{36})$. By Case (i) and Case (ii) we have that $\norm{\sum_{i=1}^n \frac{u_i}{\norm{u}_1}p_i} \leq 6\sqrt{\varepsilon}$ for any $d\geq 1$. Lemma~\ref{strongToWeek} now holds by substituting $u$ and $\bar{s} = \sum_{i=1}^n \frac{u_i}{\norm{u}_1}p_i$ in Lemma~\ref{weak_coreset_lema}. \end{proof} \section{Strong and Weak $(\varepsilon,\delta)$-Coreset Constructions}\label{sec:strondelta} In this section, we aim to compute strong and weak $(\varepsilon,\delta)$-coreset for a normalized weighted set $(P,w)$. In Section~\ref{sec:sensitivityCoresets} we present a strong coreset construction result which utilizes the sensitivity sampling framework~\cite{DBLP:journals/corr/BravermanFL16}. We then combine this result with the reduction result from strong to weak coresets (see Section~\ref{sec:strongToWeak}) to obtain a weak coreset construction. In Section~\ref{sec:bernstein} we utilize the Bernstein inequality to obtain a weak coreset for an input set of points contained inside the unit ball. We then show how to leverage this result in order to compute both a strong coreset, based on non-uniform sampling and reweighting of the points. We then obtain a weak coreset by combining the strong coreset construction result with the reduction from Section~\ref{sec:strongToWeak}. Those weak and strong coresets are smaller than the ones obtained via the sensitivity framework in Section~\ref{sec:sensitivityCoresets}. \subsection{Sensitivity Based Coresets} \label{sec:sensitivityCoresets} We now prove that using a smart reweighting scheme of a normalized weighted input set, we can pick a non-uniform random sample of the input, based on the smart weights, to obtain a strong $\varepsilon$-coreset. This is based on the sensitivity framework suggested in~\cite{DBLP:journals/corr/BravermanFL16} and the sensitivity tight bound from~\cite{tremblay2018determinantal}. \begin{definition} [\textbf{Definition 4.2 in~\cite{DBLP:journals/corr/BravermanFL16}}] \label{def:querySpace} Let $(P,w)$ be a weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$. Let $Q$ be a set of items called queries. Let $f:P\times Q \to \ensuremath{\mathbb{R}}$ be a cost function. The tuple $(P,w,Q,f)$ is called a \emph{query space}. \end{definition} \begin{definition} [\textbf{Definition 4.5 in~\cite{DBLP:journals/corr/BravermanFL16}}] \label{def:VC} For a query space $(P,w,Q,f)$, $q\in Q$ and $r\in [0,\infty)$ we define \[ \mathrm{range}(q,r) = \br{p\in P \mid w(p)\cdot f(p,q) \leq r}. \] The dimension of $(P,w,Q,f)$ is the smallest integer $d'$ such that for every $C\subseteq P$ we have \[ \left| \br{\mathrm{range}(q,r) \mid q\in Q, r\in [0,\infty)} \right| \leq |C|^{d'}. \] \end{definition} \begin{theorem} [\textbf{Theorem 5.5 in~\cite{DBLP:journals/corr/BravermanFL16}}]\label{braverman} Let $(P,w,Q,f)$ be a query space; see Definition~\ref{def:querySpace}, where $f$ is a non-negative function. Let $s:P\to [0,\infty)$ such that \[ \sup_{q\in Q} \frac{w(p)f(p,q)}{\sum_{p\in P} w(p)f(p,q)} \leq s(p), \] for every $p\in P$ and $q\in Q$ such that the denominator is non-zero. Let $t = \sum_{p\in P} s(p)$ and let $d'$ be the dimension of the query space $(P,w,Q,f)$; See Definition~\ref{def:VC}. Let $c \geq 1$ be a sufficiently large constant and let $\varepsilon, \delta \in (0,1)$. Let $C$ be a random sample of \[ |C| \geq \frac{ct}{\varepsilon^2}\left(d'\log{t}+\log{\frac{1}{\delta}}\right) \] points from $P$, such that $p$ is sampled with probability $s(p)/t$ for every $p\in P$. Let $u(p) = \frac{t\cdot w(p)}{s(p)|C|}$ for every $p\in C$. Then, with probability at least $1-\delta$, for every $q\in Q$ it holds that \[ (1-\varepsilon)\sum_{p\in P} w(p)\cdot f(p,q) \leq \sum_{p\in C} u(p)\cdot f(p,q) \leq (1+\varepsilon)\sum_{p\in P} w(p)\cdot f(p,q). \] \end{theorem} \newcommand{\textsc{Sensitivity-sampling-Coreset}}{\textsc{Sensitivity-sampling-Coreset}} \begin{algorithm2e}[ht] \SetAlgoLined \caption{$\textsc{Sensitivity-sampling-Coreset}(P,w,\varepsilon,\delta)$\label{alg:prob}}{ \begin{tabbing} \label{alg1} \textbf{Input: \quad } \= A normalized weigthed set $(P,w)$ of $n\geq 2$ points in $\ensuremath{\mathbb{R}}^d$, such that $w=(\frac{1}{n}, \cdots, \frac{1}{n})$, \\ \> an error parameter $\varepsilon\in (0,1)$, and a probability of failure $\delta\in(0,1)$.\\ \textbf{Output: } \> A weight vector $u\in[0,1)^n$ of cardinality $\norm{u}_0 \in O(\frac{1}{\varepsilon}\left(d+\log{\frac{1}{\delta}}\right))$ non-zero entries \\ \> that satisfies Lemma~\ref{tightSens} and Lemma~\ref{tightSensWeak} . \end{tabbing}} \For{every $i \in \{1,\cdots,n\}$ \label{LineFor}} { $\displaystyle{s_i := \frac{1}{2n}\left(1+\norm{p_i}^2\right)}$ \label{s(p) def}\\ } $c:=$ the constant from Theorem~\ref{braverman}.\\ $S:=$ a random sample (multi-set) of $|S| \geq \frac{2c}{\varepsilon}\left(d+\log{\frac{1}{\delta}}\right)$ points from $P$ sampled i.i.d from the distribution $s=(s_1,\cdots,s_n)$ \label{Ssampled} \\ \For{every $i \in \{1,\cdots,n\}$} { $u_i := \frac{k_i 2\cdot w_i}{s(p_i)\abs{S}}$, where $k_i = |S\cap p_i|$ is the number of times $p_i$ was sampled for $S$. \label{usamled} } \Return $u$ \end{algorithm2e} \begin{lemma}[Strong coreset via sensitivity sampling]\label{tightSens} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$ such that $w=(\frac{1}{n},\cdots,\frac{1}{n})^T$. Let $c \geq 1$ be the constant from Theorem~\ref{braverman} and let $\varepsilon, \delta \in (0,1)$. Let $u$ be the output of a call to $\textsc{Sensitivity-sampling-Coreset}(P,w,\varepsilon^2,\delta)$; see Algorithm~\ref{alg:prob}. Then $(P,u)$ is a strong $(\varepsilon,\delta)$-coreset of cardinality $\norm{u}_0 \in O(\frac{1}{\varepsilon^2}\left(d+\log{\frac{1}{\delta}}\right))$ for $(P,w)$, i.e., with probability at least $1-\delta$, for every $x\in \ensuremath{\mathbb{R}}^d$ we have that \[ (1-\varepsilon)\sum_{i=1}^n w_i\cdot \norm{p_i-x}^2 \leq \sum_{i=1}^n u_i\cdot \norm{p_i-x}^2 \leq (1+\varepsilon) \sum_{i=1}^n w_i\cdot \norm{p_i-x}^2 . \] \end{lemma} \begin{proof} Mainly the proof here relies on Lemma D.1 of~\cite{tremblay2018determinantal} which states that for every $j\in[n]$, the sensitivity of the $j$th point is: $$s(p_j) := \sup_{x\in\ensuremath{\mathbb{R}}^d} \frac{\norm{p_j -x}^2}{\sum_{i=1}^n \norm{p_i - x}^2} =\frac{1}{n}\left(1+\frac{\norm{p_j}^2}{v}\right), $$ where $v=\sum_{i=1}^n 1/n\norm{p_i}^2$, and by our assumption we have that $v=1$. Hence, the total sensitivty is $$t := \sum_{j=1}^n \sup_{x\in\ensuremath{\mathbb{R}}^d} \frac{\norm{p_j -x}^2}{\sum_{i=1}^n\norm{p_i - x}^2} = \sum_{j=1}\frac{1}{n}\left(1+{\norm{p_j}^2}\right) =1+\sum_{j=1}^n\frac{1}{n}\norm{p_j}^2 = 2.$$ By Theorem~\ref{braverman}, if we sample $|S| \geq \frac{2c}{\varepsilon^2}\left(d+\log{\frac{1}{\delta}}\right)$ i.i.d points from $P$ according to the distribution $(s(p_1)/t ,\cdots ,s(p_n)/t)$, and define the weights vector $u = (u_1,\cdots,u_n)$ where $u_i := \frac{k_i 2\cdot w_i}{s(p_i)\abs{S}}$ and $k_i = |S\cap p_i|$ is the number of times $p_i$ was sampled for $S$, then $(P,u)$ is a strong $(\varepsilon,\delta)$-coreset for $(P,w)$. In Line~\ref{s(p) def} we compute the distribution $(s_1, \cdots, s_n) = (s(p_1)/t ,\cdots ,s(p_n)/t)$. In Line~\ref{Ssampled} we sample the set $S$ as required by Theorem~\ref{braverman}, and then we compute in Line~\ref{usamled} the final weights $u$. \end{proof} \begin{lemma}[Weak coreset via sensitivity sampling]\label{tightSensWeak} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$ such that $w=(\frac{1}{n},\cdots,\frac{1}{n})^T$. Let $c \geq 1$ be the constant from Theorem~\ref{braverman} and let $\varepsilon, \delta \in (0,1)$. Let $u$ be the output of a call to $\textsc{Sensitivity-sampling-Coreset}(P,w,{\varepsilon/36},\delta)$; see Algorithm~\ref{alg:prob}. Then $(P,u)$ is a weak $(\varepsilon,\delta)$-coreset of cardinality $\norm{u}_0 \in O\left(\frac{1}{\varepsilon}\left(d+\log{\frac{1}{\delta}}\right)\right)$ for $(P,w)$, i.e., with probability at least $1-\delta$, for every have that \[ \sum_{i=1}^n \frac{1}{n}\norm{p_i-\overline{s}}^2\leq (1+\varepsilon)\min_{x\in\mathbb{R}^d}\sum_{i=1}^n \frac{1}{n}\norm{p_i-x}^2. \] \end{lemma} \begin{proof} Lemma~\ref{tightSensWeak} immediately holds by combining Lemma~\ref{tightSens} with Theorem~\ref{strongToWeek}. \end{proof} \subsection{Bernstein Inequality for Smaller Coresets. } \label{sec:bernstein} The following theorem is Theorem 6.1.1 from~\cite{tropp2015introduction}. \begin{theorem}[Matrix Bernstein.]\label{berns} Consider a finite sequence $\{S_k\}$ of independent, random matrices with common dimension $d_1 \times d_2$. Assume that (i) $E (S_k) = 0,$ and (ii) $\norm{S_k}\leq L $ for each index $k$. Introduce the random matrix $Z = \sum_{k}S_k$. Let $v(Z)$ be the matrix variance statistic of the sum: \begin{align*} v(Z) &= \max\br{\norm{E(ZZ^T)},\norm{E(Z^TZ)}} \\&= \max\br{\norm{\sum_k E(S_kS_k^T)},\norm{\sum_k E(S_k^TS_k)}}. \end{align*} Then $$E(\norm{Z}) = \sqrt{2v(Z)\log(d_1+d_2)} + \frac{1}{3}L\log(d_1+d_2).$$ Furthermore, for all $t\geq 0$, $$\mathrm{pr}(\norm{Z} \geq t)\leq (d_1 +d_2) \exp\bigg(\frac{-t^2/2}{v(Z)+ Lt/3}\bigg).$$ \end{theorem} The following corollary is an immediate result of Theorem~\ref{berns}. \begin{corollary}[Bounding Points in the Unit Ball via Bernstein Inequality.]\label{pointsinunitbenrs} Let $\varepsilon,\delta \in (0,1)$, $(P,w)$ be a set of $n$ points in $\ensuremath{\mathbb{R}}^d$, such that for every $i\in [n]$, $\norm{p_i}\leq 1$, and $\sum_{i=1}^n w_i =1$. Let $S$ be a sample of $k=\frac{4\log((d+1)/\delta)}{\varepsilon}$ points, chosen i.i.d, where each $p_i\in P$ is sampled with probability $w_i$. Let $\overline{s} = \frac{1}{k}\sum_{s\in S}s$. Then with probability at least $1-\delta$ we have that, $$\norm{\overline{s}}^2 \leq \varepsilon.$$ \end{corollary} \begin{proof} Let $z = \sum_{s\in S}s$, and let $v(z) = \max\br{\norm{\sum^k_{i=1} E(s_is_i^T)},\norm{\sum^k_{i=1} E(s_i^Ts_i)}}.$ First, since for every $p\in P$ we have $\norm{p}\leq1$, we get that $$\norm{\sum^k_{i=1} E(s_i^Ts_i)} \leq \norm{\sum^k_{i=1} 1} = k.$$ Also \begin{align*} \norm{\sum^k_{i=1} E(s_is_i^T)} &= \norm{\sum^k_{i=1} \sum_{i=1}^n w_i p_ip_i^T} = k\norm{\sum_{i=1}^n w_i p_ip_i^T} \leq k\sum_{i=1}^n w_i\norm{ p_ip_i^T} \\& = k\sum_{i=1}^n w_i \sup_{x\in \ensuremath{\mathbb{R}}^d , \norm{x}=1} \norm{p_ip_i^Tx} = k\sum_{i=1}^n w_i \norm{p_ip_i^T\frac{p_i}{\norm{p_i}}} \\& = k\sum_{i=1}^n w_i \norm{p_i}^2 \leq k\sum_{i=1}^n w_i = k, \end{align*} where the first derivation holds by the definition of mean, the third holds by the rules of norm, the fourth by the definition of matrix norm, the seventh derivation holds since $||p_i||\leq 1$, and the last holds since $\sum_{i=1}^n w_i =1$. Hence $v(z) \leq k$. We are interested in bounding the following probability: $$\mathrm{pr}\bigg(\norm{\overline{s} }^2 \geq \varepsilon\bigg) .$$ To use Theorem~\ref{berns}, we observe that \begin{align}\label{touse} \mathrm{pr}(\norm{\overline{s}}^2 \geq \varepsilon)= \mathrm{pr}\bigg(\norm{\sum_{i=1}^k s_i/k }^2 \geq \varepsilon\bigg) = \mathrm{pr}\bigg(\norm{\sum_{i=1}^k s_i }^2 \geq \varepsilon k^2\bigg) = \mathrm{pr}\bigg(\norm{\sum_{i=1}^k s_i} \geq \sqrt{\varepsilon} k\bigg). \end{align} Plugging $d_1 = d, d_2 = 1, L=1, Z=z =\sum_{i=1}^k s_i$, and $t= \sqrt{\varepsilon}k$ in Theorem~\ref{berns} yields \begin{align}\label{useberns} \mathrm{pr}\bigg(\norm{\sum_{i=1}^k s_i} \geq \sqrt{\varepsilon} k\bigg) &\leq (d + 1) \exp\bigg(\frac{-(\sqrt{\varepsilon}k)^2/2}{v(z)+ 1\cdot \sqrt{\varepsilon} k/3}\bigg) = (d + 1) \exp\bigg(\frac{-\varepsilon k^2/2}{v(z)+ 1\cdot \sqrt{\varepsilon} k/3}\bigg) \\& \leq (d + 1) \exp\bigg(\frac{-\varepsilon k^2/2}{k+ 1\cdot \sqrt{\varepsilon} k/3}\bigg) = (d + 1) \exp\bigg(\frac{-\varepsilon k/2}{1+ 1\cdot \sqrt{\varepsilon}/3}\bigg)\nonumber \\ & \leq (d + 1) \exp\bigg(\frac{-\varepsilon k}{4}\bigg) ,\nonumber \end{align} where the third derivation holds since $v(z) = k$, and the last holds since $\varepsilon < 1.$ Substituting $k=\frac{4\log((d+1)/\delta)}{\varepsilon}$ in~\eqref{useberns} \begin{align}\label{doneusingberns} \mathrm{pr}\bigg(\norm{\sum_{i=1}^k s_i} \geq \sqrt{\varepsilon} k\bigg) \leq (d + 1) \exp\bigg(-\varepsilon \frac{4\log((d+1)/\delta)}{4\varepsilon}\bigg) = (d+1)\frac{\delta }{d+1} = \delta. \end{align} Hence, by combining~\eqref{touse} and~\eqref{doneusingberns} we obtain that $$\mathrm{pr}(\norm{\overline{s} }^2 < \varepsilon) = 1- \mathrm{pr}(\norm{\overline{s} }^2 \geq \varepsilon) = 1-\mathrm{pr}\bigg(\norm{\sum_{i=1}^k s_i} \geq \sqrt{\varepsilon} k\bigg) \geq 1-\delta.$$ \end{proof} \newcommand{\textsc{Bernstein-CoreSet}}{\textsc{Bernstein-CoreSet}} \begin{algorithm2e}[ht] \SetAlgoLined \caption{$\textsc{Bernstein-CoreSet}(P,w,\varepsilon,\delta)$\label{alg:berns}}{ \begin{tabbing} \label{algbern} \textbf{Input: \quad } \= A normalized weigthed set $(P,w)$ of $n\geq 2$ points in $\ensuremath{\mathbb{R}}^d$, \\ \> an error parameter $\varepsilon\in (0,1)$, \\ \>and a probability of failure $\delta \in (0,1)$.\\ \textbf{Output: } \> A weight vector $u\in[0,\infty)^n$ with $O(\frac{\log(d/\delta)}{\varepsilon})$ non-zero entries that satisfies \\ \>Theorems~\ref{strong-coreset-theorem-bern} and~\ref{weak-coreset-theorem-bern} . \end{tabbing}} \For{every $i \in \{1,\cdots,n\}$ \label{LineFor}} { $\displaystyle{s_i = \frac{w_i\norm{(p^T_i\mid 1)}^2}{\sum_{j=1}^n w_j\norm{(p_j^T\mid 1)}^2}}$\label{line:defdist} } $k=\frac{4\log((d+1)/\delta)}{\varepsilon}$ $S$ := an i.i.d random sample from $P$ of size $|S|=k$, where every point $p_i\in P$ is sampled with probability $s_i$. \For{every $i \in \{1,\cdots,n\}$} { $\displaystyle{u_i :=\frac{ 2 c_i} { k\norm{(p_i,1)}^2}}$, \label{w'} where $c_i = |S\cap p_i|$ is the number of times $p_i$ was sampled for $S$. } \Return $u$ \end{algorithm2e} \begin{theorem}[Strong coreset via Bernstein inequality] \label{strong-coreset-theorem-bern} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\varepsilon,\delta\in (0,1)$, and let $u=(u_1,\cdots,u_n)\in \ensuremath{\mathbb{R}}^n$ be the output of a call to $\textsc{Bernstein-CoreSet}(P,w,\varepsilon^2,\delta)$; See Algorithm~\ref{algbern}. Then $u$ has $\norm{u}_0\leq \frac{4\log(d+1/\delta)}{\varepsilon^2}$ non-zero entries and $(P,u)$ is a strong $(2\varepsilon,\delta)$-coreset for $(P,w)$, i.e., with probability at least $1-\delta$, for every $x\in\ensuremath{\mathbb{R}}^d$ we have that \[ \bigg| \sum_{i=1}^n (w_i -u_i )\norm{p_i-x}^2 \bigg| \leq 2\varepsilon \sum_{i=1}^n w_i\norm{p_i -x}^2. \] \end{theorem} \begin{proof} For every $i \in\br{1,\cdots, n}$, let $s_i = \frac{w_i\norm{(p^T_i\mid 1)}^2}{\sum_{i=1}^n w_i\norm{(p_i^T\mid 1)}^2}$, and define the distribution vector $s=(s_1,\cdots,s_n)$. Let $I$ be an i.i.d random sample from $\br{1,\cdots,n}$ of size $k=\frac{4\log((d+1)/\delta)}{\varepsilon^2}$, where every $i\in \br{1,\cdots,n}$ is sampled with probability $s_i$. Finally, for every $i\in \br{1,\cdots,n}$ assign a weight $u_i = \frac{2c_i}{k\norm{(p_i\mid 1)}^2}$, where $c_i$ is the number of times $i$ was sampled for $I$. For every $i \in \br{1,\cdots, n}$, let $p_i'= \frac{(p_i^T\mid 1)}{\norm{(p^T_i\mid 1)}^2}$. Let $P' = \br{p_i'\mid i\in \br{1,\cdots,n}}$. Let $S'$ be a set of size $\abs{I}$, that has the corresponding points from ${P'}$ to the sampled indexes in $I$, i.e., ${S'} = \br{{p'_i}| i \in I}$. Observe that \begin{enumerate}[(i)] \item for every $i\in [n]$, $\norm{p'_i}\leq1$, \item $\sum_{i=1}^n s_i = \sum_{i=1}^n \frac{w_i\norm{(p^T_i\mid 1)}^2}{\sum_{i=1}^n w_i \norm{(p_i^T\mid 1)}^2} =1$. \end{enumerate} Hence, by Corollary~\ref{pointsinunitbenrs} we have that with probability at least $1-\delta$ $$\norm{\sum_{i=1}^n s_i p_i' - \frac{1}{k}\sum_{p'\in S'}p'}^2 \leq \varepsilon^2.$$ Therefore, with probability at least $1-\delta$, $$\norm{\sum_{i=1}^n s_i p_i' - \frac{1}{k}\sum_{p'\in S'}p'} \leq \varepsilon.$$ Substituting $p_i'= \frac{(p_i^T\mid 1)}{\norm{(p^T_i\mid 1)}^2}$, and $s_i = \frac{w_i\norm{(p^T_i\mid 1)}^2}{\sum_{i=1}^n w_i \norm{(p_i^T\mid 1)}^2}$ for every $i\in [n]$ we get $$\norm{\sum_{i=1}^n \frac{w_i\norm{(p^T_i\mid 1)}^2}{\sum_{i=1}^n w_i\norm{(p_i^T\mid 1)}^2} \frac{(p_i^T\mid 1)}{\norm{(p^T_i\mid 1)}^2} - \frac{1}{k}\sum_{p'\in S'}p'} \leq \varepsilon.$$ Rearranging the above $$\norm{\sum_{i=1}^n\frac{w_i(p_i^T\mid 1)}{\sum_{i=1}^n w_i\norm{(p_i^T\mid 1)}^2} - \frac{1}{k}\sum_{p'\in S'}p'} \leq \varepsilon.$$ Observe that $\sum_{i=1}^n w_i\norm{(p_i^T\mid 1)}^2 = \sum_{i=1}^n w_i \norm{p_i}^2 + \sum_{i=1}^n w_i =2.$ Hence, multiplying both side by $2$ yields $$\norm{\sum_{i=1}^n {w_i(p_i^T\mid 1)} - \frac{2}{k}\sum_{p'\in S'}p'} \leq 2\varepsilon.$$ For every $i\in [n]$, let $c_i$ be the number of times $p'_i$ was sampled for $S'$. By observing that $\frac{1}{k}\sum_{p'\in S'}p' = \sum_{i=1}^n \frac{c_i}{k}p'_i = \sum_{i=1}^n \frac{c_i}{k\norm{(p_i^T\mid 1)}^2}(p^T_i\mid1)$, we obtain \begin{align}\label{neededinequalityviaberns} \norm{\sum_{i=1}^n {w_i(p_i^T\mid 1)} - \sum_{i=1}^n \frac{2c_i}{k\norm{(p_i^T\mid 1)}^2}(p^T_i\mid1) } \leq 2\varepsilon. \end{align} Now, for every $i\in \br{1,\cdots,n}$, let $\tilde{p_i} = (p_i\mid 1)$. Let $\tilde{P} = \br{\tilde{p_i}\mid i\in \br{1,\cdots,n}}$, and let $\tilde{S}$ be a set of size $\abs{I}$, that has the corresponding points from $\tilde{P}$ to the sampled indexes in $I$, i.e., $\tilde{S} = \br{\tilde{p_i}| i \in I}$. Finally, recall the weights vector $u=(u_1,\cdots,u_n)$. The squared euclidean distance from the mean of $(\tilde{P},u)$ to the mean of $(\tilde{P},w)$ is \begin{align}\label{neededinequalityviaberns2} \norm{\sum_{i=1}^n {w_i(p_i^T\mid 1)} - \sum_{i=1}^n u_i(p^T_i\mid1) }= \norm{\sum_{i=1}^n {w_i(p_i^T\mid 1)} - \sum_{i=1}^n \frac{2c_i}{k\norm{(p_i^T\mid 1)}^2}(p^T_i\mid1) }\leq 2\varepsilon. \end{align} where, the last equality holds by~\ref{neededinequalityviaberns}. In our algorithm, we sample according to the same distribution, and assign the same weights. Hence, by~\eqref{neededinequalityviaberns2} we have that \begin{enumerate} \item $ \norm{\sum_{i=1}^n {w_ip_i} - \sum_{i=1}^n \frac{2c_i}{k\norm{(p^T_i\mid 1)}^2}p_i} \leq 2\varepsilon.$ \label{oneyes} \item $|\sum_{i=1}^n w_i - \sum_{i=1}^n u_i |\leq 2\varepsilon$, and by plugging $\sum_{i=1}^n w_i= 1$, we obtain $$|1-\sum_{i=1}^n u_i|\leq 2\varepsilon$$ \label{twoyes} \item $2=2 \sum_{i=1}^n c_i/k = \sum_{i=1}^n u_i \norm{(p_i\mid 1)}^2 = \sum_{i=1}^n u_i\norm{p_i}^2 + \sum_{i=1}^n u_i$. Hence \label{3yes} $$|\sum_{i=1}^n u_i \norm{p_i}^2 -1| = |2-\sum_{i=1}^n u_i -1| = |1-\sum_{i=1}^n u_i| \leq 2\varepsilon. $$ \end{enumerate} Theorem~\ref{strong-coreset-theorem-bern} now holds by combining the above properties~\ref{oneyes}--~\ref{3yes} with Lemma~\ref{strong_coreset_lema}. \begin{comment} $$\norm{\sum_{i=1}^n s_i p_i' - \frac{1}{k}\sum_{p'\in S'}p'}^2 = \norm{\sum_{i=1}^n (s_i -\frac{c_i}{k})p'_i}^2$$ $$\norm{\sum_{i=1}^n \frac{w_i\norm{(p^T_i\mid 1)}^2}{\sum_{i=1}^n w_i\norm{(p_i^T\mid 1)}^2} \frac{(p_i^T\mid 1)}{\norm{(p^T_i\mid 1)}^2} - \sum_{i=1}^n \frac{c_i}{k} \frac{(p_i^T\mid 1)}{\norm{(p^T_i\mid 1)}^2}}^2 \leq \varepsilon.$$ Rearranging the above $$\norm{\sum_{i=1}^n \frac{w_i(p_i^T\mid 1)}{\sum_{i=1}^n w_i\norm{(p_i^T\mid 1)}^2} - \frac{1}{k}\sum_{p'\in S'}p'}^2 \leq \varepsilon.$$ \end{comment} \end{proof} \begin{theorem}[Weak coreset via Bernstein inequality] \label{weak-coreset-theorem-bern} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\varepsilon,\delta\in (0,1)$, and let $u=(u_1,\cdots,u_n)\in \ensuremath{\mathbb{R}}^n$ be the output of a call to $\textsc{Bernstein-CoreSet}(P,w,\varepsilon,\delta)$; See Algorithm~\ref{algbern}. Then $u$ has $\norm{u}_0\leq \frac{4\log(d+1/\delta)}{\varepsilon}$ non-zero entries and $(P,u)$ is a weak $(\varepsilon,\delta)$-coreset for $(P,w)$. \end{theorem} \begin{proof} By Theorem~\ref{strong-coreset-theorem-bern}, the output of a call to $\textsc{Bernstein-CoreSet}(P,w,\varepsilon/144,\delta)$ is a strong $\frac{\sqrt{\varepsilon}}{6}$-coreset for $(P,w)$. By Lemma~\ref{strongToWeek}, a $\frac{\sqrt{\varepsilon}}{6}$-coreset for $(P,w)$ is also a weak $\varepsilon$-coreset for $(P,w)$. \end{proof} Observe that Algorithm~\ref{alg:berns} and Algorithm~\ref{alg:prob} differ only in the sampling size of the set $S$. The computed distribution and re-weighting of the sampled points are exactly the same. This difference is due to the following facts: (i) Algorithm~\ref{alg:prob} relies on the generic sensitivity framework while Algorithm~\ref{alg:berns} hinges upon the analysis dedicated for the 1-mean problem, and (ii) Algorithm~\ref{alg:berns} uses the Bernstein equality to compute a coreset, while the hidden inequality used in the sensitivity framework is the Hoeffding inequality. Each inequality may be favorable according to the given scenario at hand. \section{Deterministic $\varepsilon$-Coreset}\label{sec:detcore} In the previous section we constructed randomized coresets. We now show how to construct both a deterministic weak $\varepsilon$-coreset and a deterministic strong $\varepsilon$-coreset in Theorem~\ref{weak-coreset-theorem} and Theorem~\ref{strong-coreset-theorem} respectively. This is by first constructing a weak coreset for an input set of points contained inside the unit ball. We then show how to leverage this result in order to compute a strong coreset, using the Frank-Wolfe algorithm. We then obtain a weak coreset by combining the strong coreset result with the reduction presented in Section~\ref{sec:strongToWeak}. We use what we call the measure $C_f$, which was defined in Section~{$2.2$} in~\cite{clarkson2010coresets}; See equality~$(9)$. For a simplex $S$ and concave function $f$, the quantity $C_f$ is defined as \begin{align} C_f := \sup \frac{1}{\alpha^2}( f(x) + (y-x)^T\Delta f(x)-f(y)),\label{C_F} \end{align} where the supremum is over every $x$ and $z$ in $S$, and over every $\alpha$ so that $y =x + \alpha(z-x)$ is also in $S$. The set of such $\alpha$ includes $[0, 1]$, but $\alpha$ can also be negative. \begin{theorem}[\textbf{Theorem~$2.2$ from~\cite{clarkson2010coresets}}] For simplex $S$ and concave function $f$, Algorithm~{1.1} from~\cite{clarkson2010coresets} finds a point $x(k)$ on a $k$-dimensional face of $S$ such that \[ \frac{f(x*) - f(x(k))}{4C_f} \leq \frac{1}{k + 3}, \] for $k > 0$, where $f(x*)$ is the optimal value of $f$. \end{theorem} \begin{theorem}[\textbf{Coreset for points inside the unit ball\label{thm1}}] Let $P=\{p_1,\cdots,p_n\}$ be a set of n points in $\ensuremath{\mathbb{R}}^d$ such that $\norm{p_i}\leq 1$ for every $i\in [n]$. Let $w=(w_1,\cdots,w_n)\in[0,1]^n$ be a distribution vector, i.e., $\sum_i w_i=1$ and let $\varepsilon\in(0,1)$.Then there is a distribution vector $\tilde{u}=(\tilde{u}_1,\cdots,\tilde{u}_n)\in[0,1]^n$ with $\norm{\tilde{u}}_0\leq 8/\varepsilon$ non-zero entries such that, \[ \norm{\sum_{i=1}^n(w_i-\tilde{u_i})p_i}^2\leq \varepsilon. \] \end{theorem} \begin{proof} Let $S\subseteq \ensuremath{\mathbb{R}}^n $ be the simplex that is the convex hull of the unit basis vectors of $\ensuremath{\mathbb{R}}^n$, for every $x=(x_1,\cdots,x_n)\in S$ we define $\displaystyle{f(x) =-\norm{\sum_{i=1}^n (w_i-x_i)p_i}^2}$. Let $C_f$ be defined for $f$ and $S$ as in~\ref{C_F}. Let $\tilde{\varepsilon} = \varepsilon/8$, $\tilde{u}$ be the output of a call to Algorithm~1.1 of~\cite{clarkson2010coresets} with $f$ as input after $k=\ceil{1/\tilde{\varepsilon}}$ iterations, and let $f(x^*)$ be the maximum value of $f$ in $S$. Based on Theorem 2.2~\cite{clarkson2010coresets} we have that $\tilde{u}$ is a point on a $k$-dimensional face of $S$ such that, \begin{align} \frac{ f(x^*) - f(\tilde{u}) }{4C_f} \leq \frac{1}{k+3}. \label{result of frank wolf}\end{align} Sine $f(x) \leq 0$ for every $x\in S$ We have that, $$f(x^*) = f(w) = -\norm{\sum_{i=1}^n (w_i-w_i)p_i}^2 =0.$$ By equality~$(12)$ at section~$2.2.$ in~\cite{clarkson2010coresets} we see that $C_f\leq diam(AS)^2$ for quadratic problems, while $A$ is the matrix of $d\times n$ such that the $i$-th col of $A$ is the $i$-th point in $P$. We have that, \begin{align*} diam(AS)^2 =\sup_{a,b \in AS}\norm{a-b}_2^2=\sup_{x,y \in S}\norm{Ax-Ay}^2_2 \end{align*} Observe that $x$ and $y$ are distribution vectors, thus \begin{align*} \sup_{x,y \in S}\norm{Ax-Ay}_2^2=\sup_{i,j} \norm{p_i-p_j}^2_2. \end{align*} Since $\norm{p_i}\leq1$ for each $i\in [n]$, we have that, \begin{align*} \sup_{i,j} \norm{p_i-p_j}^2_2 \leq 2. \end{align*} By substituting $f(\tilde{u})=-\norm{\sum_{i=1}^n(w_i-\tilde{u_i})p_i}^2$, $C_f\leq 2$, $k=1/\tilde{\varepsilon}$ and $f(x^*)=0$ in~\eqref{result of frank wolf} we get that, \begin{align} \frac{ \norm{\sum_{i=1}^n(w_i-\tilde{u_i})p_i}^2 } {8} \leq \frac{1}{1/\tilde{\varepsilon}+3}. \end{align} Multiplying both sides of the inequality by $8$ and rearranging yields, \begin{align} \norm{\sum_{i=1}^n(w_i-\tilde{u_i})p_i}^2 \leq \frac{8}{1/\tilde{\varepsilon}+3}\leq \frac{8}{1/\tilde{\varepsilon}}=8\cdot \tilde{\varepsilon} =\varepsilon , \end{align} and since $\tilde{u}$ is a point on a $k$-dimensional face of $S$, we have that, $$\norm{\tilde{u}}_0 = k = 1/\tilde{\varepsilon} =8/\varepsilon .$$ \end{proof} \paragraph{Overview of Algorithm~\ref{alg:two}. } Algorithm~\ref{alg:two} takes as input a normalized weighted set $(P,w)$ and an error parameter $\varepsilon$, and outputs a coreset which is both a weak $\varepsilon$-coreset and a strong $\sqrt{\varepsilon}$-coreset for $(P,w)$. In Lines~\ref{LineFor}--\ref{w'} we augment the data points and their weights, such that the new points are inside the unit ball. We then apply Theorem~\ref{thm1} to construct a coreset of size $O(1/\varepsilon)$ for the new data points of unit length. In Lines~\ref{LineFor}--\ref{u} we compute the output coreset weights. To construct a weak $\varepsilon$-coreset we call Algorithm~\ref{alg:two} with the normalized weighted input and the error parameter $\varepsilon$; see Theorem~\ref{weak-coreset-theorem}. To construct a strong $\varepsilon$-coreset we simply call Algorithm~\ref{alg:two} with the normalized weighted input and the error parameter $\varepsilon^2$; see Theorem~\ref{strong-coreset-theorem}. \newcommand{\textsc{Frank-Wolfe-CoreSet}}{\textsc{Frank-Wolfe-CoreSet}} \begin{algorithm2e}[ht] \SetAlgoLined \caption{$\textsc{Frank-Wolfe-CoreSet}(P,w,\varepsilon)$\label{alg:two}}{ \begin{tabbing} \label{alg1} \textbf{Input: \quad } \= A normalized weigthed set $(P,w)$ of $n\geq 2$ points in $\ensuremath{\mathbb{R}}^d$, \\ \> and an error parameter $\varepsilon\in (0,1)$.\\ \textbf{Output: } \> A weight vector $u\in[0,\infty)^n$ with $O(1/\varepsilon)$ non-zero entries that satisfies \\ \>Theorems~\ref{weak-coreset-theorem} and~\ref{strong-coreset-theorem} . \end{tabbing}} \For{every $i \in \{1,\cdots,n\}$ \label{LineFor}} { $\displaystyle{p'_i := \frac{(p_i,1)}{\norm{(p_i,1)}^2}}$ \label{p'}\\ $\displaystyle{w'_i :=\frac{ w_i\norm{(p_i,1)}^2}{2}}$ \label{w'} } Use Thorem~\ref{thm1} to compute a sparse vector $u$ with $O(1/\varepsilon)$ non-zero entries, such that $$\norm{\sum_{i=1}^n (w'_i - u_i')p'_i}^2\leq \varepsilon$$\label{define u'}\\ \For{every $i \in \{1,\cdots,n\}$ \label{LineFor2}} { $\displaystyle{u_i = \frac{2 u_i'}{\norm{(p_i,1)}^2}}$ \label{u} } \Return $u$ \end{algorithm2e} \begin{theorem}[Strong deterministic coreset via Frank-Wolfe] \label{strong-coreset-theorem} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\varepsilon\in (0,1)$, and let $u=(u_1,\cdots,u_n)\in \ensuremath{\mathbb{R}}^n$ be the output of a call to $\textsc{Frank-Wolfe-CoreSet}(P,w,(\frac{\varepsilon}{4})^2)$; See Algorithm~\ref{alg1}. Then $u$ has $\norm{u}_0\leq \frac{128}{\varepsilon^2}$ non-zero entries and $(P,u)$ is a strong $\varepsilon$-coreset for $(P,w$), i.e., for every $x\in\ensuremath{\mathbb{R}}^d$ we have that \[ \bigg| \sum_{i=1}^n (w_i -u_i )\norm{p_i-x}^2 \bigg| \leq \varepsilon \sum_{i=1}^n w_i\norm{p_i -x}^2. \] \end{theorem} \begin{proof} Let $\varepsilon'=\frac{\varepsilon}{4}$, let $p'_i := \frac{(p_i,1)}{\norm{(p_i,1)}^2}$ and $w'_i :=\frac{ w_i\norm{(p_i,1)}^2}{2}$ for every $i\in [n]$. By the definition of $u'$ at line~\ref{define u'} in Algorithm~\ref{alg1}, and since the algorithm gets ${\varepsilon'}^2$ as input, we have that \begin{align} \norm{u'}_0\leq 8/{\varepsilon'}^2 = \frac{128}{\varepsilon^2}, \label{gar1} \end{align} and \begin{align} \norm{\sum_{i=1}^n (w'_i - u_i')p'_i}^2\leq {\varepsilon'}^2 .\label{from alg} \end{align} For every $i\in[n]$ let $u_i = \frac{2 u_i'}{\norm{(p_i,1)}^2}$ be defined as at Line~\ref{u} of the algorithm. It immediately follows by the definition of $u=(u_1,\cdots,u_n)$ and~\eqref{gar1} that \begin{align} \norm{u}_0\leq 8/{\varepsilon'}^2, \label{gar1used} \end{align} also we have \begin{align} 2{\varepsilon'} &\geq 2\norm{\sum_{i=1}^n (w'_i - u_i')p'_i} = 2\norm {\sum_{i=1}^n \frac{ w_i\norm{(p_i,1)}^2 -u_i\norm{(p_i,1)}^2 } {2}\cdot \frac{(p_i,1)}{\norm{(p_i,1)}^2}} \nonumber \\ &= \norm { \sum_{i=1}^n ( w_i -u_i) \cdot (p_i,1)} =\norm { \bigg( \sum_{i=1}^n (w_i -u_i) \cdot p_i \mid \sum_{i=1}^n ( w_i -u_i ) \bigg )} \label{before last} \\ &\geq \norm { \sum_{i=1}^n (w_i -u_i)\cdot p_i }, \label{2eps bound} \end{align} where the first derivation follows from~\eqref{from alg}, the second holds by the definition of $w'_i$,$u'_i$,$u_i$ and $p'_i$ for every $i\in [n]$, and the last holds since $\norm{(x\mid y)} \geq \norm{x}$ for every $x,y$ such that $x\in \ensuremath{\mathbb{R}}^d$ and $y \in \ensuremath{\mathbb{R}}$. By~\eqref{before last} and since $w$ is a distribution vector we also have that \begin{align} 2{\varepsilon'} \geq \bigg| \sum_{i=1}^n ( w_i -u_i ) \bigg| = \abs{1-\sum_{i=1}^n u_i}. \label{bounding 1-sum ui} \end{align} By theorem~\ref{thm1}, we have that $u'$ is a distribution vector, which yields, \begin{align*} 2 = 2\sum_{i=1}^n u'_i = \sum_{i=1}^n u_i\norm{(p_i,1)}^2 = \sum_{i=1}^n u_i\norm{p_i}^2 + \sum_{i=1}^n u_i, \end{align*} By the above we get that $2- \sum_{i=1}^n u_i= \sum_{i=1}^n u_i\norm{p_i}^2$. Hence, \begin{align} \abs{ \sum_{i=1}^n (w_i-u_i)\norm{p_i}^2 } = \abs{ \sum_{i=1}^n w_i \norm{p_i}^2 - (2- \sum_{i=1}^n u_i)} = \abs{1- (2- \sum_{i=1}^n u_i)} = \abs{\sum_{i=1}^n u_i - 1} \leq 2{\varepsilon'} \label{bound on diff var*n} \end{align} where the first equality holds since $\sum_{i=1}^n u_i\norm{p_i}^2 = 2- \sum_{i=1}^n u_i$, the second holds since $w$ is a distribution and the last is by~\eqref{bounding 1-sum ui}. Now by ~\eqref{bound on diff var*n}, ~\eqref{bounding 1-sum ui} and~\eqref{2eps bound} we obtain that $u$ satisfies Properties~\eqref{1}--\eqref{3} in Lemma~\ref{strong_coreset_lema}. Hence, Theorem~\ref{strong-coreset-theorem} holds as, \begin{align} \abs{\sum_{i=1}^n (w_i-u_i)\norm{p_i - x}^2 } \leq 4{\varepsilon'} \sum_{i=1}^n {w_i \norm{p_i-x}^2} = \varepsilon \sum_{i=1}^n {w_i \norm{p_i-x}^2} . \end{align} \end{proof} \begin{theorem}[Weak deterministic coreset via Frank-Wolfe] \label{weak-coreset-theorem} Let $(P,w)$ be a normalized weighted set of $n$ points in $\ensuremath{\mathbb{R}}^d$, and $\varepsilon\in (0,1)$. Let $u=(u_1,\cdots,u_n)\in \ensuremath{\mathbb{R}}^n$ be the output of a call to $\textsc{Frank-Wolfe-CoreSet}(P,w,\varepsilon/576)$; See Algorithm~\ref{alg1}, and let $\overline{u} = \sum_{i=1}^n u_i p_i$. Then, $u$ has $\norm{u}_0\leq 8/\varepsilon$ non-zero entries and $(P,u)$ is a weak $4\varepsilon$-coreset for $(P,w)$, i.e., \[ \sum_{i=1}^n w_i\norm{p_i- \overline{u}}^2 \leq (1+\varepsilon) \min_{x\in \ensuremath{\mathbb{R}}^d}{\sum_{i=1}^n w_i \norm{p_i -x}^2}. \] \end{theorem} \begin{proof} By Theorem~\ref{strong-coreset-theorem}, the output of a call to $\textsc{Frank-Wolfe-CoreSet}(P,w,\varepsilon/576)$ is a strong $\frac{\sqrt{\varepsilon}}{6}$-coreset for $(P,w)$. By Lemma~\ref{strongToWeek}, a $\frac{\sqrt{\varepsilon}}{6}$-coreset for $(P,w)$ is also a weak $\varepsilon$-coreset for $(P,w)$. \end{proof} \section{Weak Coreset Constructions in Sublinear Time}\label{sec:weaksublinear} In this section we present two coreset construction result, both of which require sublinear time, which compute a weak $\varepsilon$-coreset for the mean problem. Therefore, we cannot assume that the input is a normalized weighted set. The first result utilizes Chebychev's inequality (see Section~\ref{sec:chebychev}), and the second result utilizes the known median of means result (see Section~\ref{sec:medianOfMeans}). \subsection{Weak Coreset via Chebychev's Inequality} \label{sec:chebychev} In what follows we prove that a uniform random sample $S$ of sufficiently large size yields a weak $\varepsilon$-coreset with high probability. To do so, we first use Chebyshev's inequality to show that, with high probability, the mean of $S$ is small, and then conclude by applying Lemma~\ref{weak_coreset_lema}. \newcommand{\sigma}{\sigma} \newcommand{\sum_{p\in P}}{\sum_{p\in P}} \newcommand{\sum_{p\in S}}{\sum_{p\in S}} \begin{lemma}[Weak coreset via Chebychev inequality] \label{weak_coreset_markov} Let $P$ be a set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\mu = \frac{1}{n}\sum_{p\in P} p$, and $\sigma^2=\frac{1}{n}\sum_{p\in P} \norm{p - \mu}^2$. Let $\varepsilon,\delta \in (0,1)$, and let $S$ be a sample of $m = \frac{1}{\varepsilon\delta}$ points chosen i.i.d uniformly at random from $P$. Then, with probability at least $1-\delta$ we have that $$\norm{ \frac{1}{m}\sum_{p\in S} p - \mu}^2 \leq \varepsilon \sigma^2.$$ \end{lemma} \begin{proof} For any random variable $X$, we denote by $E(X)$ and $\text{var}(X)$ the expectation and variance of the random variable $X$ respectively. Let $x_i$ denote the random variable that is the $i$th sample for every $i\in [m]$. Since the samples are drawn i.i.d, we have \begin{equation} \text{var}\left(\frac{1}{m}\sum_{p\in S} p\right) = \sum_{i=1}^{m} \text{var}\left(\frac{x_i}{m}\right) = m \cdot \text{var}\left(\frac{x_1}{m}\right) = m\left(\frac{\sigma^2}{m^2}\right) = \frac{\sigma^2}{m} = \varepsilon\delta\sigma^2. \label{variance} \end{equation} For any random variable $X$ and error parameter $\varepsilon' \in (0,1)$, the generalize Chebyshev's inequality~\cite{chen2007new} reads that \begin{equation}\label{eq:GenCheby} \Pr (\norm{X - E(X)} \geq \varepsilon') \leq \frac{\text{var}(X)}{(\varepsilon')^2}. \end{equation} Substituting $X = \frac{1}{m}\sum_{p\in S} p$, $E(X) = \mu$ and $\varepsilon' = \sqrt{\varepsilon}\sigma$ in~\eqref{eq:GenCheby} yields that \begin{equation} \Pr\left(\norm{ \frac{1}{m}\sum_{p\in S} p - \mu} \geq \sqrt{\varepsilon} \sigma \right) \leq \frac{\text{var}(\frac{1}{m}\sum_{p\in S} p)}{\sigma^2\varepsilon }. \label{chebchev} \end{equation} Combining~\eqref{variance} with~\eqref{chebchev} proves the lemma as: \begin{equation} \Pr\left(\norm{ \frac{1}{m}\sum_{p\in S} p - \mu}^2 \geq \varepsilon \sigma^2 \right) \leq \frac{\varepsilon\delta\sigma^2}{\sigma^2\varepsilon} =\delta . \end{equation} \end{proof} \subsection{Weak Coreset Via Median Of Means} \label{sec:medianOfMeans} The following algorithm and theorem show how to compute, in sublinear time, a weak $(\varepsilon,\delta)$-coreset of smaller size, compared to the one in Section~\ref{sec:chebychev}, using the median of means approach. \newcommand{\frac{4}{\eps}}{\frac{4}{\varepsilon}} \newcommand{\frac{\eps}{4}}{\frac{\varepsilon}{4}} \newcommand{\floor{3.5\log{\left(\frac{1}{\delta}\right)}} +1}{\floor{3.5\log{\left(\frac{1}{\delta}\right)}} +1} \newcommand{{3.5\log{({1}/{\delta})}}}{{3.5\log{({1}/{\delta})}}} \newcommand{\frac{4k}{\eps}}{\frac{4k}{\varepsilon}} \newcommand{\textsc{Prob-Weak-Coreset}}{\textsc{Prob-Weak-Coreset}} \begin{algorithm2e}[ht] \SetAlgoLined \caption{$\textsc{Prob-Weak-Coreset}(P,\varepsilon,\delta)$\label{alg:smallProb}}{ \begin{tabbing} \textbf{Input: \quad } \= A set $P$ of $n\geq 2$ points in $\ensuremath{\mathbb{R}}^d$, \\ \> an error parameter $\varepsilon\in (0,1)$, \\ \> and a probability parameter $\delta \in (0,1)$\\ \textbf{Output: } \> A subset $S\subseteq P$ that satisfies Lemma~\ref{weak-probabilistic-coreset-theorem}. \end{tabbing}} $k:= \floor{3.5\log{\left(\frac{1}{\delta}\right)}} +1$. \label{line:defk}\\ $S:=$ an i.i.d sample of size $\frac{4k}{\eps}$.\\ $\br{S_1, \cdots, S_{k}} :=$ a partition of $S$ into $k$ disjoint subsets, each contains $\frac{4}{\eps}$ points .\label{line:sapledsets} \\ Set $\overline{s}_i:=$ the mean of the $i$'th subset $S_i$ for every $i \in [k]$. \label{line:si}\\ $\displaystyle{i^{*}:=\argmin_{j \in [k]}\sum_{i=1}^{k}\norm{\overline{s}_i -\overline{s}_j }_2}$. \\ \tcp{$i^{*}$ is the index of the closest subset mean $\overline{s}_i^{*}$ to the geometric median of the set $\br{\overline{s}_1,\cdots,\overline{s}_{k}}$.} \label{closeindex} \Return $S_{i^{*}}$ \end{algorithm2e} \begin{lemma} [Weak coreset via median of means] \label{weak-probabilistic-coreset-theorem} Let $P$ be a set of $n$ points in $\ensuremath{\mathbb{R}}^d$, $\mu = \frac{1}{n}\sum_{p\in P} p$, and $\sigma^2=\frac{1}{n}\sum_{p\in P} \norm{p - \mu}^2$. Let $\varepsilon\in (0,1)$, $\delta \in (0,0.9]$, and let $S_{i^{*}}=\br{s_i,\cdots, s_{\abs{S}}} \subseteq \ensuremath{\mathbb{R}}^{d}$ be the output of a call to $\textsc{Prob-Weak-Coreset}(P,\varepsilon,\delta)$; See Algorithm~\ref{alg:smallProb}. Then $S\subseteq P$ is of size $|S| = \frac{4}{\varepsilon}$, and with probability at least $1-3\delta$ we have that $$ \norm{ \frac{1}{\abs{S}} \sum_{i=1}^{\abs{S}} s_i - \mu }^2 \leq 33 \cdot \varepsilon\sigma^2.$$ Furthermore, $S_i^*$ can be computed in $O\left(d\left (\log^2{(\frac{1}{\delta})} + \frac{\log{(\frac{1}{\delta})}}{\varepsilon} \right) \right)$ time. \end{lemma} \begin{proof} Let $\br{S_1,\cdots,S_k}$ be a set of $k$ i.i.d sampled subsets each of size $\frac{4}{\eps}$ as defined at Line~\ref{line:sapledsets} of Algorithm~\ref{alg:smallProb}, and let $\overline{s}_i$ be the mean of the $i$th subset $S_i$ as define at Line~\ref{line:si}. Let $\displaystyle{\hat{s}:=\argmin_{x\in \ensuremath{\mathbb{R}}^d}\sum_{i=1}^{k}\norm{\overline{s}_i - x}_2}$ be the geometric median of the set of means $\br{\overline{s}_1,\cdots,\overline{s}_{k}}$. Using Corollary~$4.1.$ from~\cite{minsker2015geometric} we obtain that $$\Pr \left(\norm{\hat{s} - \mu} \geq 11\sqrt{\frac {\sigma^2\log({1.4}/{\delta})}{ \frac{4k}{\eps} } }\right )\leq \delta,$$ from the above we have that \begin{align} \Pr \left(\norm{\hat{s}- \mu}^2 \geq 121{\frac {\varepsilon\sigma^2\log({1.4}/{\delta})}{ 4k } }\right )\leq \delta.\label{paperbound} \end{align} Note that \begin{align} \Pr \left(\norm{\hat{s}- \mu}^2 \geq 121{\frac {\varepsilon\sigma^2\log({1.4}/{\delta})}{ 4k } }\right ) &= \Pr \left(\norm{\hat{s}- \mu}^2 \geq 30.25 \cdot \varepsilon\sigma^2{\frac {\log({1.4}/{\delta})}{ \floor{3.5\log{\left(\frac{1}{\delta}\right)}} +1 } }\right )\label{i1} \\ &\geq \Pr \left(\norm{\hat{s}- \mu}^2 \geq 31\cdot \varepsilon\sigma^2 \right ), \label{use} \end{align} where~\eqref{i1} holds by substituting $k=\floor{3.5\log{\left(\frac{1}{\delta}\right)}} +1$ as in Line~\ref{line:defk} of Algorithm~\ref{alg:smallProb}, and~\eqref{use} holds since $\frac {\log({1.4}/{\delta})}{ \floor{3.5\log{\left(\frac{1}{\delta}\right)}} +1 }<1$ for every $\delta \leq 0.9$ as we assumed. Combining~\eqref{use} with~\eqref{paperbound} yields, \begin{align}\label{medianisclose} \Pr \left(\norm{\hat{s}- \mu}^2 \geq 31 \cdot \varepsilon \sigma^2\right ) \leq \delta. \end{align} For every $i\in [k]$, by substituting $S = S_i$, which is of size $\frac{4}{\varepsilon}$, in Lemma~\ref{weak_coreset_markov}, we obtain that \[ \Pr(\norm{\overline{s}_i -\mu}^2 \geq \varepsilon \sigma^2) \leq 1/4. \] Hence, with probability at least $1- ({1}/{4})^{k}$ there is at least one set $S_j$ such that $$\norm{\overline{s}_j -\mu}^2 \leq \varepsilon\sigma^2.$$ By the following inequalities: $$ ({1}/{4})^{k} = ({1}/{4})^{\floor{3.5\log{\left(\frac{1}{\delta}\right)}} +1} \leq ({1}/{4})^{\log(1/\delta)} = 4^{\log(\delta)} \leq 2^{\log(\delta)}=\delta$$ we get that with probability at least $1-\delta$ there is a set $S_j$ such that \begin{align}\label{closetothemean} \norm{\overline{s}_j -\mu}^2 \leq \varepsilon\sigma^2. \end{align} Combining~\eqref{closetothemean} with~\eqref{medianisclose} yields that with probability at least $(1-\delta)^2$ the set $S_j$ satisfies that \begin{align}\label{medianandmean} \norm{\overline{s}_j - \hat{s}}^2 \leq 32 \varepsilon \sigma^2 . \end{align} Let $f:\ensuremath{\mathbb{R}}^d\to [0,\infty)$ be a function such that $f(x)=\sum_{i=1}^{k}\norm{\overline{s}_i - x }_2$ for every $x\in \ensuremath{\mathbb{R}}^d$. Therefore, by the definitions of $f$ and $\hat{s}$, $\displaystyle{\hat{s}:=\argmin_{x\in \ensuremath{\mathbb{R}}^d}\sum_{i=1}^{k}\norm{\overline{s}_i - x}_2=\argmin_{x\in \ensuremath{\mathbb{R}}^d}f(x)}$. Observe that $f$ is a convex function since it is a sum over convex functions. By the convexity of $f$, we get that for every pair of points $p,q \in P$ it holds that: \begin{align}\label{Imsmart} \text{if } f(q) \leq f(p) \text{ then } \norm{q-\hat{s}} \leq \norm{p-\hat{s}}. \end{align} Therefore, by the definition of $i^{*}$ at Line~\ref{closeindex} of Algorithm~\ref{alg:smallProb} we get that \begin{align}\label{Imsmart2} {i^{*}} \in \argmin_{i\in [k]}\norm{\overline{s}_{i} - \hat{s}}. \end{align} Now by combining~\eqref{medianandmean} with~\eqref{Imsmart2} we have that: \begin{align}\label{medianandclosetoit} \Pr\left(\norm{\overline{s}_{i^{*}} - \hat{s}}^2 \leq 32 \varepsilon \sigma^2 \right) \geq (1-\delta)^2 . \end{align} Combining~\eqref{medianandclosetoit} with~\eqref{medianisclose} and noticing the following inequality $$(1-\delta)^3 = (1-2\delta +\delta^{2})(1-\delta) \geq (1-2\delta )(1-\delta) =1 -\delta -2\delta + 2\delta^2 \geq 1-3\delta,$$ satisfies Lemma~\ref{weak-probabilistic-coreset-theorem} as, \[ \Pr\left( \norm{ \overline{s}_{i^{*}} -\mu }^2 \leq 33\varepsilon \sigma^2\right) \leq 1-3\delta. \] \noindent\textbf{Running time.} It takes $O\left( \frac{d\log{(\frac{1}{\delta})}}{\varepsilon} \right)$ to compute the set of means at Line~\ref{line:si}, and $O\left(d\log{(\frac{1}{\delta})}^2 \right)$ time to compute Line~\ref{closeindex} by simple exhaustive search over all the means. Hence, the total running time is $O\left(d\left (\log{(\frac{1}{\delta})}^2 + \frac{\log{(\frac{1}{\delta})}}{\varepsilon} \right) \right)$. \end{proof} \clearpage \bibliographystyle{alpha}
{'timestamp': '2021-11-05T01:22:23', 'yymm': '2111', 'arxiv_id': '2111.03046', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03046'}
arxiv
\section{Introduction} \begin{figure} \centering \begin{subfigure}[b]{0.46\textwidth} \includegraphics[width=1.0\textwidth]{qualitative/wgangp_lsun_fig1.png} \caption{WGAN-GP (FID: 13.6)} \end{subfigure}\\ \begin{subfigure}[b]{0.46\textwidth} \includegraphics[width=1.0\textwidth]{qualitative/sngan_lsun_fig1.png} \caption{SNGAN (FID: 13.2)} \end{subfigure}\\ \begin{subfigure}[b]{0.46\textwidth} \includegraphics[width=1.0\textwidth]{qualitative/grand_lsun_fig1.png} \caption{GraND-GAN (FID: 10.8)} \end{subfigure} \caption{Images generated by WGAN-GP, SNGAN, and our method (GraND-GAN) on $128\times128$ LSUN-Bedrooms (zoom in for better viewing). Lower FID is better.} \label{fig:my_label} \end{figure} Generative adversarial networks (GANs) \cite{goodfellow2014generative} are a class of generative models that have been shown to be very effective, especially for unsupervised high-resolution image generation \cite{miyato2018spectral,gulrajani2017improved,karras2019style,karras2020analyzing}. GANs usually consist of two networks, a generator $G(z)$ that generates synthetic data conditioned on a noise vector $z$ (sampled from a known noise distribution, usually standard normal) and a discriminator (or critic) $D(x)$ that classifies real data from the generated synthetic data. $G$ and $D$ are generally parametrized as deep neural networks and optimize a mini-max objective. A Nash equilibrium of the zero-sum game is attained when $G$ models the real data distribution and $D$ is maximally uncertain in discriminating the real from synthetic samples.% Despite the effectiveness of GANs in modeling high-dimensional data distributions, they are hard to train. The quality of the images output by $G$ is dependent on the magnitude of the \textit{input gradients} of the generator loss $\mathcal{L}_G$, written % \begin{align} \label{eq1} \nabla_x\mathcal{L}_G(D(x))= \nabla_{D}\mathcal{L}_G(D(x)) \nabla_xD(x) , \end{align} where $x=G(z)$. The characteristics of the input gradient of $\mathcal{L}_G$, in general, are determined both by the architecture of the discriminator $D(x)$ as well as the loss function $\mathcal{L}_G$ used in formulating the mini-max objective. In turn, $\nabla_xD(x)$ is a function of the parameters $\theta_D$ of the discriminator (or critic) that is trained to minimize a loss $\mathcal{L}_D$ to separate real samples $x_r$ from the synthetically generated ones $x_f=G(z)$ for a given $G$. Therefore, in contrast to image classification, the role of $D$ is not only to accurately discriminate real data from fake or synthetic data, but also to have a well-behaved input gradient $\nabla_x D(x)$, which is the primary signal that $G$ relies on for learning. Designing such a discriminator is a major objective for GAN research. % Towards this goal, in this paper, we present a novel input-dependent normalization method called \textit{Gradient Normalization} or \textit{GraN}, which guarantees bounded gradients and a piecewise Lipschitz constraint almost everywhere. GraN can be applied to neural networks with piecewise linear activation functions, a prominent class of function approximators within deep learning, and we use the normalized output for discriminators (or critics). Fig.\ \ref{fig:my_label} shows a qualitative comparison of our method on the popular dataset LSUN-Bedrooms. % Other works have considered constraining $D$ for stabilizing GAN training. In contrast to spectral normalization \cite{miyato2018spectral}, our method does not restrict processing at the individual layers and achieves a tight, piecewise Lipschitz bound on the class of functions that $D$ can model. Unlike gradient penalties \cite{gulrajani2017improved}, which softly penalize gradient norms at samples from the input space, our method strictly enforces piecewise constant gradients over the entire input space and ensures the gradient norms within each piece are strictly bounded by a single Lipschitz constant. However, our normalization introduces discontinuities in the discriminator itself, and it is only piecewise continuous and piecewise Lipschitz. Nevertheless, we show that our method achieves empirical results that are competitive with or better than existing methods.% Our main contributions are as follows: \begin{itemize}[itemsep=0pt,partopsep=0pt,topsep=0pt] \item We present Gradient Normalization (GraN) for piecewise linear networks $f(x)$ that strictly constrains $f$ to be piecewise $\mathcal{K}$-Lipschitz, where the input space $x$ is partitioned into convex polytopes in each of which $f(x)$ is linear with $\| \nabla_x f(x) \| = \mathcal{K}$. \item We show that normalizing discriminators (or critics) with GraN bounds the gradients received by the generator $G$ almost everywhere, stabilizing GAN training. \item Unlike spectral normalization (SN), GraN does not restrict processing at the individual layers and does not suffer from gradient attenuation. Further, in contrast to both SN and gradient penalties, GraN enforces the piecewise Lipschitz property as a hard constraint. \item Empirically, GraN performs better or competitive to existing methods on multiple datasets (CIFAR-10, CIFAR-100, STL-10, LSUN bedrooms, and CelebA), and two loss functions (discriminators with a non-saturating cross-entropy loss and critics with a soft hinge loss). \item While GraN only enforces a local, piecewise Lipschitz constraint, we find the finite-difference gradient norm is empirically well-behaved across large step sizes, likely including jumps across the polytopes modeled by $f$. \item We also investigate the effect of the Lipschitz constant $\mathcal{K}$ on standard baseline models, finding (a) constrained discriminators (trained with cross-entropy loss) outperform constrained critics, (b) $\mathcal{K}$ influences training dynamics when using Adam, especially on loss plateaus, and (c) tuning $\mathcal{K}$ can significantly improve performance. \end{itemize} \section{Related Work} \label{relwork} \subsection{Stabilizing GANs} \label{relwork:stab} Most previous works on stabilizing GANs take one of the following approaches: (1) proposing novel loss functions (e.g., \cite{mao2017least,berthelot2017began}), (2) devising improved architectures (e.g., \cite{karras2020analyzing,zhang2019self,zhao2020diffaugment,park2021styleformer,gong2019autogan,ghosh2018multi,karras2017progressive}) or (3) introducing new constraints on $D$ (e.g., \cite{arjovsky2017towards,arjovsky2017wasserstein,roth2017stabilizing,tseng2021regularizing}). Herein, we continue along the latter line of research, constructing an architectural regularization on $D$ that improves training without sacrificing network capacity. One of the earliest works on constraining $D$ to stabilize GAN training is the Wasserstein GAN (WGAN) \cite{arjovsky2017wasserstein}. They propose a novel loss function and present weight-clipping as a way to regularize $D(x)$ to be 1-Lipschitz in $x$. However, subsequent work \cite{gulrajani2017improved} showed gradient penalties to be more effective, as they do not impede optimization or severely reduce network capacity. \subsection{Gradient Penalties} \label{relwork:gradpen} Recent research has found gradient penalties (GPs), of the form $ % P_\delta(x) = ( || \nabla_x f(x) ||_2 - \delta )^2, $ % to be useful for GANs. Building on WGAN, among the most popular GAN variants is WGAN-GP \cite{gulrajani2017improved}, which forgoes weight clipping by applying $P_1$ along random convex combinations of reals and fakes, since any $C^0$ function with unit-length gradient is necessarily 1-Lipschitz. Later research considered \textit{one-sided} GPs \cite{petzka2017regularization}, as well as alternate sampling methods \cite{wei2018improving}. Part of the motivation for turning to optimal transport distances is the reduction of gradient uninformativeness, which is a problem for most $f$-divergence-based GANs when the real and fake distributions do not sufficiently overlap \cite{roth2017stabilizing}. However, Zhou \etal \cite{zhou2019lipschitz} show that Lipschitz continuity can combat gradient uninformativeness in GANs more generally. Separately, Roth \etal \cite{roth2017stabilizing} showed that increasing distributional overlap via noise is approximately equivalent to a zero-centered GP. This was simplified to the popular ``R1'' GP (defined as $P_0$ on real data) \cite{mescheder2018training}, used in recent state-of-the-art GANs (e.g., \cite{karras2020analyzing,chan2020pi}). Clearly, gradient regularization has seen empirical success in improving GANs. Yet, a downside of soft GPs is that they may not enforce exactly the desired value at a given position; furthermore, they are only applied to a subset of the input domain, which may shift over time. In contrast, GraN enforces unit gradients almost everywhere by construction. \subsection{Weight Normalization} Weight normalization (WN) \cite{salimans2016weight} reparametrizes layers in a manner conducive to better conditioned optimization, used in early GAN work \cite{salimans2016improved}. In WN, for each individual layer $i$ of the network, the corresponding weight vectors are rewritten as $% \widetilde{w_i} = w_i {\rho_i} / {|| w_i ||}~\forall~i, $ % where the learned scalar $\rho_i$ controls the norm and $w_i/{|| w_i ||}$ represents the direction. For piecewise linear networks, each $x$ is linearly mapped to $f(x) = w\cdot x + b$, where $w$ is locally constant around $x$, is implicitly input-dependent, and may be interpreted as the \textit{effective weight vector} of a (local) linear model (see \S\ref{sec-pieces} for details). In a manner reminiscent of WN, GraN essentially normalizes $f$ by the norm of its gradient, i.e., $\nabla_xf=||w||$. In contrast, however, GraN acts on the full network, rather than a single layer at a time, and enforces piecewise constant gradients, rather than reparametrizing the network. \subsection{Spectral Normalization and Gradient Attenuation under Global Lipschitz Constraints} Building on prior regularizations, such as GPs and weight clipping, Miyato \etal \cite{miyato2018spectral} present spectral normalization (SN) as an alternative method of ensuring $D$ is 1-Lipschitz, without an additional penalty in the objective for $D$. This is enforced by a layer-wise weight normalization technique, dividing by an estimate of the maximal singular value from each weight matrix. Empirically, SN is an effective stabilizer for GANs during training, independent of the loss function employed. As a result, it is a major component in recent large-scale GANs \cite{brock2018large,schonfeld2020u}. We discuss SN further in \S\ref{sec-comparisons}. At an architectural level, balancing network capacity and regularization is difficult for globally Lipschitz-constrained networks. Indeed, Anil \etal \cite{anil2019sorting} showed that standard networks struggle to solve simple tasks when globally Lipschitz constrained, and that smooth SNed ReLU networks with unit gradients become globally linear, which they solve by enforcing gradient norm preservation and weight matrix orthonormality. We avoid this in GraN by permitting discontinuities in $D$ with respect to the input space and by only constraining the Lipschitz constant $\mathcal{K}$ locally in a piecewise manner. Later work \cite{li2019preventing} combated the gradient attenuation induced by Lipschitz constraints with a novel orthogonal convolution operator. In contrast, % GraN can be applied on top of any piecewise linear network without globally constraining $\mathcal{K}$, while doing so locally in a piecewise sense. \section{Background} \subsection{Generative adversarial networks} \label{sec-background-gans} Let $\mathbb{P}_r$ represent the distribution of real data and $\mathbb{P}_g$ be the distribution of generated data at a given state of the generator $G$. Let $\mathcal{L}_G$ and $\mathcal{L}_D$ represent the loss functions for the generator $G$ and the discriminator (or critic) $D$, respectively. Let $z\sim \mathcal{N}(0, 1)$ be a $|\mathcal{Z}|$-dimensional noise vector sampled from an i.i.d.\ standard normal distribution. Let $f:\mathbb{R}^{d} \rightarrow \mathbb{R}$ represent a deep neural network encoding a scalar field. For image generation, $ \mathbb{R}^{d} = \mathbb{R}^{3 \times H \times W} $. Goodfellow \etal \cite{goodfellow2014generative} originally propose a cross-entropy (CE) loss-based objective for training $G$ and $D$ as follows: \begin{align} &\mathcal{L}_D = \mathbb{E}_{x \sim \mathbb{P}_r}\left[ -\log D(x) \right] + \mathbb{E}_{x \sim \mathbb{P}_g}\left[ -\log (1-D(x)) \right],\label{eqD1} \\ &\mathcal{L}_G = \mathbb{E}_{x \sim \mathbb{P}_g}\left[\log (1-D(x)) \right]\label{eqG1}, \end{align} where the discriminator $D(x) = \sigma(f(x))\in [0, 1]$ represents the probability of a sample $x$ coming from the real distribution $\mathbb{P}_r$ and $\sigma(\cdot)$ is the sigmoid function $1/(1+e^{-(\cdot)})$. Hence, $f$ computes a logit mapped to a probability by $\sigma(\cdot)$. The gradient of $\mathcal{L}_G$ with respect to the inputs $x$ is then \begin{align} \nabla_x\mathcal{L}_G = \mathbb{E}_{x\sim \mathbb{P}_g}\left[-D(x)\nabla_xf(x)\right]. \end{align} Notice that, when $D(x)\rightarrow 0$ for some generated $ x \sim \mathbb{P}_g$, the contribution to $ \nabla_x\mathcal{L}_G $ from such points will necessarily be small and have little influence on updating $G$. This is particularly probable early in training, when $\mathbb{P}_g$ and $\mathbb{P}_r$ are easily separated. To overcome this problem, in the same work, the authors suggest using an alternative objective for $G$ that is non-saturating, given as \begin{align} \mathcal{L}_G = \mathbb{E}_{x \sim \mathbb{P}_g}\left[-\log D(x) \right]\label{eqG2}, \end{align} for which the gradient is \begin{align} \nabla_x\mathcal{L}_G=\mathbb{E}_{x\sim \mathbb{P}_g}\left[-(1-D(x))\nabla_xf(x)\right]. \label{vanillagangrad} \end{align} In this case, note that when $D$ confidently rejects fakes (i.e., $D(G(z)) \approx 0$), they can still contribute to $\nabla_x\mathcal{L}_G$. For future convenience of notation, we use ``NSGAN" to refer to the non-saturating (NS) version of training a discriminator via a GAN, where $\mathcal{L}_D$ is given by Eq. \eqref{eqD1} and $\mathcal{L}_G$ is given by Eq. \eqref{eqG2}. Note that although $\mathcal{L}_G$ in Eq. \eqref{eqG2} is relatively non-saturating early in the training compared to Eq.\ \eqref{eqG1}, it may still saturate later in training as $\mathbb{P}_g$ gets closer to $\mathbb{P}_r$. Subsequently, the WGAN model \cite{arjovsky2017wasserstein} attempted to address two issues with the original GAN formulation. First, due to the use of the Jensen-Shannon divergence, disjoint support for $\mathbb{P}_g$ and $\mathbb{P}_r$ leads to poor gradients (as a confident $D$ rapidly saturates, leading to vanishing gradients). Second, for fixed $D$, the optimal $G$ samples a sum of Dirac deltas at points with the \textit{highest} value of $D(x)$, leading to gradients that encourage mode collapse \cite{metz2017}. Using an approximate Wasserstein distance in WGANs mitigates these issues. This WGAN objective for $G$ and critic $D$ may be written \begin{align} &\mathcal{L}_D = -\mathbb{E}_{x\sim\mathbb{P}_r}\left[ D(x) \right] + \mathbb{E}_{x\sim\mathbb{P}_g}\left[ D(x) \right]\label{wgand1},\\ &\mathcal{L}_G = - \mathbb{E}_{x\sim\mathbb{P}_g}\left[ D(x) \right]\label{wgang1}, \end{align} where $D(x)=f(x)$, and $f(x)$ is constrained to be 1-Lipschitz in $x$, denoted by $\|f\|_{\text{Lip}}=1$. We now have \begin{align} \nabla_x\mathcal{L}_G=\mathbb{E}_{x\sim \mathbb{P}_g}\left[-\nabla_xf(x)\right], \label{wgangrad} \end{align} which does not saturate, unlike NSGAN (Eq.\ \eqref{vanillagangrad}). Another commonly used variant of the critic loss $\mathcal{L}_D$ is the hinge loss \cite{lim2017geometric,miyato2018spectral}: \begin{align} \mathcal{L}_D = \mathbb{E}_{x\sim\mathbb{P}_r}&\left[ \text{ReLU}\left(1-D(x)\right) \right] +\nonumber \\&\mathbb{E}_{x\sim\mathbb{P}_g}\left[ \text{ReLU}\left(1 + D(x) \right) \right]\label{wgand2}, \end{align} where $\text{ReLU}(x)=\max\{0, x\}$ is the rectified linear unit. It is straightforward to define a smooth analogue of the hinge loss in Eq.\ \eqref{wgand2} by using a smooth approximation of ReLU defined as $ \text{SoftPlus}(x) = \log(1+e^x) $, which we refer to as the \textit{soft hinge loss}. For convenience of notation, we call $D$ a \textit{critic} with $D(x)=f(x)$, when $\mathcal{L}_D$ is any of the Wasserstein, hinge, or soft hinge loss, and a \textit{discriminator} with $D(x)=\sigma(f(x))$, when $\mathcal{L}_D$ is a variant of the cross-entropy loss (as in NSGANs). For GANs, several methods have been proposed to effectively constrain $D$, generally to 1-Lipschitz function spaces. WGAN uses weight clipping, which compromises optimization ease and capacity, while WGAN-GP imposes a soft gradient penalty to improve upon this (see \S\ref{relwork:stab} and \S\ref{relwork:gradpen}). More recently, SNGAN tries to impose a 1-Lipschitz constraint by enforcing unit spectral norm of every layer. In \S\ref{sec-comparisons}, we show that a composition of such constrained functions typically results in the overall Lipschitz constant being bounded loosely by 1, and discuss empirical results in \S\ref{sec-empirical-analysis}. While constraining $D$ to be 1-Lipschitz is necessary for training WGANs, Miyato \etal \cite{miyato2018spectral} empirically show that such a constraint is also beneficial when training NSGANs. One may immediately see why such smoothness constraints might help. Consider the norm of $\nabla_x\mathcal{L}_G$ for NSGANs (Eq. \eqref{vanillagangrad}) and WGANs (Eq. \eqref{wgangrad}) as follows \begin{align} \|\nabla_x\mathcal{L}_G \|_{\text{NSGAN}} &= \| \mathbb{E}_{x\sim \mathbb{P}_g}\left[-(1-D(x))\nabla_xf(x)\right] \| \nonumber\\ &\leq \mathbb{E}_{x\sim \mathbb{P}_g}\left[\|(1-D(x))\nabla_xf(x)\|\right]\nonumber \\ &\leq \mathbb{E}_{x\sim \mathbb{P}_g}\left[\|\nabla_xf(x)\|\right]\label{eq-vanillagan-gradbound}\\ \|\nabla_x\mathcal{L}_G \|_{\text{WGAN}} &= \| \mathbb{E}_{x\sim \mathbb{P}_g}\left[-\nabla_xf(x)\right] \nonumber\| \\ &\leq \mathbb{E}_{x\sim \mathbb{P}_g}\left[\|\nabla_xf(x)\|\right]\label{eq-wgan-gradbound}. \end{align} When $f$ is constrained to be $\mathcal{K}$-Lipschitz, clearly, $\|\nabla_x\mathcal{L}_G \|_{\text{NSGAN}}$ and $\|\nabla_x\mathcal{L}_G \|_{\text{WGAN}}$ are both bounded above by $\mathcal{K}$. This ensures that the gradients received by $G$ throughout the training are well-behaved and do not explode, thereby improving training stability. In this paper, we introduce an alternative way to strictly bound the gradients by enforcing a piecewise $\mathcal{K}$-Lipschitz continuity almost everywhere (as opposed to a global $\mathcal{K}$-Lipschitz constraint). In a similar spirit to Miyato \etal \cite{miyato2018spectral}, we empirically show that our method benefits both discriminators and critics. In the next section, we introduce a notation for the class of functions implemented by deep neural networks with piecewise linear activations, and subsequently, in \S\ref{grand}, we present gradient normalization for discriminators and critics. \subsection{Deep piecewise linear networks} \label{sec-pieces} Modern deep neural networks predominantly use piecewise linear activation functions such as ReLU and LeakyReLU. Such activation functions do not admit regions with saturation, and, hence, allow training very deep networks effectively without vanishing gradients. Let $f(x):\mathbb{R}^{d}\rightarrow\mathbb{R}$ represent a (deterministic) deep neural network with piecewise linear activation functions. Denote the network parameters by $\theta$. Then one may write \begin{align} f(x,\theta) = w(x, \theta) \cdot x + b(x, \theta), \label{piecewise1} \end{align} where $w(x, \theta)$ and $b(x, \theta)$ are piecewise constant in $x$. We denote $w(x, \theta) \cdot x$ as the scalar dot-product of flattened tensors. Thus, $w(x, \theta)$ and $b(x, \theta)$ being piecewise constant in $x$ means that $\exists$ input sub-sets $S_k \in \left\{S_j\right\}_j \subseteq \mathbb{R}^{d}$, where \begin{align} w(x\in S_k, \theta) &= w_k(\theta) \,~\text{and}~\, % b(x\in S_k, \theta) = b_k(\theta), \nonumber \end{align} such that $w_k$ and $b_k$ are independent of $x$ within the sub-set $S_k$. Hence, $\forall x \in S_k$, we have \begin{align} f(x\in S_k, \theta) = w_k(\theta) \cdot x + b_k(\theta), \label{plane1} \end{align} which is linear in $x\in S_k$. Then $f(x,\theta)$ is the composition of continuous, piecewise linear functions, and is therefore itself a continuous and piecewise linear function of $x$. That is, there exist disjoint open input subsets $S_k$, such that $\cup_{k=1}^K S_k = \mathbb{R}^{d}$, where Eq.\ \ref{plane1} holds. I.e., $f(x, \theta)$ is a linear function of $x\in S_k$, with coefficients $w_k$ and $b_k$ that only depend on $\theta$. One can interpret $w_k(\theta)$ and $b_k(\theta)$ as the \textit{effective} weights and bias of a linear functional (given by Eq.\ \eqref{plane1}) that equals the predictions of the deep neural network, $f(x)$, $\forall ~ x \in S_k$. Note that, unlike a linear hyperplane in logistic regression, the effective weights $w_k(\theta)$ and bias $b_k(\theta)$ are only applicable for $x \in S_k$. Given this structure, for points off of $\partial S_k$ (the boundary of $S_k$), the gradient takes a simple form: \begin{align} \nabla_xf(x, \theta) = w_k(\theta), \label{piecegradienteq} \end{align} which is a constant vector $\forall ~ x \in S_k$. \section{Gradient Normalization} \label{grand} In this section, we present \textit{gradient normalization} (GraN), which strictly constrains piecewise linear networks to be 1-Lipschitz almost everywhere. As in \S\ref{sec-pieces}, let $f(x):\mathbb{R}^{d}\rightarrow\mathbb{R}$ represent a piecewise linear neural network with parameters $\theta$. We then define the gradient normalized function $g(x)$ as % \begin{align} g(x) = f(x) ~ \mathcal{R}_\epsilon(\| \nabla_xf(x)\|) = \frac{f(x)~ \| \nabla_xf(x)\|}{\| \nabla_xf(x) \|^2 + \epsilon}, \end{align} where $\epsilon>0$ is a fixed constant for numerical stability and $\mathcal{R}_\epsilon(n)=n/(n^2 + \epsilon)$ is the normalization factor, with $n=\| \nabla_xf(x)\|$. Any bounded $R(n)$, with $R(n) = (1/n)(1 + o(1))$ as $n \rightarrow \infty$, could be tried. We briefly experimented with $R(n) = 1/(n + \epsilon)$, which produced similar although slightly worse results than $ \mathcal{R}_\epsilon $. The choice of $R(n)$ could benefit from further study. We remark that a concurrent work \cite{Wu_2021_ICCV} to ours independently explores a similar technique to regularize $D$, but with a different normalization factor. Given this normalization, if $f$ is an arbitrary piecewise linear function then $g$ is piecewise linear such that $ % \|\nabla_xg(x)\| \leq 1 $ % analytically almost everywhere in $x\in \mathbb{R}^{d}$. While the gradient $\nabla_xg(x)$ is bounded, $g(x)$ itself can still take real values with no bounds, i.e., $g(x)\in \mathbb{R}$. One can better describe this result with the notation developed in \S\ref{sec-pieces}. Consider an arbitrary input $x \in S_k$ (without any loss of generality) that belongs to the input open subset $S_k$ and is mapped by the network to a linear piece given by $f(x) = w_k(\theta) \cdot x + b_k(\theta)$ $\forall ~ x \in S_k$. Then one has $\nabla_xf(x, \theta) = w_k(\theta)$ $\forall ~ x \in S_k$ (Eq. \eqref{piecegradienteq}). Therefore, the GraNed function $g(x)$, given $f(x)$, for $x\in S_k$ becomes \begin{align} g(x\in S_k) = \left[w_k(\theta) \cdot x + b_k(\theta)\right] ~\frac{\|w_k(\theta) \|}{\|w_k(\theta) \|^2 + \epsilon}. \end{align} Consequently, $\nabla_x g$ and its norm can be written as \begin{align} \nabla_x g(x\in S_k) = w_k(\theta) ~ \frac{\|w_k(\theta) \|}{\|w_k(\theta) \|^2 + \epsilon},\\ \implies \| \nabla_x g(x\in S_k)\| = \frac{\|w_k(\theta) \|^2}{\|w_k(\theta) \|^2 + \epsilon} < 1. \label{eq:nrmBnd} \end{align} Since $x$ and $S_k$ were arbitrarily chosen, it follows that $\| \nabla_x g(x)\| < 1$ except at the boundaries, say $x \in \partial S_k$, where the gradient does not exist. Since $\cup_k \partial S_k$ is measure zero, we have $\| \nabla_x g(x)\| < 1$ almost everywhere in $\mathbb{R}^{d}$. Further, for $\|w_k(\theta) \| \gg \epsilon$, we have $||\nabla_x g|| \approx 1$ in $S_k$. Note that, since the original piecewise linear function $f(x)$ does not have a smooth gradient $\nabla_x f(x)$, the normalization factor $\mathcal{R}_\epsilon(\| \nabla_x f(x) \|)$ will have discontinuities for $x \in \cup_k \partial S_k$. Therefore, $g$ is typically discontinuous and not guaranteed to be globally 1-Lipschitz. However, we empirically find that $g(x)$ has bounded finite-differences over substantial perturbations (see \S\ref{sec-empirical-analysis}). Due to this piecewise constant gradient property (with unit-bounded norm), we remark that $g$ is \textit{piecewise 1-Lipschitz}, since $g$ is 1-Lipschitz with respect to any pair of points within each subset $S_k$. It is also \textit{locally} 1-Lipschitz continuous almost everywhere, since there exists an open ball around every point $x \in \cup_k S_k$, within which 1-Lipschitz continuity holds. Empirically, we find that the tight bound on $\| \nabla_x g(x) \|$ almost everywhere assists with GAN training. \subsection{Gradient Normalized GANs} \label{granddiscsec} Given a deep neural network represented by $f(x)$, we write $D(x)=\sigma(f(x))$ when $D$ represents discriminators, and $D(x)=f(x)$, when $D$ represents critics, respectively, where $\sigma(\cdot)$ is the sigmoid function (see \S\ref{sec-background-gans}). When $f(x)$ is piecewise linear in $x$, we define the gradient normalized discriminator (GraND) and critic (GraNC) as $D(x)=\sigma(g(x))$ and $D(x)=g(x)$, respectively, where \begin{align} g(x) = \frac{f(x)}{\tau} ~ \frac{\| \nabla_xf(x)\|}{\| \nabla_xf(x) \|^2 + \epsilon},\label{eq:grandgx} \end{align} and $\tau$ is a positive constant that constrains $g$ to be $\mathcal{K}$-Lipschitz, with $\mathcal{K}=1/\tau$. For GraNDs, $\tau$ takes a role analogous to the temperature of a sigmoid, and, hence, we term it as the ``temperature" hyperparameter. Like spectral normalization \cite{miyato2018spectral}, the Lipschitz constant $\mathcal{K}=1/\tau$ is the only additional hyperparameter that needs to be tuned for our method. Moreover, in practice, our method achieves a tight bound on the Lipschitz constant, unlike spectral normalization, which imposes a loose upper bound with $\|g\|_{\text{Lip}}\leq\mathcal{K}$. See \S\ref{sec-comparisons} for details. Finally, note that since the gradients in Eqs.\ \eqref{eq-vanillagan-gradbound} and \eqref{eq-wgan-gradbound} are computed by back-propagation, the step discontinuities in $g(x)$ are ignored. Therefore, for GANs with GraNDs and GraNCs, the generator $G$ receives gradients that are always bounded, i.e., $\|\nabla_x \mathcal{L}_G \| \leq \mathcal{K}$. \section{Comparison to Layer-wise Norms} % \label{sec-comparisons} \textbf{Spectral Normalization}~% As noted in \S\ref{relwork:gradpen}, GPs softly encourage Lipschitz continuity in a data-dependent manner. Improving on this, the spectrally normalized GAN (SNGAN) \cite{miyato2018spectral} achieves it at the architectural level. In particular, a linear layer $\ell(x) = Wx$ (ignoring the bias term) with weights $W$ is normalized via $ % \widetilde{W} = { W } / { ||W||_2 }, $ % before being applied to an input ($\widetilde{\ell}(x) = \widetilde{W}x$), where $ ||W||_2 = \sigma_{1}(W) $ is the spectral norm of $W$, equal to its largest singular value (SV) $\sigma_1$. This is a form of WN, but acts on the whole matrix rather than its individual rows. Notice that $|| \ell ||_\text{Lip} \leq \sigma_1(W) $ and $ \sigma_1(\widetilde{W}) = 1 $, so $ || \widetilde{\ell} ||_\text{Lip} \leq 1 $. As such, SN ensures layer-wise 1-Lipschitz continuity, and thus enforces it across the whole network, where SVs are estimated via power iteration.\footnote{Although note that, at each step, power iteration provides a \emph{lower bound} on $\sigma_1(W)$, and thus in practice it is possible that $|| \ell ||_\text{Lip} > 1$. } One downside of SN is the tendency to over-constrain the network, reducing capacity and attenuating gradients, due to the layer-wise enforcement mechanism \cite{anil2019sorting,li2019preventing}. SN guarantees a function is globally 1-Lipschitz by bounding the Lipschitz constant (LC) of every layer, as this then bounds their composition: $% || f \circ g ||_\text{Lip} \leq || f ||_\text{Lip} || g ||_\text{Lip}. $ % However, this upper-bound is often loose, over-constraining the network and attenuating gradients (expanded upon below). In comparison, GraN acts upon the network as a whole, leaving weights per layer free to vary, and ensuring that gradients with respect to the input are always of unit norm. \textbf{The Looseness of Layerwise Constraints}~~% For illustration, consider the simple case of two SNed linear layers without biases, ignoring non-linear activations (though, for instance, this occurs in the positive domain of ReLU): $ z = f(g(x))$, where $f(y) = By$ and $g(x) = Ax$. Assuming sufficient power iterations under SN, the largest singular values (SVs) of $A$ and $B$ are one, assigning each layer an LC of one. We next examine the conditions for which the composition of the layers, $f \circ g$, also has a LC of one. In this case, $z = f(g(x)) = B A x$, and so $f \circ g$ has a sharp LC of one if and only if the maximal SV of $BA$, namely $\sigma_1(BA)$, is also one. Let $\Gamma_\sigma(A)$ denote the span of the right singular vectors of $A$ with corresponding SVs equal to $\sigma$. We show in appendix \ref{appendixD}, that $\sigma_1(BA) = 1$ if and only if the \textit{first principal angle} \cite{golub2013matrix,zhu2012angles} between the subspaces $\Gamma_1(A^T)$ and $\Gamma_1(B)$ is zero. This only occurs if they intersect in at least one dimension. However, if \textit{even one} SV of $A$ and $B$ is less than one, then $\Gamma_1(A^T)$ and $\Gamma_1(B)$ will be measure zero, meaning the network must solve a high dimensional ``alignment'' problem of two measure zero sets. The only scenario avoiding this is when every SV of either $A$ or $B$ are one, which is also a measure zero event. Importantly, since the SN framework does not directly encourage these subspaces to align, or all the SVs of the weight matrices to be one, in practice it is likely that $\sigma_1 (B A) < 1$. This issue is exacerbated for deeper networks, as the overall LC equals the product of $\sigma_1 (B A)$ for every adjacent pair of layers. In addition, though training may encourage the network to utilize its capacity by avoiding small SVs, empirically it struggles to do so \cite{anil2019sorting}. In contrast, GraN not only guarantees the function is locally 1-Lipschitz, but does so without constraining individual layers (avoiding subspace alignment issues) and enforces \textit{exactly} unit gradient almost everywhere as well (% attaining the sharp LC bound within every $S_k$). Fig.\ \ref{fig:gradnorms} displays this exactness for GraN; note that SNGAN, due its residual architecture, actually has an LC of 1024, showcasing the looseness of the bound. \begin{table}[t] \caption{\label{tab:settings} Hyperparameters tested in Fig.\ \ref{fig:lrsbetascores} for GraND-GAN, SNGAN, and WGAN-GP on CIFAR-10, where $\alpha$ is the learning rate, $\beta_1$ and $\beta_2$ parametrize Adam in Eq. \eqref{eq:adam}, and $n_{\rm dis}$ is the number of discriminator steps per generator step. } \vspace{1mm} \centering \small{ \begin{tabular}{lrrrr} \toprule \textbf{Setting} & $\alpha$ (LR) & $\beta_1$ & $\beta_2$ & $n_{\rm dis}$\\ \midrule A & 0.0001 & 0.5 & 0.9 & 5\\ B & 0.0002 & 0.5 & 0.999 & 1\\ C & 0.001 & 0.5 & 0.999 & 5\\ D & 0.001 & 0.9 & 0.999 & 5\\ E (default) & 0.0002 & 0.0 & 0.9 & 5 \\ \bottomrule \end{tabular} } \end{table} \begin{figure} \centering \begin{subfigure}[b]{0.15\textwidth} \includegraphics[width=\textwidth]{inception_scores_beta_Lrs.pdf} \caption{\label{fig:incpscores_cifar10} IS~$\uparrow$} \end{subfigure}% \begin{subfigure}[b]{0.15\textwidth} \includegraphics[width=1.0\textwidth]{FID_beta_Lrs.pdf} \caption{\label{fig:fid_cifar10} FID~$\downarrow$} \end{subfigure} \begin{subfigure}[b]{0.15\textwidth} \includegraphics[width=1.0\textwidth]{KID_beta_Lrs.pdf} \caption{\label{fig:kid_cifar10} KID~$\downarrow$} \end{subfigure} \caption{\label{fig:lrsbetascores} Inception scores (IS), FIDs, and KIDs on CIFAR-10 image generation across different hyperparameters listed in Table \ref{tab:settings} for GraND-GAN, WGAN-GP, and SNGAN. Results show superior robustness for GraND. % } \end{figure} \begin{figure} \centering \includegraphics[width=0.5\textwidth]{gradnorm_boxplt_50K.pdf} \caption{\label{fig:gradnorms} Boxplots of gradient norms at real (blue) and fake (red) samples for different methods at 50K iterations (out of 100K) on CIFAR-10 during training. Gradient norms for GraND/C have a very narrow distribution (spanning less than $\pm 10^{-6}$) around the piecewise Lipschitz constant $\mathcal{K}$=0.83. % } \end{figure} \section{Experiments} \textbf{Model Architectures and Training}~% We evaluate our method on unconditional image generation across datasets of various sizes: CIFAR-10/100 ($32\times32$) \cite{Krizhevsky09learningmultiple}, STL-10 ($48\times48$) \cite{coates2011analysis}, LSUN bedrooms ($128\times128$) \cite{yu15lsun}, and CelebA ($128\times128$) \cite{liu2015faceattributes}. We use Mimicry \cite{lee2020mimicry} with PyTorch \cite{NEURIPS2019_9015} on a single NVIDIA V100 GPU for training our models. The generator $G$ and discriminator (or critic) $D$ architectures are identical across methods for a given dataset with identical number of learnable parameters for fair comparison. We use the Adam \cite{kingma2014adam} optimizer with $\beta_1=0.0$, $\beta_2=0.9$, and a batch size of $64$ for $100\text{K}$ iterations, with a dataset-dependent learning rate (LR) $\alpha$ and number of $D$ steps per $G$ step $n_{\rm dis}$. NSGANs and GraND-GAN use the cross-entropy loss for $D$ in Eq.\ \eqref{eqD1} and the non-saturating loss for $G$ in Eq. \eqref{eqG2}. GraNC-GAN uses a soft version of the hinge loss for $D$ in Eq. \eqref{wgand2}, replacing ReLU with softplus, and Eq.\ \eqref{wgang1} for $G$ (see \S\ref{sec-background-gans}). % The soft hinge loss was found to be more performant and stable than the (hard) hinge loss with GraNC-GANs: on LSUN, GraNC diverged with the hard hinge loss, while on CelebA, a lower FID was obtained. See appendix for further model details, ablation experiments, and hyperparameter choices. \looseness=-1 \textbf{Lipschitz Constant Analysis}~~% We find that tuning the Lipschitz constant $\mathcal{K}$ significantly affects the performance and stability of models when using the Adam optimizer. This is due to the interdependence of $\epsilon_{\text{Adam}}$ in the update with $\mathcal{K}$: \begin{equation} \delta \mathbf{\theta} = - \frac{\langle \mathbf{g} \rangle_{\beta_1}}{\sqrt{\langle\mathbf{g}^2\rangle_{\beta_2}} + \epsilon_{\text{Adam}}}. \label{eq:adam} \end{equation} Changing $\mathcal{K}$ from its default value of one has an effect of scaling the gradients of the loss function $\mathbf{g}$ by $\mathcal{K}$. This in turn has an effect of scaling $\epsilon_{\text{Adam}} \longrightarrow \epsilon_{\text{Adam}}/\mathcal{K}$. Empirically, we find that the Adam update for individual parameters can go $\ll 10^{-7}$ in magnitude on the plateaus of the loss landscape where $\epsilon_{\text{Adam}}$ becomes significant. We find it helps having smaller $\mathcal{K}$ generally when training on larger image resolutions which has an effect of increasing $\epsilon_{\text{Adam}}$ from its default value of $1\times 10^{-8}$. Intuitively, a larger $\epsilon_{\text{Adam}}$ suppresses the Adam update when the loss gradient magnitudes are $\lesssim \epsilon_{\text{Adam}}$. Therefore, $\epsilon_{\text{Adam}}$ determines the extent of noisy Adam updates at plateaus of the loss landscape, and so may need tuning. More details on the choice of $\mathcal{K}$ are provided in the appendix. \looseness=-1 \textbf{Baselines and Evaluation}~~% To directly compare our normalization method GraN with gradient penalty (GP) and spectral normalization (SN), independent of the loss function, we train NSGAN with a gradient penalty $P_1$ loss (NSGAN-GP), and with SNed layers (NSGAN-SN). We also train NSGAN-GP$\dagger$ and NSGAN-SN$\dagger$, which correspond to models constrained with a tuned Lipschitz constant (instead of 1). WGAN-GP$\dagger$ and SNGAN$\dagger$ are defined analogously. We quantitatively evaluate the methods by Inception Score (IS) \cite{salimans2016improved}, FID \cite{fid}, and KID \cite{binkowski2018demystifying} with 50K synthetic images randomly sampled from $G$ and 50K real images from the dataset. IS is not used for LSUN and CelebA, as these comprise a single class, for which IS performs poorly \cite{lee2020mimicry}. See appendix \ref{appendixA} for additional details. \textbf{Unconditional Image Generation}~~% Table \ref{tab:cifar10-100-results} presents the comparative results on CIFAR-10, CIFAR-100, and STL-10 image generation. Our methods rank among the top two across every metric (KID, FID, IS) on CIFAR-10 and CIFAR-100. On STL-10, our two methods rank the highest in IS and FID, however, we fall behind on KID by a small margin compared to SNGAN and SNGAN$\dagger$.\looseness=-1 Table \ref{tab:lsunceleba-results} summarizes our results on LSUN bedrooms and CelebA image generation. The NSGAN model did not converge (i.e., FID $> 70$) in two random restarts of training for both LSUN and CelebA. Similarly, WGAN-GP failed to converge on CelebA in two runs. GraND-GAN achieves the best results on CelebA, and the second-best on LSUN bedrooms, falling slightly behind NSGAN-GP$\dagger$. Among critics, GraNC-GAN performs best by FID as well. \begin{table*}[t] \centering \caption{\label{tab:cifar10-100-results}Inception scores (IS), FIDs, and KIDs with unsupervised image generation on CIFAR-10, CIFAR-100, and STL-10. The best and the second best models per evaluation metric and GAN family (i.e., with discriminators or critics) are indicated by \boldred{bold red} and \boldblue{bold blue} fonts. $\dagger$ indicates modified baselines with an altered Lipschitz constant $\mathcal{K}$. The table is split comparing discriminators (top) and critics (bottom). We write ``\textbf{--}" for cases where a model did not achieve a FID $< 70$. }\vspace{-2mm} \resizebox{\textwidth}{!}{ \begin{tabular}[t]{lrrrrrrrrrr} \toprule \multirow{2}{*}{Method} & \multicolumn{3}{c}{\textbf{IS}~$\uparrow$} & \multicolumn{3}{c}{\textbf{FID}~$\downarrow$} & \multicolumn{3}{c}{\textbf{KID} (${\times}1000$) ~$\downarrow$} \\ & CIFAR-10 & CIFAR-100 & STL-10 & CIFAR-10 & CIFAR-100 & STL-10 & CIFAR-10 & CIFAR-100 & STL-10\\ \midrule NSGAN & {7.655} & {6.611} & {7.920} & {23.750} & {30.842} & {44.179} & {14.5} & {20.5} & {40.0} \\ NSGAN-GP & {8.016} & \textbf{--} & {8.568} & \boldblue{15.813} & \textbf{--} & {38.848} & \boldblue{12.9} & \textbf{--} & {38.9} \\ NSGAN-SN & {7.792} & {7.258} & {8.167} & {20.998} & {25.564} & \boldblue{38.669} & {15.7} & {18.4} & \boldblue{35.7} \\ NSGAN-GP$\dagger$ & \boldblue{8.019} & \boldblue{7.892} & \boldblue{8.623} & {15.911} & \boldblue{20.894} & {40.110} & {13.1} & \boldblue{17.0} & {39.8} \\ NSGAN-SN$\dagger$ & {7.814} & {7.526} & {8.135} & {20.323} & {24.200} & {39.013} & {15.3} & {17.7} & {36.7} \\ GraND-GAN (Ours) & \boldred{8.031} & \boldred{8.314} & \boldred{8.743} & \boldred{14.965} & \boldred{18.978} & \boldred{35.226} & \boldred{12.3} & \boldred{13.7} & \boldred{35.0} \\ \midrule \midrule WGAN-GP & {7.442} & {7.520} & {8.492} & {22.927} & {27.231} & {42.170} & {21.1} & {23.5} & {43.0} \\ SNGAN & \boldred{8.112} & {7.778} & {8.385} & {17.107} & {20.739} & {38.218} & \boldblue{12.6} & \boldred{14.3} & \boldblue{34.3} \\ WGAN-GP$\dagger$ & {7.344} & {7.684} & {8.466} & {22.705} & {25.211} & {42.595} & {20.6} & {21.2} & {44.7} \\ SNGAN$\dagger$ & \boldblue{7.991} & \boldblue{7.959} & \boldblue{8.552} & \boldblue{16.740} & \boldblue{20.104} & \boldblue{36.203} & \boldred{12.0} & \boldred{14.3} & \boldred{33.3} \\ GraNC-GAN (Ours) & {7.966} & \boldred{8.208} & \boldred{8.957} & \boldred{16.361} & \boldred{19.131} & \boldred{35.770} & {13.7} & \boldblue{14.8} & {35.4} \\ \bottomrule \end{tabular} } \end{table*} \begin{table}[t] \centering \caption{\label{tab:lsunceleba-results} Unsupervised $128\times128$ image generation on LSUN-Bedrooms and CelebA. We write ``\textbf{--}" to indicate the cases where a model did not achieve a FID $< 70$ in two random training restarts. The best and the second best models per evaluation metric and GAN family (i.e., with discriminators or critics) are indicated by \boldred{bold red} and \boldblue{bold blue} fonts. $\dagger$ indicates modified baselines with an altered Lipschitz constant $\mathcal{K}$. We split the table into discriminators (top) and critics (bottom), to better highlight the differences per loss function. GraN performs best or second-best across all datasets, losses, and performance metrics; in the case of discriminators, GraND-GAN and NSGAN-GP$\dagger$ (our Lipschitz-tuned GP-based approach) are the top two performers. }\vspace{1mm} \resizebox{0.47\textwidth}{!}{ \begin{tabular}[]{lrrrrrrr} \toprule \multirow{2}{*}{Method} & \multicolumn{2}{c}{\textbf{FID}~$\downarrow$} & \multicolumn{2}{c}{\textbf{KID (${\times}1000)$}~$\downarrow$} \\ & LSUN & CelebA & LSUN & CelebA\\ \midrule NSGAN & \textbf{--} & \textbf{--} & \textbf{--} & \textbf{--} \\ % NSGAN-GP & \textbf{--} & \textbf{--} & \textbf{--} & \textbf{--} \\ NSGAN-SN & {74.926} & {14.33} & {44.8} & {21.2} \\ NSGAN-GP$\dagger$ & \boldred{10.483} & \boldblue{9.385} & \boldred{7.2} & \boldblue{5.8} \\ NSGAN-SN$\dagger$ & {12.635} & {9.644} & {8.3} & \boldblue{5.8} \\ GraND-GAN (Ours) & \boldblue{10.795} & \boldred{9.377} & \boldblue{7.3} & \boldred{5.2} \\ \midrule \midrule WGAN-GP & {13.562} & \textbf{--} & {9.8} & \textbf{--} \\ % SNGAN & \boldblue{13.237} & \boldblue{13.466} & \boldred{8.0} & {8.9} \\ WGAN-GP$\dagger$ & {16.884} & \textbf{--} & {12.0} & \textbf{--} \\ SNGAN$\dagger$ & {67.346} & {15.874} & {32.0} & \boldblue{8.7}\\ GraNC-GAN (Ours) & \boldred{12.533} & \boldred{12.000} & \boldblue{9.1} & \boldred{8.1} \\ \bottomrule \end{tabular} } \end{table} Figure \ref{fig:lrsbetascores} presents a comparison of GraND-GAN with WGAN-GP and SNGAN on CIFAR-10 image generation across various training settings listed in Table \ref{tab:settings}. For setting B ($n_{\rm dis}$ = 1), our method retains a respectable FID score (and other metrics) compared to SNGAN and WGAN-GP. For settings C and D with larger learning rates and momentum hyperparameters, the performance of WGAN-GP degrades while our method and SNGAN remain quite robust. \begin{figure} \centering \begin{subfigure}[b]{0.23\textwidth} \includegraphics[width=1.0\textwidth]{FDgradnorm_box_WGANGP_baseline_50k.pdf} \caption{\label{fig:fid_cifar10:w} WGAN-GP} \end{subfigure} \begin{subfigure}[b]{0.215\textwidth} \includegraphics[width=1.0\textwidth]{FDgradnorm_box_SNGAN_baseline_50K.pdf} \caption{\label{fig:fid_cifar10:s} SNGAN} \end{subfigure} \begin{subfigure}[b]{0.22\textwidth} \includegraphics[width=1.0\textwidth]{FDgradnorm_box_GrandNSGAN_50k.pdf} \caption{\label{fig:fid_cifar10:gd} GraND-GAN} \end{subfigure} \begin{subfigure}[b]{0.22\textwidth} \includegraphics[width=1.0\textwidth]{FDgradnorm_box_GrandWGAN_50K.pdf} \caption{\label{fig:fid_cifar10:gc} GraNC-GAN} \end{subfigure} \caption{\label{fig:fdgradnorms} Boxplots of estimated finite-difference gradient norm with increasing $L2$ perturbation strengths $\delta$ around the real (blue) and fake samples (red) on CIFAR-10 at 50K iterations (out of 100K) for different methods. Empirically, GraND/C is fairly Lipschitz bounded across polytopes globally, close to the piecewise Lipschitz constant of $\mathcal{K}=0.83$. } \end{figure} \section{Gradient Normalization Empirical Analysis} \label{sec-empirical-analysis} In this section, we empirically analyze the effect of gradient normalization on (a) the gradient norms and (b) the finite-difference approximation to the gradient norm at increasing levels of perturbation $\delta$, and compare it with spectral normalization and gradient penalty. Figure \ref{fig:gradnorms} shows a boxplot of $\|\nabla_xf(x)\|$ for the baselines, and $\|\nabla_xg(x)\|$ for our methods, on a CIFAR-10 image generation task at 50K iterations (out of 100K), where $f(x)$ is the piecewise linear discriminator (or critic) network and $g(x)$ is its gradient normalized version. The gradient norms $\| \nabla_xf(x)\|$ for NSGAN with an unconstrained discriminator are substantially larger. For WGAN-GP and SNGAN, $\|\nabla_xf(x)\|$ are bounded within a reasonable range. Gradient normalized discriminators and critics with a piecewise Lipschitz constant of $\mathcal{K}=0.83$, have a narrow distribution with a gradient norm that is $\approx\mathcal{K}$ ($\pm 10^{-6}$) across samples. % Unlike spectral normalization or gradient penalty, our method does not constrain the discriminator or critic to be globally $\mathcal{K}$-Lipschitz. We investigate this on a CIFAR-10 image generation task by first sampling fake data from $G$ at a given training iteration and real data from the dataset. We estimate $\Delta_i = \| h(x_i + \delta n_i) - h(x_i)\|/\delta$ for each of the samples, which is the finite difference along a step of magnitude $\delta>0$ along the local gradient direction $n_i = \nabla h(x_i)/ \| \nabla h(x_i) \|$, where $h$ denotes $f$ for baselines and $g$ for our methods, respectively. This provides a probe for the LC (albeit a lower bound) similar in spirit to prior work \cite{zou2019lipschitz}. Figure \ref{fig:fdgradnorms} shows a boxplot of the resulting $\Delta_i$ for increasing perturbation magnitudes $\delta$. Evidently, gradient normalized discriminators and critics have well-behaved finite-differences, even for fairly large neighborhoods $\delta$, despite being only piecewise Lipschitz in theory. Moreover, the variance of the computed $\Delta_i$'s across $\delta$ for our methods is comparable to WGAN-GP. \section{Discussion} \textbf{Limitations}~~We observed instabilities when training gradient normalized critics with the Wasserstein loss (Eq.\ \eqref{wgand1}). The hinge loss (Eq.\ \eqref{wgand2}) improved this, but still struggled for larger images; the soft hinge approach was found to work better. However, training GraND with the NS loss (Eq.\ \eqref{eqD1}) was found to be more stable, especially on larger images. Also, on such images, our method periodically diverged late in training, an issue present for the baselines as well. \textbf{Future work}~~While GraN does not guarantee a global Lipschitz constraint due to discontinuities, it does enforce constant bounded-norm gradients almost everywhere (and thus piecewise Lipschitz continuity). Moreover, empirically, it is competitive with, or better than, existing baselines. Investigating global versus local Lipschitz continuity, as well as gradient regularization, is thus an enticing future direction. \textbf{Conclusion}~~We introduced a novel input-dependent normalization for piecewise linear critics and discriminators. Our method guarantees a bounded input gradient norm almost everywhere and is piecewise $\mathcal{K}$-Lipschitz. We empirically showed that our method improves unconditional image generation using GANs across a range of datasets. Finally, though our method does not explicitly impose a global $\mathcal{K}$-Lipschitz constraint, empirically, the finite-difference gradient norm is well-behaved in a large local neighbourhood. % {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2021-11-08T02:04:59', 'yymm': '2111', 'arxiv_id': '2111.03162', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03162'}
arxiv
\section*{Ethical Considerations} StyleCLIPDraw relies heavily on the feedback from the CLIP\cite{radford2021-clip} image-text encoding model. CLIP was trained on 400 million image-text pairs scraped from the internet, and this dataset is not made publicly available. As pointed out in the original CLIPDraw paper\cite{frans2021-clipdraw}, the biases in this data will be reflected in the generated images from the model. The biases of the CLIP model have been investigated\cite{radford2021-clip}, and it is important to recognize the presence of them when utilizing StyleCLIPDraw. \bibliographystyle{plain}
{'timestamp': '2021-11-08T02:03:45', 'yymm': '2111', 'arxiv_id': '2111.03133', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03133'}
arxiv
\section{Introduction}\label{S1} \IEEEPARstart{S}{ea} subsurface is the part of ocean below the sea surface. Its temperature plays an important role in ocean science research \cite{chen18_grsl}. Sea subsurface temperature is important information for understanding the global ocean ecosystem and earth climate system. The study of the spatial and temporal distribution of sea temperature and its variation law is not only a critical issue in marine geography, but also of considerable significance to fishery, navigation, and underwater acoustics. Diverse sources of external factors, such as radiation and diurnal wind, affect the sea subsurface temperature, and the prediction of the sea subsurface information is very challenging \cite{Mcphaden98}. Existing studies on sea subsurface temperature rely on numerical modeling and observational data \cite{tandeo09_grsl,meng20_grsl,wu12_grsl,hosoda12_grsl}. Numerical modeling is a widely used technique to tackle complex ocean problems by data simulation, based on the equations of ocean physical laws. Currently, Princeton Ocean Model (POM) \cite{Umlauf03_jmr}, HYbrid Coordinate Ocean Model (HYCOM) \cite{Chassignet07_jms}, and Finite-Volume Coastal Ocean Model (FVCOM) \cite{Chen06} are commonly used in oceanography. POM is a classic traditional ocean model with clear structure, concise model specifications, and thorough model physical interpretation. The flexible vertical hierarchical structure of HYCOM makes it more suitable for the significant expansion of the stratification effect. FVCOM model includes momentum equation, continuity equation, thermo-salt conservation equation and state equation. The numerical solution of FVCOM adopts the finite volume method (FVM), which has the advantages of accurate and fast calculation and good fitting of coastline boundary and seabed topography based on the unstructured mesh. This is because FVM can better guarantee the conservation of each physical quantity not only in each unit but also in the whole calculation area. All these numerical models are constructed based on our knowledge of ocean physics, and they are often applied to simulate ocean dynamics and predict sea subsurface temperature. However, their prediction accuracy can hardly be guaranteed, since there exist a large range of environmental factors that affect marine environments. In order to improve the prediction accuracy of the numerical models, assimilation methods are commonly used. Traditional assimilation methods can improve the model prediction performance by fusing new observational data in the dynamic running process of a numerical model. Smedstad and O’Brien \cite{smedstad} summarized the data assimilation methods developed before 1991 and classified them into polynomial interpolation methods, optimal interpolation methods, and variational analysis methods. Anderson \emph{et al.} \cite{anderson} also surveyed the data assimilation methods in Physical Oceanography. Although the prediction accuracy of the traditional assimilation methods is much higher than that of the numerical models, there are ample rooms that these methods can be further improved. In contrast to the physics-based numerical models, data-driven models, such as neural networks, rely purely on observational data to learn the underlying data distribution. However, it is unclear how these models produce specific decisions, and interpreting these data-driven models physically are very difficult. Since these methods only rely on training data, their generalization ability on unseen data is often limited, whereas most physics-based models do not utilize training data and therefore may perform well on unseen data, provided that the physical laws employed to build these models accurately represent the underlying data distribution. Nevertheless, the physical rules are often incomplete, and these numerical models need to be improved and supplemented. A fundamental principle in data modeling is to incorporate available \emph{a priori} information regarding the underlying data generating mechanism into the modeling process. Data-physics hybrid models capable of incorporating prior knowledge typically outperforms data-driven modeling \cite{HongChen2009,Chen_etal2011}. Motivated by this fundamental principle for data modeling, in this paper, we focus on developing a physics-guided framework for training neural network to predict sea subsurface temperature, which combines numerical modeling and observational data modeling. We demonstrate that this data-physics hybrid modeling approach can not only take advantage of our prior knowledge of ocean physical laws but also improve the overall prediction accuracy. In recent years, deep learning in computer vision \cite{Cheng18_tgrs,Mou17_tgrs,Zhang18_tgrs} and natural language processing \cite{Li16_nips,Sarikaya14_taslp,Korpusik19_taslp} has achieved breakthrough progress. Its underlying motivation is to simulate the human brain neural connection structures \cite{liu_hang_17_tgrs,sun19_grsl,henry18_grsl,ogut19_tgrs}. When handling high-dimensional data, high-level features are extracted through multiple layers progressively to identify the concepts relevant to human \cite{Chen16_tip,Wang20_tip,Perera19_tip}. Deep learning models can be roughly divided into two categories: discriminant models and generative models \cite{wang_liu_19_tgrs,wang_yuan_19_tgrs}. Discriminant models are trained to distinguish the correct output among possible output choices \cite{Yang19_tgrs,Sun20_tgrs}. On the other hand, generative models are trained to obtain better understandings of the data samples. Specifically, a generative model learns a distribution from the input samples, and then generates similar samples based on this distribution to enhance the model. Goodfellow {\it et al.} \cite{goodfellow14_nips} proposed the generative adversarial network (GAN), which uses adversarial training to train a generative network and a discriminative network jointly. The generative network captures the potential distribution of the real data, while the discriminative network is commonly a binary classifier which judges whether the input samples are real or not. Many GAN-based models have been proposed to solve the problem of high-quality image generation. Isola {\it et al.} \cite{Isola17_cvpr} proposed Pix2pix for image translation. In Pix2pix, a pair of image datasets from different domains are fed into the model during training, and an image can be transformed from one domain to the other. Zhu {\it et al.} \cite{Zhu17_cvpr} proposed CycleGAN to learn mappings between an input image and an output image when paired training data is unavailable. A cycle consistency loss is introduced to achieve this goal. \begin{figure}[tp!] \begin{center} \includegraphics[width=0.98\columnwidth,angle=0]{fig_1.pdf} \end{center} \vspace*{-4mm} \caption{Two-stage sea subsurface temperature prediction framework. In the first stage, generative adversarial training is performed on the model with the data from the physics-based numerical model. In the second stage, the model is fine-tuned with observational data.} \label{fig_1} \vspace*{-4mm} \end{figure} The deep neural network has strong predictive power but it does not follow the laws of physics. By contrast, a numerical model simulates the ocean dynamics, based on knowledge of ocean physics. Karpatne {\it et al.} \cite{Karpatne17_arxiv} blended the numerical model with multi-layer perceptron to correct lake temperature. In this work, the authors applied all the variables related to the lake temperature and the output of the numerical model for the lake temperature as the inputs to the neural network. If the numerical model accurately simulates the motion of the lake temperature, the output of their model is generated by the numerical model; otherwise the result is generated by the neural network. This approach basically chooses the result from either the physics-based numerical model or the neural network trained by observation data. Ideally, we would like to design a prediction method by combining both the physics-based numerical model and the data-driven model. Jia {\it et al.} \cite{jia_PGRNN} combined a recurrent neural network (RNN) model with the numerical model to predict the lake temperature. Their model was trained over the numerical model data and then fine-tuned on the limited observation data. However, their model was applied for each depth separately, and the data from the same depth is used to predict the lake temperature of the same depth. In addition, they only predicted the temperature value at one subsurface point, not over an entire area. We also note that most existing studies concentrate on the sea surface prediction, while there is a paucity of contributions on the daily sea subsurface temperature prediction. This will be further discussed in the related work section. \begin{figure*}[!bp] \vspace*{-5mm} \begin{center} \includegraphics[width=0.9\linewidth,angle=0]{fig_framework.pdf} \end{center} \vspace*{-7mm} \caption{The proposed GAN-based sea subsurface temperature prediction framework. \emph{Stage} 1: The generator learns the mapping from the sea surface temperature to the target depth temperature in the numerical model. The generator is composed of two components: one single shared network and several task-specific attention networks. The shared network learns the mapping from sea surface temperature and random noise to the numerical model data. The task-specific attention networks capture the mapping between the sea surface temperature and the sea subsurface temperature. \emph{Stage} 2: Fine-tuning the GAN model with observational data. The weights of the generator are shared with Stage 1, and the weights of the discriminator are fixed.} \label{fig_framework} \vspace*{-2mm} \end{figure*} In this paper, to tackle the above-mentioned limitations in the existing sea temperature analysis literature, we propose a new framework to predict the sea subsurface temperature by combining the physics-based numerical model with deep neural networks. In our method, we apply the physics-based numerical model to train the neural network model in the first phase, and then observational data is used to calibrate the model parameters in the second phase. More specifically, we design two neural networks in the proposed framework, as illustrated in Fig.~\ref{fig_1}. The first network learns the simplified physics laws from the numerical model. The weights of this first network are shared by the second network. This effectively encodes the knowledge of ocean physics into this second network model, and its weights are then fine-tuned by observational data. It can be seen that the merits of both physics-based numerical modeling and observational data modeling approaches are combined and, consequently, the prediction accuracy is further enhanced. The main contributions of this paper are summarized as follows. \begin{itemize} \item A novel GAN-based framework is proposed which predicts the daily sea subsurface temperature by learning the relationship between sea surface temperature and subsurface temperature. \item We explore the use of GAN combined with the physics-based numerical model for building a hybrid prediction model incorporating more effectively the known ocean physics with the observational data information. \item We propose a physics-based loss with a mask as prior knowledge. The mask filters out land locations and this loss automatically encodes the knowledge of ocean physics into the modeling process, leading to prediction performance improvement. \end{itemize} The rest of the paper is organized as follows. Section~\ref{S2} presents the background of GAN models and sea temperature prediction. Section~\ref{S3} details the proposed framework for sea subsurface temperature prediction. The experimental results are reported in Section~\ref{S4}. We draw concluding remarks and discuss the future work in Section~\ref{S5}. \section{Related Works}\label{S2} \subsection{Generative Adversarial Networks}\label{S2.1} Inspired by the binary zero-sum game, Goodfellow {\it et al.} \cite{goodfellow14_nips} proposed GAN in which two neural networks contest each other in a game. More specifically, GAN is composed of two networks: a generative network $G$ and a discriminative network $D$. The generator $G$ iteratively learns the distribution of the real input samples, and it generates samples following the learnt distribution. The generated fake samples are then fed into the discriminator $D$, and $D$ is trained to judge whether the input samples are real or fake. In the training process, the generator $G$ learns the input data distribution. During this learning process, fake samples can be identified by the discriminator $D$ from the real data distribution. In such an adversarial learning, the generator $G$ tries to `fool' the discriminator $D$ by producing samples as similar as possible to the real samples. With this mutual competitive reinforcement, the performances of both $G$ and $D$ are jointly enhanced. Conditional generative adversarial network (CGAN) \cite{mirza14} is an extension of GAN in which a conditional setting is applied. In CGAN, both the generator $G$ and discriminator $D$ are conditioned on class labels. As a result, the model can learn mappings from inputs to outputs by feeding it with contextual information. Yang {\it et al.} \cite{PI_SDE} solved the stochastic differential equations by encoding the known physical laws into the GAN. L{\"u}tjens {\it et al.} \cite{PI_CFV} used GAN to learn the latent features of the numerical model data in order to generate more realistic coastal floor data. Zheng {\it et al.} \cite{PI_SI} reconstructed the image based on its known pixels by employing a GAN model. These works used the GAN model to learn the latent features from the numerical model. Then they applied the pre-trained GAN model to do the corresponding tasks. In other words, these works used the GAN models to replace part or the entire numerical model. The works \cite{PI_SDE,PI_CFV,PI_SI} highlight the potential application of the GAN model in physical-relevant tasks. However, the difference of these works with our hybrid physics-data based GAN is huge. Not only we pre-train the GAN with the physics-based numerical model but also we adopt the observational data to calibrate the pre-trained GAN model. In other words, our GAN model not only learns the physical laws from the numerical model but also adapts itself using observational data. \subsection{Sea Subsurface Temperature Prediction}\label{S2.2} Temperature is an important factor in marine hydrology and climate change \cite{liu17_tgrs}. Existing studies based on satellite remote sensing data mainly focus on sea surface temperature and assessment. Yang {\it et al.} \cite{yang18_grsl} considers the task of sea temperature prediction as a sequence prediction problem and builds an end-to-end trainable long short-term memory (LSTM) neural network model. Then, the temporal and spatial features are combined to predict sea temperature. Wei {\it et al.} \cite{wei20_grsl} used Ice Analysis (OSTIA) data to train a neural network for South China Sea temperature prediction. Deep learning-based methods have also been utilized to predict the sea surface temperature in Bohai Sea and Indian Ocean \cite{zhang17_grsl,patil17_od,patil18_jaot}. \begin{figure*}[!tp] \vspace*{-2mm} \begin{center} \includegraphics[width=0.8\linewidth,angle=0]{Generator_architecture.pdf} \end{center} \vspace*{-6mm} \caption{Illustration of the generator architecture. The generator comprises of the U-NET architecture and the two sets of attention module. The attention module is connected with the output of the convolution block and the attention module from the last layer, which is passed one by one.} \label{fig_generator} \vspace*{-4mm} \end{figure*} The above mentioned studies mainly focus on temperature prediction of the sea surface. However, the sea subsurface temperature prediction research is scarce. Han {\it et al.} \cite{Conv_SST} applied the convolutional neural network (CNN) to predict the subsurface temperature from a sets of the remote sensing data. Lu {\it et al.} \cite{Cnn_SST} adopted the pre-clustered neural network method to estimate the subsurface temperature and the results are better than those obtained without clustering. Wu {\it et al.} \cite{Snn_SST} used the self-organizing map neural network to predict the subsurface temperature anomaly in the North Atlantic. These methods can reliably predict the monthly subsurface temperature using neural network owing to the fact that sufficient monthly observational data of the subsurface temperature are available for training neural network models. However, due to the very limited daily observation data, the prediction of the daily subsurface temperature cannot be carried out efficiently and accurately only using neural networks. Zhang {\it et al.} \cite{zhang19_grsl} used monthly Argo data to predict the sea subsurface temperature but no physics-based numerical model was utilized in this monthly sea subsurface temperature prediction model. These works indicate the lack of research on daily subsurface temperature prediction. In this paper, we combine deep neural networks and a physics-based numerical model into a unified framework, which is capable of predicting the daily sea subsurface temperature. \section{Proposed Framework}\label{S3} The proposed framework, depicted in Fig.~\ref{fig_framework}, composes of two stages: 1)~generative adversarial pre-training on numerical model data; and 2)~fine-tuning of the GAN model with observational data. In the first stage, the generator learns the mapping from the sea surface temperature to the target depth temperature using numerical model data. This effectively encodes the knowledge of ocean physics into the neural network model. In the second stage, real-world observation data are used to fine-tune the weights of the neural network model. This enables the model to learn the real-data distribution and to compensate for physics knowledge missing in the numeral model. We now detail these two stages. \subsection{Stage~1:~Generative Adversarial Training on Numerical Model Data}\label{S3.1} Numerical models play an important role in understanding the ocean's influence on global climate. They simulate the ocean properties and circulation based on the equations of ocean physics laws. Since numerical models approximate the physical correlations among different depths of the ocean, we use a GAN model in the proposed framework to acquire these relationships from the data generated by a numerical model. Without loss of generality, we consider predicting the subsurface temperatures at 50m, 100m and 150m underwater simultaneously. The prediction tasks of different depth temperatures can be achieved jointly by multi-task learning. In order to obtain good performance for each task, attention modules are used to enable both the task-shared and task-specific feature learning in an end-to-end manner \cite{liu_multitask}. The generator architecture is depicted in Fig.~\ref{fig_generator}, which is comprised of multiple sets of attention modules and the U-NET architecture. Each set of attention module can learn the features for individual tasks. Specifically, each attention module learns a soft attention mask, which is dependent on the features in the shared network. The features in the shared network and the soft attention masks can be trained jointly to optimize the generalization of the features across different tasks. As shown in Fig.~\ref{fig_attention_module}, the shared features after pooling are denoted as $p$, and the learnt attention mask in the layer for task $i$ is denoted as $a_i$. The task-specific features $\hat{a}_i$ are computed by element-wise multiplication of the attention mask with the shared features as $\hat{a}_i\! =\! a_i\! \odot\! p$, where $\odot$ denotes element-wise multiplication operator. The attention module has strong capabilities of emphasizing non-trivial features and weakening unimportant ones. Moreover, as the seawater temperature generally decreases with the increase of depth. we exploit this fact and set it as prior knowledge. If the seawater temperature in a lower layer is estimated higher than the one in an upper layer, the model is penalized. Hence we apply this physics-based loss to guide the fitting ability of the model between different depths\footnote{In some high latitude oceanic regions, seawater temperature at 50\,m can actually be higher than sea surface temperature. In this case, the physics-based loss should not be applied to this first underwater layer.}. \begin{figure}[tp!] \begin{center} \includegraphics[width=0.98\columnwidth,angle=0]{fig_attention_module.pdf} \end{center} \vspace*{-4mm} \caption{Illustration of the attention module.} \label{fig_attention_module} \vspace*{-4mm} \end{figure} As mentioned in Subsection~\ref{S2.1}, a GAN model is composed of two networks: the generative network $G$ and the discriminative network $D$. In our model, the generator contains two parts: one single shared network, and three task-specific attention networks. The shared network uses a conditional GAN model which learns a mapping from the observed image $x$ and random noise $z$ to real image $y$. The network objective is defined as follows: \begin{align}\label{eq1} L_{S_1}(G, D) =& E_{x,y}\log D(x,y) \nonumber \\ & + E_{x,z}\log(1-D(x, G(x,z))) , \end{align} where $E_{x,y}$ denotes the expectation operator with respect to $x$ and $y$, $D(x,y)$ distinguishes whether $x$ and $y$ are the true paired data, and $G(x,z)$ learns the mapping from the data $x$ and random vector $z$ to the real data $y$. As can be observed in Eq.\,(\ref{eq1}), in the shared network, the generator $G$ tries to minimize the objective while $D$ tries to maximize it. In the generator model, the input noise $z$ and conditional information $x$ jointly constitute the joint hidden layer representation in order to model the same distribution with domain $y$. To further improve the prediction performance, we mix the conditional GAN objective with a $L_1$ distance which is defined as \begin{equation}\label{eq2} L_{L_1}(G) = E_{x,y,z}\lVert G(x,z)-y \rVert_1. \end{equation} Besides the shared network, we build three task-specific attention networks, $G_{0\rightarrow50}$, $G_{0\rightarrow100}$ and $G_{0\rightarrow150}$, to capture the mappings between the sea surface temperature and the undersea temperatures at 50m, 100m and 150m, respectively. Correspondingly, the discriminative network can be decomposed into three sub-discriminative networks, namely, $D=\{D_{50},D_{100},D_{150}\}$. In our implementation, the sea surface temperature $x_0$ is obtained from the HYCOM data \cite{Chassignet07_jms}. Besides $x_0$, we generate three masks, $M_{0}$, $ M_{50}$ and $ M_{100}$. Starting from $M_0$, its value at a given location is set to 1 if the sea surface temperature is available from the numerical model at this location, and the value is set to 0 if the temperature is not exploitable, e.g., the location is on the land. This mask can filter out noise regions, such as the land. We further set the margin to 0.1. If the temperature of the deep layer is 0.1 degree higher than that of the shallow layer, the model is penalized. Specifically, we define an objective function $L_{0\sim50}(G)$ as follows: \begin{align}\label{eq3} & L_{0\sim50}(G) = \nonumber \\ & \hspace*{3mm} E_{x,z}\lVert\max\{(G_{0\rightarrow50}(x_{0},z) \odot M_{0}\! -\! x_{0}\odot M_{0}), 0.1\}\rVert_1.\! \end{align} The purpose of the mask $M_0$ can be seen clearly from the objective function $L_{0\sim50}(G)$. Only when the temperature at the 0\,m depth is exploitable, i.e., this location is not on land, the comparison between the temperature at the -50\,m depth and the temperature at the 0\,m depth is meaningful. Similarly, we have the mask $M_{50}$, whose value at a location is set to 0 if the numerical model data indicates that this 50\,m depth location is on the land; otherwise the temperature at this location is exploitable and we set $M_{50}=1$. Likewise, we can calculate $M_{100}$. Hence we can define the objectives $L_{50\sim100}(G)$ and $L_{100\sim150}(G)$ respectively as: \begin{align} L_{50\sim100}(G) =& E_{x,z}\lVert\max\{(G_{0\rightarrow100}(x_{0},z)\odot M_{50}- \nonumber \\ & \hspace*{7mm} G_{0\rightarrow50}(x_{0},z)\odot M_{50}), 0.1\}\rVert_1 , \label{eq4} \\ L_{100\sim150}(G) =& E_{x,z} \lVert\max\{( G_{0\rightarrow 150}(x_{0},z) \odot M_{100}- \nonumber \\ & \hspace*{7mm} G_{0\rightarrow100}(x_{0},z)\odot M_{100}), 0.1\}\rVert_1. \label{eq5} \end{align} Based on the above three objective functions, we propose the physics-based loss by using the three masks as prior knowledge, which leads to an improved prediction performance. Hence the physics-based loss in Stage 1 is defined as: \begin{align}\label{eq6} L_{P_1}(G) =& L_{0\sim50}(G) + L_{50\sim100}(G) + L_{100\sim150}(G). \end{align} It can be seen that this physics-based loss applies `shallower sea temperature' as masks (SL masks). Specifically, when comparing the temperature difference of a deeper layer and the shallower layer, the mask is referencing the shallower-layer sea temperature. It is natural to ask whether we can adopt `deeper sea temperature' as masks (DP masks). That is, when comparing the temperature difference of a deeper layer and the shallower layer, the mask is referencing the deeper layer sea temperature. Adopting DP masks in the proposed physics-based loss corresponds to replacing $M_0$ in the loss (\ref{eq3}) with $M_{50}$ and replacing $M_{50}$ in the loss (\ref{eq4}) with $M_{100}$ as well as calculating the mask $M_{150}$ and using it to replace $M_{100}$ in the loss (\ref{eq5}). This DP mask approach however is less effective than the SL mask approach. This is because the land area at the 0\,m depth is smaller than that at the -50\,m depth, and the land area at the -50\,m depth is smaller than that at the -100\,m depth, and so on. Therefore, the exploitable values of $M_0$ ($M_0=1$) or the size of $M_0$ is much larger than that of $M_{50}$, the size of $M_{50}$ is much larger than that of $M_{100}$, and the size of $M_{100}$ is much large than that of $M_{150}$. Hence, adopting the SL mask approach enables the model to exploit larger sea subsurface area. In the ablation study of Subsection~IV-C, we will demonstrate that better performance can be obtained by adopting the SL mask approach than the DP mask approach. By employing a physics-based loss, the generator can learn the mapping from the sea surface temperature to the temperature at 50m, 100m and 150m undersea from the numerical model simultaneously. According to the prior knowledge, the sea surface temperature should be higher than the one at 50m undersea, which should be higher than the temperature at 100m underwater and so on. If there is some irregular data, the penalty term will be added in the training process. According to the above discussion, the full objective function in the first stage of generative adversarial training using the physics-based numerical model data is expressed as \begin{equation}\label{eq7} L(G, D)=L_{S_1}(G, D) + L_{L_1}(G) + L_{P_1}(G). \end{equation} \begin{algorithm}[tp!] \caption{Stage I training procedure} \label{ALG1} \begin{algorithmic}[1] \Require HYCOM model training data $x$, $y$, random noise vector $z$, sea temperature masks $M_{0}$, $M_{50}$ and $M_{100}$, initial learning rate $l_1$, learning rate decaying factor $\eta$, numbers of critic iterations $n_1$, $n_2$ \Require Initial generator parameters $\theta_{g}$, initial discriminator parameters $\theta_d=\{\theta_{d}^i\}_{i\in\{50,100,150\}}$ \Ensure {Generator\,$G$\,and\,discriminator\,${D\! =\!\{D_{i}\}_{i\in\{50,100,150\}}}$} \While {not converged} \State Set learning rate to $l=l_1$; \For{$t=0,\cdots,n_1$} \State Sample image pair $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{y_{50}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{y_{100}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{y_{150}^{i}\}_{i=1}^{N}$; \State Update $D$ by gradient descent based on cost (\ref{eq1}); \State Update $G$ by gradient descent based on cost (\ref{eq7}); \EndFor \For{$t=n_1+1,\cdots,n_1+n_2$} \State Sample image pair $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{y_{50}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{y_{100}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{y_{150}^{i}\}_{i=1}^{N}$; \State Update $D$ by gradient descent based on cost (\ref{eq1}); \State Update $G$ by gradient descent based on cost (\ref{eq7}); \State Update learning rate $l=l_1-\eta(t-n_1)$; \EndFor \EndWhile \end{algorithmic} \end{algorithm} Algorithm~\ref{ALG1} implements the first stage of the training process in our proposed method. The weights of the discriminators and the generator are updated based on the costs (\ref{eq1}) and (\ref{eq7}) separately. In our implementation, the first $ n_1\! =\! 100$ epochs maintain a constant learning rate of $l_1\! =\!0.0002$, followed by another $n_2\! =\! 100$ epochs with a linearly decaying learning rate whose decaying factor $\eta$ satisfies $0 < \eta <\frac{l_1}{n_2}$. This setting is the same as the original Pix2Pix method \cite{Isola17_cvpr}. \subsection{Stage~2:~Fine-tuning GAN Model with Observation Data}\label{S3.2} Since numerical models rely heavily on simplified physics law, their results sometimes exhibit discrepancies from the observed data. Therefore, we utilized remotely sensing data, Argo data \cite{argo_data}, to correct numerical data errors. As illustrated in Fig.~\ref{fig_framework}, AVHRR Sea Surface Temperature (SST) data \cite{sst_data} is fed as the input of the model, while Argo data is employed as the real data. The generator shares the weights with the model from the first stage, while the weights of the discriminators are fixed. The generator in the second stage is composed of one single shared network and two task-specific attention networks. The objective function of the shared network is as follows: \begin{equation}\label{eq8} L_{S_2}(G) = E_{x,z}\log(1-D(x, G(x,z))) , \end{equation} where the discriminator $D$ does not update its weights, and only the generator updates its parameters through backpropagation. In this stage, the real data is Argo data. As Argo data contains the temperature information at single location, we cannot use Argo data to train the discriminator. Instead, we have to fix the discriminator in order to predict the temperatures on the entire area, not at a point location like Argo data. Since daily Argo data are point data, to predict values from the point to the entire plane, the discriminator pretrained in the first stage is used to measure the differences between the generated samples and the real data according to \begin{equation}\label{eq9} L_{dot}(G)=E_{x,z} \lVert G(x_{i,j},z)-\textrm{Argo}_{i,j} \rVert_1, \end{equation} where the index pairs $i$ and $j$ denote the locations of the temperature values from Argo data. Since daily Argo data only contain one temperature value, we employ $L_1$ distance to measure the temperature error between Argo data and the corresponding generated sample in (\ref{eq9}). By doing this, the adjustment from point to plane can be achieved. \begin{algorithm}[bp!] \caption{Stage II training procedure} \label{ALG2} \begin{algorithmic}[1] \Require Remote sensing satellite training data $x$, Argo training data $\text{Argo}_{50}$, $\text{Argo}_{100}$ and $\text{Argo}_{150}$, random noise vector $z$, sea temperature masks $M_{50}$ and $M_{100}$, initial learning rate $l_1$, learning rate decaying factor $\eta$, numbers of critic iterations $n_{1}$, $n_{2}$ \Require Generator parameters $\theta_{g}$ and discriminator parameters $\theta_d=\{\theta_{d}^i\}_{i\in\{50,100,150\}}$ \Ensure Generator $G$ \While {not converged} \State Set learning rate to $l=l_1$; \For{$t=0,\cdots,n_1$} \State Sample image pair $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{\text{Argo}_{50}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{\textbf{Argo}_{100}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{\text{Argo}_{150}^{i}\}_{i=1}^{N}$; \State Update $G$ by gradient descent based on cost (\ref{eq11}); \EndFor \For{$t=n_1+1,\cdots,n_1+n_{2}$} \State Sample image pair $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{\text{Argo}_{50}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{\text{Argo}_{100}^{i}\}_{i=1}^{N}$, $\{x_{0}^{i}\}_{i=1}^{N}$ and $\{\text{Argo}_{150}^{i}\}_{i=1}^{N}$; \State Update $G$ by gradient descent based on cost (\ref{eq11}); \State Update learning rate $l=l_1-\eta(t-n_1)$; \EndFor \EndWhile \end{algorithmic} \end{algorithm} It should be noted that in the second stage, two task-specific attention networks are employed. Due to the imprecision of AVHRR SST data, the temperature difference between the sea surface and 50m undersea is not taken into account. In the experiment section this will be fully explained. Therefore, the physics-based loss in Stage 2 is defined as: \begin{align}\label{eq10} L_{P_2}(G) = L_{50\sim100}(G) + L_{100\sim150}(G), \end{align} where $L_{50\sim100}(G)$ and $L_{100\sim150}(G)$ use the same configurations as the corresponding objective functions in the first stage. The full objective function employed in the second stage is therefore given by: \begin{equation}\label{eq11} L(G) = L_{S_2}(G) + L_{dot}(G) + L_{P_2}(G). \end{equation} Algorithm~\ref{ALG2} implements the second stage of the training process in our method. \section{Experiments}\label{S4} \subsection{Study Area and Data}\label{S4.1} The study was conducted on South China sea, a marginal sea in the western Pacific Ocean, located in the south of Mainland China. The sea has an area of about 3.5 million square kilometers, with an average depth of 1,212 meters and a maximum depth of 5,559 meters. A typical study area of (\ang{3.99}N$\sim$\ang{24.78}N, \ang{98.4}E$\sim$\ang{124.4}E) was selected. The numerical model data, satellite remote sensing data and Argo data from May 2007 to November 2017 were used for training. The remote sensing data from January 2004 to April 2007 were employed as the test input data. The Argo data from January 2004 to April 2007 were used as the true values for the comparison with the predictions, i.e., in the testing, the predicted results are compared with the Argo data. The numerical model data used in our experiments is HYCOM from \cite{hycom_data}. The HYCOM data format is NetCDF and its spatial resolution is 1/\ang{12}$\times$1/\ang{12}. The data is configured with 32 layers in the vertical direction. The National Oceanic and Atmospheric Administration (NOAA) optimum interpolation SST (OISST) data from \cite{sst_data} is used in this paper. The spatial resolution of the SST data is \ang{0.25} $\times$ \ang{0.25}, and daily mean data is employed in our study. The Argo data employed in our study is collected from \cite{argo_data}. The Argo data is composed of the data collected from different buoys placed at different locations in the South China sea. The daily Argo data is sea subsurface temperature data acquired at only one point in the whole sea area. As the Argo data are point data, we randomly choose one point from the predicted temperature results at the target locations to compare with the true value of the Argo data at the same locations. More specifically, the sea temperatures of the numerical model data at the depths of 0\,m, -50\,m, -100\,m and -150\,m are used for the first training stage. In the second training stage, we train the model over the satellite remote sensing data and the Argo data at the depths of -50\,m, -100\,m, -150\,m. The input data for the first stage is constructed in the format: [3856,\,128,\,128,\,1], where the first number is the size of the training dataset, the next two numbers are the height and the width of the input data, respectively, and the last number represents the grey-scale map with one color channel. Similarly, the format for the input data is [2020,\,128,\,128,\,1] in the second training stage, after removing the bad quality Argo data. In the test stage, the formats of the input data and the output data are [180,\,128,\,128,\,1] and [540,\,128,\,128,\,1], respectively, where the output data includes equal numbers of data samples for the sea subsurface temperature at 50\,m, 100\,m and 150\,m. \subsection{Baseline Models and Evaluation Metrics}\label{S4.2} To the best of our knowledge, this paper is the first to predict daily sea subsurface temperature by using methods other than numerical models. Due to the sparsity of the observational sea subsurface temperature data for training, it is not feasible to predict the temperature of a whole ocean area by solely relying on neural network. Therefore, in our experimental evaluation, we combine the neural network methods with the numerical model and the traditional data assimilation approach to perform study. Since there are only a few Argo devices in the entire China South Sea, daily sea temperature can only be obtained in a small set of data points in the entire region. Thus, our method adopts numerical model data to do predictions first due to limited observational data, as the numerical model can simulate ocean dynamics and obtain sea temperature in the entire region. Then we use the set of observational data to fine-tune the model. In the experiments, when we need to compare with other state-of-the-art methods, we also train the model with numerical model data using those methods and then observational data are applied for fine-tuning. The data generated by the numerical model assimilation method are obtained from \cite{hycom_data}. This HYCOM assimilation data has a spatial resolution of 1/\ang{12}$\times$1/\ang{12}, a temporal resolution of 1 day, a vertical resolution from the sea surface to 5000 meters undersea. It is much closer to the observational data compared than the HYCOM model data. We compare these data with our method in the following experiment part. Furthermore, the following neural network methods are selected as the baselines to compare with our model: Pix2pix \cite{Isola17_cvpr}, CycleGAN \cite{Zhu17_cvpr}, and PGNN \cite{Karpatne17_arxiv}. For Pix2pix and CycleGAN, we use the publicly available source codes provided by the authors, with the same default parameters. Specifically, for Pix2pix, $\lambda=100$ and $70\times 70$ PatchGAN are employed as mentioned in \cite{Isola17_cvpr}. For CycleGAN, an Adam solver \cite{kingma15_iclr} is employed with a learning rate of 0.0002. For PGNN, its output comes from either the neural network or the numerical model. However, having an output solely relying on a pure neural network is unsuitable for daily sea subsurface prediction over the whole sea area. Therefore, we cannot directly compare the PGNN with our method. Since PGNN uses a physics-based loss to guide the training of its neural network, in our experiments, we compare the physics-based loss obtained by PGNN with the physics-based loss obtained by our method. Additionally, we also compare our method with the methods of \cite{jia_PGRNN} and \cite{zhang19_grsl}. The two evaluation criteria, the root mean square error (RMSE) and the coefficient of determination ($R^2$) \cite{R2}, are used to assess the performance of the compared methods. \subsection{Experiment Design and Ablation Study}\label{S4.3} All our experiments are implemented on an NVIDIA GeForce 2080Ti GPU. Training iterations and learning rates are the same for the both phases of our approach. We train our model for $n_1\! +\! n_2\! =\! 200$ epochs. The first $n_1\! =\! 100$ epochs maintain a constant learning rate of $0.0002$, followed by another $n_2\! =\! 100$ epochs with a linearly decaying learning rate. The main network of the generator adopts a U-NET architecture \cite{UNET}, and each convolution is followed by an attention module. The discriminator applies the same six-layer convolutional network as in pix2pix \cite{Isola17_cvpr}. We construct the data as $128\times 128$ squared-shape heatmaps. Due to the inconsistency of Argo data underwater position, one-dimensional interpolation method was applied to obtain the data of 50 meters, 100 meters and 150 meters underwater. We use the Z-score standardization method to preprocess the data. \begin{table}[tp!] \caption{Study on the multi-task learning} \label{table_multi_task} \vspace*{-4mm} \begin{center} \begin{tabular}{|c||c|c|c|} \hline \multirow{2}{*}{Model} & \multicolumn{3}{c|}{RMSE ($^{\circ}$C)} \\ \cline{2-4} & ~~~~50m~~~~ & ~~~~100m~~~~ & ~~~~150m~~~~ \\ \hline\hline Model without TANs & 0.9532 & 1.3265 & 1.2475 \\ Model with TANs~~~ & 0.9435 & 1.3067 & 1.2439 \\ \hline \hline \multirow{2}{*}{Model} & \multicolumn{3}{c|}{$R^{2}$} \\ \cline{2-4} & 50m & 100m & 150m \\ \hline \hline Model without TANs & 0.5431 & 0.3129 & 0.5410 \\ Model with TANs~~~~ & 0.5437 & 0.3374 & 0.5514 \\ \hline \end{tabular} \end{center} \vspace*{-6mm} \end{table} We perform an extensive ablation study to demonstrate the effectiveness of the multi-task learning and physics-based loss. The influence of different margin values in physics-based loss is also studied. Moreover, the temperature difference between sea surface and 50m undersea is analyzed in detail. \subsubsection*{Effectiveness of Multi-task Learning} Multi-task learning exploits the correlation among different tasks to promote each other, and consequently the performance of the whole model is enhanced. We add multiple task-specific attention networks (TANs) to learn the mappings from the sea surface temperature to 50m, 100m, and 150m undersea simultaneously. Table~\ref{table_multi_task} illustrates the RMSE and $R^2$ results on the usefulness of TANs. By using TANs, the RSME values improve 0.0097, 0.0198, and 0.0036, respectively, for predicting the sea subsurface temperatures 50m, 100m, and 150m undersea. Using TANs also improves the $R^2$ values. The results of Table~\ref{table_multi_task} therefore demonstrate that multi-task learning is effective to improve the prediction performance. \subsubsection*{Effectiveness of the Mask} When we employ the physics-based loss to guide the network training, the temperature between the upper and lower layers are compared by using a mask and the margin is set to 0.1 here. Here we compare several schemes: no use of mask (NO mask), deeper-layer sea temperature as mask (DP mask) and shallower-layer sea temperature as mask (SL mask). Table~\ref{table_pbl} summarizes the RMSE and $R^2$ results obtained with these mask schemes. It can be seen that the method with the SL mask achieves the best RMSE and $R^2$ values. Therefore, we adopt the SL mask in the physics-based loss for our approach (see (\ref{eq3}) to (\ref{eq5}) and the discussions after (\ref{eq6})). \begin{table}[hbp!] \vspace*{-3mm} \caption{Study on the mask in physics-based loss} \label{table_pbl} \vspace*{-4mm} \begin{center} \begin{tabular}{|c||c|c|c|} \hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{RMSE ($^{\circ}$C)}\\ \cline{2-4} & ~~~~50m~~~~ & ~~~~100m~~~~ & ~~~~150m~~~~ \\ \hline \hline ~~~~ NO mask ~~~~ & 0.9480 & 1.3663 & 1.1977 \\ DP mask & 0.9647 & 1.3114 & 1.2048 \\ SL mask & 0.9333 & 1.2931 & 1.1969 \\ \hline \hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{$R^{2}$} \\ \cline{2-4} & 50m & 100m & 150m \\ \hline \hline NO mask & 0.5276 & 0.3020 & 0.5865 \\ DP mask & 0.5217 & 0.3277 & 0.5742 \\ SL mask & 0.5457 &0.3577 & 0.5885 \\ \hline \end{tabular} \end{center} \vspace*{-3mm} \end{table} \subsubsection*{Analysis of the Margin} Likewise, in order to obtain better fitting ability, we add a margin in physics-based loss. First, we calculated the maximum temperature difference between the samples of two depths. Then the margin of the physics-based loss is scaled from 0 to Max. Table~\ref{table_margin} shows the prediction results of different margins. The best RMSE and $R^{2}$ values are obtained when the margin is set to 0.100. Therefore, in our approach we set the margin to 0.100 (see (\ref{eq3}) to (\ref{eq5})). \begin{table}[tp!] \vspace*{-1mm} \caption{Study on different margins} \label{table_margin} \vspace*{-4mm} \begin{center} \begin{tabular}{|c||c|c|c|} \hline \multirow{2}{*}{Margin} & \multicolumn{3}{c|}{RMSE ($^{\circ}$C)} \\ \cline{2-4} & ~~~~ 50m ~~~~ & ~~~~ 100m ~~~~ & ~~~~ 150m ~~~~ \\ \hline \hline zero & 0.9976 & 1.3668 & 1.2345 \\ 0.001 & 0.9401 & 1.3077 & 1.2152 \\ 0.010 & 0.9731 & 1.3631 & 1.2418 \\ 0.100 & 0.9333 & 1.2931 & 1.1969 \\ max & 0.9403 & 1.3297 & 1.2063 \\ \hline \hline \multirow{2}{*}{Margin} & \multicolumn{3}{c|}{$R^{2}$} \\ \cline{2-4} & 50m & 100m & 150m \\ \hline \hline zero & 0.4768 & 0.2795 & 0.5596 \\ 0.001 & 0.5397 & 0.3489 & 0.5597 \\ 0.010 & 0.5236 & 0.2813 & 0.5596 \\ 0.100 & 0.5457 & 0.3577 & 0.5885 \\ max & 0.5300 &0.3166 & 0.5831 \\ \hline \end{tabular} \end{center} \vspace*{-5mm} \end{table} \subsubsection*{Analysis of the Physics-based Loss in Stage 2} In the second phase of the proposed method, we apply remote sensing data and Argo data to fine-tune the model. We estimate the contribution of $L_{0\rightarrow50}(G)$ in the physics-based loss in Table~\ref{table_loss_stage2}. It can be observed that the model without $L_{0\rightarrow50}(G)$ performs better. The reason is owing to the the imprecision of remote sensing AVHRR SST data, which degrades the performance of the model with $L_{0\rightarrow50}(G)$. Therefore, in our proposed method, we do not take $L_{0\rightarrow50}(G)$ into account in the physics-based loss in the second stage (see (\ref{eq10})). \begin{table}[htp!] \vspace*{-3mm} \caption{Study on the physics-based Loss in Stage 2} \label{table_loss_stage2} \vspace*{-4mm} \begin{center} \begin{tabular}{|c||c|c|c|} \hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{RMSE($^{\circ}$C)} \\ \cline{2-4} & ~50m~ & ~100m~ & ~150m~ \\ \hline\hline Model with $L_{0\rightarrow50}(G)$ in stage 2~~~ & 0.9465 & 1.3386 & 1.2031 \\ Model without $L_{0\rightarrow50}(G)$ in stage 2 & 0.9333 & 1.2931 & 1.1969 \\ \hline\hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{$R^{2}$} \\ \cline{2-4} & 50m & 100m & 150m \\ \hline \hline Model with $L_{0\rightarrow50}(G)$ in stage 2~~~ & 0.5218 & 0.3210 & 0.5826 \\ Model without $L_{0\rightarrow50}(G)$ in stage 2 & 0.5457 & 0.3577 & 0.5885 \\ \hline \end{tabular} \end{center} \vspace*{-2mm} \end{table} \begin{table}[bp!] \vspace*{-6mm} \caption{Study on the network architecture} \label{table_archi} \vspace*{-4mm} \begin{center} \begin{tabular}{|c||c|c|c|} \hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{RMSE ($^{\circ}$C)}\\ \cline{2-4} & ~~~~50m~~~~ & ~~~~100m~~~~ & ~~~~150m~~~~ \\ \hline \hline One attention module & 0.9562 & 1.3286 & 1.2003 \\ One discriminator & 1.0075 & 1.2965 & 1.2010 \\ Our method & 0.9333 & 1.2931 & 1.1969 \\ \hline \hline \multirow{2}{*}{Method} & \multicolumn{3}{c|}{$R^{2}$} \\ \cline{2-4} & 50m & 100m & 150m \\ \hline \hline One attention module & 0.5429 & 0.2799 & 0.5741 \\ One discriminator & 0.4765 & 0.3511 & 0.5736 \\ Our method & 0.5457 &0.3577 & 0.5885 \\ \hline \end{tabular} \end{center} \vspace*{-2mm} \end{table} \subsubsection*{Network Architecture Design} We use 3 attention modules and 3 discriminators for the three specific tasks, respectively. Considering the similarity in these tasks, the network architecture designs that exploit one attention module or one discriminator to learn different tasks are also experimented, and the results obtained are compared with our design in Table~\ref{table_archi}. The experimental results show that using more attention modules and discriminators can achieve better performance. Although our model performs better in this study than the model with single attention module and single discriminator, it has a higher computational complexity than the latter. In the case of predicting the subsurface temperatures at more than three depths, a single attention module with a single discriminator may become a better choice. \begin{figure}[bp!] \vspace*{-6mm} \begin{center} \includegraphics[width=0.88\columnwidth]{fig_50m_vs_argo.jpg} \end{center} \vspace*{-6mm} \caption{Predicted temperature at 50m undersea versus Argo data.} \label{fig_model_argo_50m} \vspace*{-2mm} \end{figure} \begin{figure}[bhp!] \vspace*{-2mm} \begin{center} \includegraphics[width=0.88\columnwidth]{fig_100m_vs_argo.jpg} \end{center} \vspace*{-6mm} \caption{Predicted temperature at 100m undersea versus Argo data.} \label{fig_model_argo_100m} \vspace*{-2mm} \end{figure} \begin{figure}[bhp!] \vspace*{-2mm} \begin{center} \includegraphics[width=0.88\columnwidth]{fig_150m_vs_argo.jpg} \end{center} \vspace*{-6mm} \caption{Predicted temperature at 150m undersea versus Argo data.} \label{fig_model_argo_150m} \vspace*{-1mm} \end{figure} \begin{table*}[bp!] \vspace*{-4mm} \caption{Sea Subsurface Temperature Prediction Results (Average$\pm$STD) of Different Methods Averaged over 10 Random Runs} \label{table_res_all} \vspace*{-4mm} \begin{center} \begin{tabular}{|c||c|c|c|c|c|c|} \hline \multirow{2}{*}{Model} & \multicolumn{3}{c|}{RMSE($^{\circ}$C)} \\ \cline{2-4} & ~~~50m~~~ & ~~~100m~~~ & ~~~150m~~~ \\ \hline \hline Assimilation method & 1.4520 & 1.8201 & 1.6774 \\ PGpix2pix & 0.9528$\pm$0.0114 & 1.3301$\pm$0.024 & 1.2890$\pm$0.0415 \\ PGcycleGAN & 2.6155$\pm$0.0812 & 2.5345$\pm$0.042 & 2.7954$\pm$0.180 \\ PGNN & 0.9482$\pm$0.0070 & 1.3691$\pm$0.0259 & 1.2837$\pm$0.039 \\ PGConvLSTM & 1.9213$\pm$0.223 & 1.6928$\pm$0.021 & 1.9974$\pm$0.127 \\ PGsim & 1.1132$\pm$0.033 & 1.4659$\pm$0.083 & 1.3281$\pm$0.004 \\ Our method without PLoss & 0.9517$\pm$0.0082 & 1.3312$\pm$0.0251 & 1.2648$\pm$0.0313 \\ Our method with PLoss & \textbf{0.9402$\pm$0.0069} & \textbf{1.2894$\pm$0.0038} & \textbf{1.2330$\pm$0.0361} \\ \hline\hline \multirow{2}{*}{Model} & \multicolumn{3}{c|}{$R^{2}$} \\ \cline{2-4} & 50m & 100m & 150m \\ \hline \hline Assimilation method & -0.4393 & -0.2661 & 0.1938 \\ PGpix2pix & 0.5447$\pm$0.0119 & 0.3581$\pm$0.051 & 0.4992$\pm$0.043 \\ PGcycleGAN & -2.8694$\pm$0.44 & -1.9791$\pm$0.2798 & -1.0427$\pm$0.4027 \\ PGNN & 0.5381$\pm$0.0112 & 0.2621$\pm$0.2089 & 0.2583$\pm$0.1958 \\ PGConvLSTM & -0.8927$\pm$0.2110 & -0.4445$\pm$0.3627 & -0.0655$\pm$0.1212 \\ PGsim & 0.3555$\pm$0.0191 & 0.0179$\pm$0.2842 & 0.4514$\pm$0.042 \\ Our method without PLoss & 0.5512$\pm$0.0175 & 0.2934$\pm$0.045 & 0.5515$\pm$0.0212 \\ Our method with PLoss & \textbf{0.5610$\pm$0.0153} & \textbf{0.3957$\pm$0.0392} & \textbf{0.5665$\pm$0.024} \\ \hline \end{tabular} \end{center} \vspace*{-2mm} \end{table*} \begin{figure}[thp!] \vspace*{-2mm} \begin{center} \includegraphics[width=0.77\columnwidth,height=0.77\columnwidth]{fig_50m_scatter.jpg} \end{center} \vspace*{-6mm} \caption{Predicted temperature at 50m undersea and corresponding Argo data scatter plot.} \label{fig_scatter_50m} \vspace*{-4mm} \end{figure} \begin{figure}[!th] \vspace*{-2mm} \begin{center} \includegraphics[width=0.77\columnwidth,height=0.77\columnwidth]{fig_100m_scatter.jpg} \end{center} \vspace*{-6mm} \caption{Predicted temperature at 100m undersea and corresponding Argo data scatter plot.} \label{fig_scatter_100m} \begin{center} \includegraphics[width=0.77\columnwidth,height=0.77\columnwidth]{fig_150m_scatter.jpg} \end{center} \vspace*{-6mm} \caption{Predicted temperature at 150m undersea and corresponding Argo data scatter plot.} \label{fig_scatter_150m} \vspace*{-4mm} \end{figure} \subsection{Experimental Results and Analysis}\label{S4.4} For the Argo data from January 2004 to April 2007, after removing the invalid data, we obtain 180 daily temperature observation values. We compare the predicted results with these 180 remaining Argo observational data. Fig.~\ref{fig_model_argo_50m} compares the predicted temperature at 50m undersea with the corresponding Argo data. It can be observed that the predicted results of the proposed method fit well the Argo data. Similarly, the Argo data and the corresponding predicted temperatures at 100m undersea and 150m undersea are illustrated in Figs.~\ref{fig_model_argo_100m} and \ref{fig_model_argo_150m}, respectively. These results demonstrate that the proposed method can generate reliable and accurate temperature predictions at different depths of the sea. \begin{figure*}[tp!] \vspace*{-4mm} \begin{center} \includegraphics[width=0.9\linewidth,angle=0]{map_50_100_150.pdf} \end{center} \vspace*{-4mm} \caption{Display of predicted temperature values and measurements at different depths on November 9, 2006.} \label{fig_visual_res} \vspace*{-4mm} \end{figure*} A correlation scatter plot between the predicted temperature at 50m undersea and the Argo data is depicted in Fig.~\ref{fig_scatter_50m}. If the data points are more evenly and densely distributed near the diagonal red line, the prediction result is better. Similar scatter plots of the prediction results at 100m undersea and 150m undersea are shown in Figs.~\ref{fig_scatter_100m} and \ref{fig_scatter_150m}, respectively. As can be observed, the prediction results at 50m undersea are better than the results at 100m and 150m undersea. Evidently, as depth increases, the prediction accuracy decreases. Fig.~\ref{fig_visual_res} displays the temperatures predicted by the proposed method at different depths (50m, 100m and 150m) together with the corresponding Argo observations on November 9, 2006. The visual results show that the predicted results by the proposed method are very close to the ground truth Argo data. This demonstrates that the proposed method is reliable and accurate. The temperature prediction experiment for each model is repeated 10 independent runs with different random initializations. We summarize the temperature prediction results, presented as average$\pm$standard deviation (STD), of different methods in Table~\ref{table_res_all}, where PGpix2pix and PGcycleGAN are the pix2pix method with the numerical model and the CycleGAN method with the numerical model, respectively. Note that applying neural networks, such as pix2pix and CycleGAN, without considering the numerical model is incapable of predicting daily sea subsurface temperature effectively, owing to very limited observational data. Consequently, we have to adopt our idea of physics guided (PG) enhancement by combining neural networks with numerical model. To compare with the methods in \cite{jia_PGRNN} and \cite{zhang19_grsl}, we adopt ConvLSTM model to replace the RNN model for acquiring the sea subsurface temperature prediction in the whole area of China South Sea, which we refer to as PGConvLSTM. Specifically, we train the ConvLSTM model by using the same training mode as ours and removing the mapping from the surface temperature to the subsurface temperature learned by the GAN model as the works \cite{jia_PGRNN,zhang19_grsl} did. In our proposed model, we pre-train the GAN on the numerical model data and then fine-tune the GAN model with the observational data. To compare with this two-stage training, we also simply concatenate the numerical simulation data onto the observational data together to train the GAN, which we refer to as PGsim. Our framework uses the physics loss to automatically encodes the knowledge of ocean physics into the modeling process. In addition to our method with physics loss (Our method with PLoss), the results of our method without physics loss (Our method without PLoss) are also shown in Table~\ref{table_res_all}. The results of the PGConvLSTM are poor, as this approach does not exploit the mapping from the surface temperature to the subsurface temperature learned by the GAN model \cite{jia_PGRNN,zhang19_grsl}. This demonstrates that this mapping is essential in the prediction of the daily subsurface temperature. Our proposed GAN based framework effectively exploits the merits of both the numerical model and neural network and can learn the map from the surface to the subsurface well through the proposed two-stage training. By contrast, simply concatenating the numerical data and the observational data together to train the model (PGsim) is less accurate than our approach. It can be seen from Table~\ref{table_res_all} that our proposed method with the physics loss attains the best performance. In terms of RMSE, it outperforms PGpix2pix by 0.0126, 0.0407 and 0.056 ($^{\circ}$C) for predicting the sea temperatures 50m, 100m and 150m undersea, respectively. In terms of $R^2$ statistic, our method outperforms PGpix2pix by 0.0163, 0.0376 and 0.0673 for predicting the sea subsurface temperatures at these depths, respectively. Additionally, our method and PGpix2pix have similar STDs for the both performance metrics. Also observe that our method with physics loss outperforms the one without physics loss. Hence, the experimental results clearly demonstrate that the proposed method is capable of enhancing the daily sea subsurface temperature prediction over the existing state-of-the-art methods. Currently, only the traditional assimilation method can predict the daily sea subsurface temperature. Our proposed method is the first which can significantly improve the accuracy of the daily sea subsurface temperature prediction compared with the assimilation method. We believe that exploiting the numerical model data and two-stage training mode that we propose are essential to perform the daily sea subsurface temperature prediction task. Multi-task learning is integrated into the proposed method to enable the prediction of the temperatures at 50\,m, 100\,m and 150\,m underwater simultaneously. A physics-based loss is also added to our model to further improve the the accuracy of the daily sea subsurface temperature prediction. The experimental results have verified the effectiveness of our proposed method. Furthermore, our proposed framework also benefits other existing neural network based methods. Although only applying the pix2pix framework or other neural network is incapable of predicting the daily sea subsurface temperature effectively owing to the very limited observational data, by adopting our idea of combining neural network and the numerical model, PGpix2pix becomes capable of significantly outperforming the assimilation method. The experimental results confirm that our proposed method outperforms the existing state-of-the-art methods. Compared with PGpix2pix, although the performance gain is small, our method can predict the temperatures for all the target depths simultaneously, while PGpix2pix needs multiple models to predict the temperatures of different depths. In our experiments, we have to discard a lot of data since not every daily Argo data is valid. Clearly, by using more usable data sets to provide sufficient training and testing data, the accuracy of prediction can further be improved. In addition, our experimental results will also be enhanced by looking for better quality remote sensed images. \section{Conclusions and Future Work}\label{S5} In this paper, we have proposed a novel GAN-based framework for challenging daily sea subsurface temperature prediction. In our method, a physics-based numerical model is employed in a GAN to acquire the simplified physical laws at different ocean depths, and observational data are used for fine-tuning the model parameters to obtain better prediction results. Our method has effectively exploited the complementary merit of physics-based numerical model and observational data based neural network. Moreover, a physics-based loss based on a mask has been employed, which leads to improved prediction performance. The experimental results have demonstrated that the proposed method can achieve better performance in daily sea subsurface temperature prediction compared with the state-of-the-art baselines. In the future, we plan to extend our work to temporal dimension with better quality and large scales traits, which will provide more information to further improve the prediction accuracy. In addition, we also plan to investigate the use of several self-attention networks to enhance the overall performance of our model.
{'timestamp': '2021-11-08T02:00:11', 'yymm': '2111', 'arxiv_id': '2111.03064', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03064'}
arxiv
\section{Other practical challenges} \label{app sec: practicaL challenges} \paragraph{Parameterizing covariances} It is common to to re-parameterize covariance matrices to a vector of unconstrained parameters. As above, the typical way to do this is via a function $\mathrm{tril}$ that maps unconstrained vectors to Cholesky factors, i.e. lower-triangular matrices with positive diagonals. This can be done by simple re-arranging the components of the vector into a lower-triangular matrix, followed by applying a function to map the entries on the diagonal components to the positive numbers. In our preliminary experiments, the choice of the mapping was quite significant in terms of how difficult optimization was. Common choices like the ${\exp(x)}$ and ${\log (\exp (x) + 1)}$ functions did not perform well when the outputs were close to zero. Instead, we propose to use the transformation $ x \mapsto \frac{1}{2}(x + \sqrt{x^2 + 4 \gamma})$, where $\gamma$ is a hyperparameter (we use $\gamma=1$). This is based on the proximal operator for the multivariate Gaussian entropy \cite[section 5]{domke2020provable}. Intuitively, when $x$ is a large positive number, this mapping returns approximately $x$, while if $x$ is a large negative number, the mapping returns approximately $-1/x$. This decays to zero more slowly than common mappings, which appears to improve numerical stability and the conditioning of the optimization. \paragraph{Feature network architecture.} In this paper, we propose the use of a separate \texttt{feat\_net} to deal with variable-length input and order invariance. In our preliminary experiments, we found that the performance improves when we concatenate the embedding $e_j$ in the \cref{fig: featnet} with it's dimension-wise square before sending it to the pooling function \texttt{pool}. We hypothesis that this is because the embeddings act as learnable statistics, and using the elementwise square directly provides useful information to \texttt{param\_net}. \paragraph{Batch size selection} For the small scale problems (both synthetic and MovieLens), we do not subsample data; this is to maintain a fair comparison to joint approaches that do not support subsampling. For moderate and large scales, we select the batch size for the branch methods based on the following rule of thumb: we increase the batch size such that $\mathsmaller {\frac{\verts{B}}{T^{1.18}}}$ is roughly maximized. This rule-of-thumb captures the following intuition. Suppose batch size $\verts{B}$ takes time $T$ per iteration. If the time taken per iteration for batchsize $\verts{2B}$ is less than $1.8T$, then we should use $2B$. Of course, we roughly maximize $\mathsmaller{\frac{\verts{B}}{T^{1.18}}}$ for computational ease. We use the same batch size as the branch methods for the amortized methods as we found that amortized methods were much more robust to the choice of batchsize. We use $\verts {B} = 200$ for moderate scale and $\verts{B}= 400$ for large scale. \paragraph{Initialization} We initialize the neural network parameters using a truncated normal distribution with zero mean and standard deviation equal to $\mathsmaller{\sqrt{1/\mathrm{fan\_in}}}$, where $\mathrm{fan\_in}$ is the number of inputs to the layer \cite{lecun2012efficient}. We initialize the final output layer of the \texttt{param-net} with a zero mean Gaussian with a standard deviation of 0.001 \cite{aagrawal2020}. This ensures an almost standard normal initialization for the local conditional $q_{{\normalfont \texttt{net}}_{u}(x_i, y_i)}(z_i \vert \theta)$. \paragraph{Gradient Calculation} In our preliminary experiments, we found sticking the landing gradient \cite[STL]{roeder2017sticking} to be less stable. STL requires a re-evaluation of the density which in turn requires a matrix inversion (for the Cholesky factor); this matrix inversion was sometimes prone to numerical precision errors. Instead, we found the regular gradient, also called the total gradient in \cite{roeder2017sticking}, to be numerically robust as it can be evaluated without a matrix inversion. This is done by simultaneously sampling and evaluating the density in much the same as done in normlaizing flows \cite{pmlr-v32-rezende14,papamakarios2019normalizing}. We use the total gradient for all our experiments. \section{General trade-offs} \label{app sec: tradeoffs} \begin{wraptable}{r}{0.5\textwidth} \vspace{-10pt} \caption{Summary of method applicability.} \label{tab: method applicability} \resizebox*{0.5\textwidth}{!}{ \begin{tabular}[!h]{@{} lccc @{}} \toprule Models & $q_{v,w}^{\mathrm{Branch}}$ & $q_{v,u}^{\mathrm{Amort}}$ & $q_{v,u}^{\mathrm{Amort}}$ w/ \texttt{feat\_net}$_u$\\ &{\small (\cref{def: branch dists})}& {\small (\cref{def: amort branch dist})}&{(\small ${\normalfont \texttt{net}}_u$ as in \cref{fig: featnet})}\\ \midrule HBD \hspace{44pt} {(\small \cref{eq: branch distributions})} & \checkmark & $\times$ & $\times$\\[1.5mm] Symmetric HBD {(\small \cref{eq: symmetry condition})}& \checkmark & \checkmark & \checkmark\\[1.5mm] Locally i.i.d. &&&\\ Symmetric HBD {(\small\cref{eq: branch distributions alternate})} & \checkmark & $\times$ & \checkmark\\ \bottomrule \end{tabular} } \end{wraptable} The amortized approach proposed in \cref{sec: amortized dist} is only applicable for symmetric models. In \cref{tab: method applicability}, we summarize the applicability of all the methods we discuss in this paper. In our preliminary experiments, for amortized approaches, the performance improved when we increased the number of layers in the neural networks or increased the length of the embeddings in ${\normalfont \texttt{net}}_u$. However, we make no serious efforts to find the optimal architecture. In fact, we use the same architecture for all our experiments, across the scales. We believe the performance on a particular task can be further improved by carefully curating the neural architecture. Note that there are no architecture choices in joint or branched approaches. We also did not optimize our choice of number of samples to drawn from $q$ to estimate ELBO. This forms the second source of stochasticity and using more samples can help reduce the variance \cite{titsias2014doubly}. We use 10 copies for all our experiments. A particularly interesting case arises when the number of local latent variables ($N$) is very large. In such scenarios, the true posterior $p(\theta \vert x, y)$ can be too concentrated. As the randomness in $\theta$ is very low, we might not gain any significant benefits from conditioning on $\theta$\textemdash as $\theta$ reduces to a fixed quantity, Dense Gaussian will work just well as the Block Gaussian (see \cref{tab: movielens results,tab: extended movielens a,tab: extended movielens b}). In practice, it is hard to know this apriori; in fact, our scalable approaches allow for such analysis on large scale model. \section{Proof for Theorem} \label{app sec: proof of theorem} \begin{thm*} [Repeated] Let $p$ be a HBD, and $q_\phi^\mathrm{Joint}\pp{\theta,z}$ be a joint approximation family parameterized by $\phi$. Choose a corresponding branch variational family $q_{v,w}^{\mathrm{Branch}}(\theta, z)$ as in \cref{def: branch dists}. Then, \[ \min_{v,w}\KL{q_{v,w}^{\mathrm{Branch}}}p\leq\min_{\phi}\KL{q_\phi^\mathrm{Joint}}p. \] \end{thm*} \begin{proof} Construct a new distribution $q'_\phi$ such that \begin{align} q'_\phi(\theta, z) = q_\phi^\mathrm{Joint} (\theta) \prod_{i} q_\phi^\mathrm{Joint}(z_i \vert \theta). \end{align} Then, note that $z_i$ are conditionally independent in $q'_\phi$, such that, \begin{align} q'_\phi(z_i \vert \theta, z_{<i}) & = q'_\phi(z_i \vert \theta). \end{align} From chain rule of KL-divergence, we have \begin{align*} \KL{q_\phi^\mathrm{Joint}(\uptheta, \mathsf{z})}{p(\uptheta, \mathsf{z} \vert x, y)} &= \KL{q_\phi^\mathrm{Joint}(\uptheta)}{p(\uptheta \vert x, y)} \\ & \phantom{some}+ \sum_i \KL {q_\phi^\mathrm{Joint}(\mathsf{z}_i \vert \mathsf{z}_{<i}, \uptheta)}{p(\mathsf{z}_i \vert \mathsf{z}_{<i}, \uptheta, x, y)},\text{ and}\\ \KL{q'_\phi(\uptheta, \mathsf{z})}{p(\uptheta, \mathsf{z} \vert x, y)} &= \KL{q_\phi^\mathrm{Joint}(\uptheta)}{p(\uptheta \vert x, y)} \\ & \phantom{some}+ \sum_i \KL {q'_\phi(\mathsf{z}_i \vert \mathsf{z}_{<i}, \uptheta)}{p(\mathsf{z}_i \vert \mathsf{z}_{<i}, \uptheta, x, y)}.\\ \end{align*} Consider any arbitrary summand term. We have that \begin{align*} &\KL {q_\phi^\mathrm{Joint}(\mathsf{z}_i \vert \mathsf{z}_{<i}, \uptheta)}{p(\mathsf{z}_i \vert \mathsf{z}_{<i}, \uptheta, x, y)}\\ & \overset{(1)}{=} \KL {q_\phi^\mathrm{Joint}(\mathsf{z}_i \vert \mathsf{z}_{<i}, \uptheta)}{p(\mathsf{z}_i \vert \uptheta, x_i, y_i)}\\ & \overset{(2)}{=} \E_{\theta \sim q_\phi^\mathrm{Joint}(\uptheta)}\E_{z_{< i} \sim q_\phi^\mathrm{Joint} (\mathsf{z}_{<i} \vert \uptheta)} [\KL{q_\phi^\mathrm{Joint}(\mathsf{z}_i \vert z_{<i}, \theta)}{p(\mathsf{z}_i \vert \theta, x_i, y_i)}]\\ & \overset{(3)}{\ge} \E_{\theta \sim q_\phi^\mathrm{Joint}(\uptheta)} \left[\KL{\E_{z_{< i} \sim q_\phi^\mathrm{Joint} (\mathsf{z}_{<i} \vert \uptheta)}\left[q_\phi^\mathrm{Joint}(\mathsf{z}_i \vert z_{<i}, \theta)\right]}{\E_{z_{< i} \sim q_\phi^\mathrm{Joint} (\mathsf{z}_{<i} \vert \uptheta)}\left[p(\mathsf{z}_i \vert \theta, x_i, y_i)\right]}\right]\\ & \overset{(4)}{=} \E_{\theta \sim q_\phi^\mathrm{Joint}(\uptheta)} \left[\KL{ q_\phi^\mathrm{Joint}(\mathsf{z}_i \vert \theta)}{p(\mathsf{z}_i \vert \theta, x_i, y_i)}\right]\\ & \overset{}{=} \KL{ q_\phi^\mathrm{Joint}(\mathsf{z}_i \vert \uptheta)}{p(\mathsf{z}_i \vert \uptheta, x_i, y_i)}\\ & \overset{}{=} \KL{ q'_\phi(\mathsf{z}_i \vert \uptheta)}{p(\mathsf{z}_i \vert \uptheta, x_i, y_i)}\\ & \overset{(5)}{=} \KL{ q'_\phi(\mathsf{z}_i \vert \uptheta, \mathsf{z}_{<i})}{p(\mathsf{z}_i \vert \uptheta, \mathsf{z}_{<i}, x_i, y_i)},\\ \end{align*} where (1) follows from HBD structure; (2) follows from definition of conditional KL divergence; (3) follows from convexity of KL divergence and Jensen's inequality; (4) follows from marginalization, and (5) follows from the conditional independence of $q'$ and $p$. Summing the above result over $i$ gives that \begin{align} \KL{q'_\phi}{p} \le \KL{q_\phi^\mathrm{Joint}}{p}. \end{align} Now, from \cref{def: branch dists}, we know that for every $\phi$, there exists a corresponding $(v, w)$ such that $q_{v,w}^{\mathrm{Branch}} = q'_\phi.$ Let $\phi^* = \argmin_\phi \KL {q_\phi^\mathrm{Joint}}{p}$. Then, there exists some $q_{v,w}^{\mathrm{Branch}} = q'_{\phi^*}$. Then, it follows that \begin{align} \min_{v,w}\KL{q_{v,w}^{\mathrm{Branch}}}p\le \KL{q'_{\phi^*}}{p} \le \KL{q^{\mathrm{Joint}}_{\phi^*}}{p} = \min_{\phi}\KL{q_\phi^\mathrm{Joint}}p. \end{align} \end{proof} \section{Proof for Claim} \label{app sec: proof of claim} \begin{claim*}[Repeated] Let $p$ be a symmetric HBD and let $q_\phi^\mathrm{Joint}$ be some joint approximation. Let $q_{v,u}^{\mathrm{Amort}}$ be as in \cref{def: branch dists}. Suppose that for all $v$, there exists a $u$, such that, \begin{align} {\normalfont {\normalfont \texttt{net}}}_u (x_i, y_i) = \argmax_{w_i}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right ]. \end{align} Then, \begin{align} \min_{v, u} \KL{q_{v,u}^{\mathrm{Amort}}}p \le \min_{\phi} \KL{q_\phi^\mathrm{Joint}}p \end{align} \end{claim*} \begin{proof} Consider the optimization for $q_{v,w}^{\mathrm{Branch}}$. We have \begin{align*} \max_{v,w}\ELBO{q_{v,w}^{\mathrm{Branch}}}p &=\max_{v,w} \bracs{\E_{q_{v}\left(\uptheta\right)}\left[\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}\right]+\sum_{i=1}^{N}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right]}\\ & =\max_v \bracs{\E_{q_{v}\left(\uptheta\right)}\left[\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}\right]+\sum_{i=1}^{N}\max_{w_i}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right]}\\ & \overset{(1)}{=}\max_v \bracs{\E_{q_{v}\left(\uptheta\right)}\left[\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}\right]+\sum_{i=1}^{N}\E_{q_{v}\left(\uptheta\right)}\E_{q_{{\normalfont \texttt{net}}_u(x_i, y_i)}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{{\normalfont \texttt{net}}_u(x_i, y_i)}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right]}\\ & {\le} \max_u \max_v \bracs{\E_{q_{v}\left(\uptheta\right)}\left[\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}\right]+\sum_{i=1}^{N}\E_{q_{v}\left(\uptheta\right)}\E_{q_{{\normalfont \texttt{net}}_u(x_i, y_i)}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{{\normalfont \texttt{net}}_u(x_i, y_i)}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right]}\\ & = \max_u \max_v \ELBO{q_{v,u}^{\mathrm{Amort}}}p, \end{align*} where (1) follows from the assumption in the Claim. Now, from the ELBO decomposition equation, we have \begin{align} \log p(y\vert x) & = \ELBO{q}{p} + \KL{q}{p}. \end{align} Therefore, we have \begin{align} \min_u \min_v \KL{q_{v,u}^{\mathrm{Amort}}}p \le \min_{v,w} \KL{q_{v,w}^{\mathrm{Branch}}}p \end{align} From \cref*{thm: branch q better than q for hbd}, we get the desired result. \begin{align} \min_u \min_v \KL{q_{v,u}^{\mathrm{Amort}}}p \le \min_{v,w} \KL{q_{v,w}^{\mathrm{Branch}}}p\le \min_{\phi} \KL{q_\phi^\mathrm{Joint}}p \end{align} \end{proof} \section{Derivation for Branch Gaussian} \label{app sec: derivation of branch gaussian} Let $q_\phi^\mathrm{Joint}(\theta, z) = \N ((\theta, z) \vert \mu, \Sigma)$ be the joint Gaussian approximation as in \cref{cor: branch gaussian}. Further, let $(\mu, \Sigma)$ be defined as \begin{align} \mu = \begin{bmatrix} \mu_{\theta}\\ \mu_{z_1}\\ \vdots\\ \mu_{z_N} \end{bmatrix}\quad \text{and } \quad \Sigma = \begin{bmatrix} \Sigma_\theta & \Sigma_{\theta z_1} & \dots & \Sigma_{\theta z_N}\\ \Sigma_{\theta z_1}^\top & \Sigma_{z_1 } & \dots & \Sigma_{z_1 z_N}\\ \vdots & \vdots & \ddots & \vdots\\ \Sigma_{\theta z_n}^\top & \Sigma_{z_1 z_N}^\top & \dots & \Sigma_{z_N }\\ \end{bmatrix}. \end{align} Then, from the properties of the multivariate Gaussian \cite{IMM2012-03274} \begin{align} q_\phi^\mathrm{Joint}(z_i \vert \theta) &= \N (z_i \vert \mu_{z_i \vert \theta}, \Sigma_{z_i \vert \theta}) \text{, where}\\ \mu_{z_i \vert \theta} & = \mu_{z_i} + \Sigma_{\theta z_i}^\top \Sigma_{\theta}^{-1}(\theta - \mu_\theta) \text{, and }\\ \Sigma_{z_i \vert \theta} & = \Sigma_{z_i z_i} - \Sigma_{\theta z_i}^\top \Sigma_{\theta}^{-1} \Sigma_{\theta z_i}. \end{align} Now, to parameterize a corresponding $q_{v,w}^{\mathrm{Branch}}$, we use the $(\mu_i, \Sigma_i, A_i)$, such that, \begin{align} q_{v,w}^{\mathrm{Branch}}(z_i \vert \theta) &= \N (z_i \vert \mu_i + A_i \theta, \Sigma_i). \end{align} \section{Experimental Details} \label{app sec: experimental details} \paragraph{Architectural Details} \begin{wraptable}{r}{0.35\textwidth} \vspace{-5pt} \caption{ Architecture details for ${\normalfont \texttt{net}}_u$. Each fully-connected layer is followed by leaky-ReLU baring the last layer. } \centering \label{tab: arch details} \resizebox*{0.3\textwidth}{!}{ \begin{tabular}[!h]{@{} ll @{}} \toprule Network & Layer Skeleton\\ \midrule \texttt{feat-net} & 64, 64, 64, 128\\ \texttt{param-net} & 256, 256, 256\\ \bottomrule \end{tabular} } \vspace{-10pt} \end{wraptable} We use the architecture as reported in \cref{tab: arch details} for all our amortized approaches. In addition to using $e_j$ as detailed in \cref{fig: featnet}, we concatenate the elementwise square before sending it to \texttt{param-net}. Thus, the input to \texttt{param-net} is not 128 dimensional but 256 dimensional. Further, we use mean as the \texttt{pool} function. \paragraph{Compute Resources} We use JAX \cite{jax2018github} to implement our methods. We trained using Nvidia 2080ti-12GB. All methods finished training within 4 hours. Branch approaches were at an average twice as fast as amortized variants. \paragraph{Step-size drop} We use Adam \cite{kingma2014adam} for training with an initial step-size of 0.001 (and default values for other hyperparameters.) In preliminary experiments, we found that dropping the step-size improves the performance. Starting from 0.001, we drop the step to one-tenth of it's value after a predetermined number of steps. For small scale experiments, we drop a total of three times after every 50,000 iterations (we train for 200,000 iterations.) For moderate and large scale models, we drop once after 100,000 iterations. \subsection{Movielens} \label{app sec: movielens details} \begin{wraptable}{r}{0.4\textwidth} \vspace{-10pt} \caption{\small Metrics used for evaluation. We use K = 10,000 samples from the posterior. Here, $(z^{k}, \theta^{k}) \sim q(\mathsf{z}, \uptheta \vert x^{\mathrm{train}}, y^{\mathrm{train}})$.} \centering \label{tab: metrics} \resizebox*{0.4\textwidth}{!}{ \begin{tabular}[!h]{@{} ll @{}} \toprule Metric & Expression\\ \midrule Test likelihood & $\log \frac{1}{K}\sum_{k} p(y^{\mathrm{test}}\vert x^{\mathrm{test}}, z^k, \theta^k)$ \\[1.5mm] Train likelihood & $\log \frac{1}{K}\sum_{k} \frac{p(y^{\mathrm{train}}, z^k, \theta^k\vert x^{\mathrm{train}})}{q(z^k, \theta^k \vert x^{\mathrm{train}}, y^{\mathrm{train}})}$ \\[1.5mm] Train ELBO & $\frac{1}{K}\sum_{k} \log \frac{p(y^{\mathrm{train}}, z^k, \theta^k\vert x^{\mathrm{train}})}{q(z^k, \theta^k \vert x^{\mathrm{train}}, y^{\mathrm{train}})}$ \\ \bottomrule \end{tabular} } \vspace{-15pt} \end{wraptable} \paragraph{Feature Dimensions} We reduce the movie feature dimensionality to 10 using PCA. This is done with branch approaches in focus as the number of features for dense branch Gaussian scale as $\mathcal{O}(ND^3)$, where $D$ is the dimensionality of the movie features. Note, that the number of features for amortized approaches is independent of $N$ allowing for better scalability. \paragraph{Metrics} We use three metrics for performance evaluation---test likelihood, train likelihood, and train ELBO. Details of the expressions are presented in \cref{tab: metrics}. We draw a batch of fresh 10,000 samples from the posterior to estimate each metric. Of course, the evaluated expressions are just approximation to the true value. In \cref{tab: extended movielens a} and \cref{tab: extended movielens b} we present the extended results. In \cref{tab: extended movielens b} we present the same values but normalized by the number of ratings in the dataset. \paragraph{Preprocess} Movielens25M originally uses a 5 point ratings system. To get binary ratings, we map ratings greater than 3 points to 1 and less than and equal to 3 to 0. \begin{table} \caption{This table has the extended results for the Movielens25M Dataset. All values are in nats. Higher is better. } \label{tab: extended movielens a} \resizebox{\textwidth}{!}{ \begin{tabular}{@{} llrllrllrll @{}} \toprule & {} & \multicolumn{3}{l}{Test LL} & \multicolumn{3}{l}{Train LL} & \multicolumn{3}{l}{Train ELBO} \\ $\approx$ \# ratings & & \multicolumn{1}{c}{2.5K} & \multicolumn{1}{c}{180K} & \multicolumn{1}{c}{18M} & \multicolumn{1}{c}{2.5K} & \multicolumn{1}{c}{180K} & \multicolumn{1}{c}{18M} & \multicolumn{1}{c}{2.5K} & \multicolumn{1}{c}{180K} & \multicolumn{1}{c}{18M} \\ Methods & {} & & & & & & & & & \\ \midrule Dense & $q_\phi^\mathrm{Joint}$ & -166.37 & & & -1373.97 & & & -1572.31 & & \\ & $q_{v,w}^{\mathrm{Branch}}$ & -166.66 & -11054.43 & -1.3046e+06 & -1374.20 & -95731.42 & -1.0315e+07 & -1572.39 & -1.0368e+05 & -1.1413e+07 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -166.64 & -10976.38 & -1.1476e+06 & -1374.27 & -95980.37 & -1.0027e+07 & -1572.45 & -1.0352e+05 & -1.0665e+07 \\[2.5mm] Block & $q_\phi^\mathrm{Joint}$ & -167.36 & & & -1375.56 & & & -1579.04 & & \\ Diagonal& $q_{v,w}^{\mathrm{Branch}}$ & -166.97 & -10987.17 & -1.2538e+06 & -1375.71 & -95891.42 & -1.0399e+07 & -1579.05 & -1.0350e+05 & -1.1078e+07 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -166.96 & -10975.96 & -1.1484e+06 & -1375.71 & -95962.56 & -1.0027e+07 & -1579.06 & -1.0353e+05 & -1.0665e+07 \\[2.5mm] Diagonal & $q_\phi^\mathrm{Joint}$ & -167.39 & & & -1377.25 & & & -1592.59 & & \\ & $q_{v,w}^{\mathrm{Branch}}$ & -167.31 & -10977.95 & -1.2713e+06 & -1377.19 & -96414.40 & -1.0709e+07 & -1592.64 & -1.0428e+05 & -1.1325e+07 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -167.29 & -10980.75 & -1.1497e+06 & -1377.20 & -96467.88 & -1.0068e+07 & -1592.64 & -1.0430e+05 & -1.0736e+07 \\ \bottomrule \end{tabular} } \end{table} \begin{table} \caption{This table has the extended results for the Movilens25M Dataset. It has the same results as in \cref{tab: extended movielens a}; however, the values are divided by the number of ratings. } \label{tab: extended movielens b} \resizebox{\textwidth}{!}{\begin{tabular}{@{} llrllrllrll @{}} \toprule & {} & \multicolumn{3}{l}{Test LL} & \multicolumn{3}{l}{Train LL} & \multicolumn{3}{l}{Train ELBO} \\ & $\approx$ \# ratings & \multicolumn{1}{c}{2.5K} & \multicolumn{1}{c}{180K} & \multicolumn{1}{c}{18M} & \multicolumn{1}{c}{2.5K} & \multicolumn{1}{c}{180K} & \multicolumn{1}{c}{18M} & \multicolumn{1}{c}{2.5K} & \multicolumn{1}{c}{180K} & \multicolumn{1}{c}{18M }\\ Methods & {} & & & & & & & & & \\ \midrule Dense & $q_\phi^\mathrm{Joint}$ & -0.5717 & & & -0.5108 & & & -0.5845 & & \\ & $q_{v,w}^{\mathrm{Branch}}$ & -0.5727 & -0.5640 & -0.6486 & -0.5109 & -0.5224 & -0.5492 & -0.5845 & -0.5658 & -0.6077 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -0.5726 & -0.5600 & -0.5705 & -0.5109 & -0.5238 & -0.5339 & -0.5846 & -0.5649 & -0.5678 \\ [2.5mm] Block & $q_\phi^\mathrm{Joint}$ & -0.5751 & & & -0.5114 & & & -0.5870 & & \\ Diagonal & $q_{v,w}^{\mathrm{Branch}}$ & -0.5738 & -0.5606 & -0.6233 & -0.5114 & -0.5233 & -0.5537 & -0.5870 & -0.5648 & -0.5898 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -0.5738 & -0.5600 & -0.5709 & -0.5114 & -0.5237 & -0.5339 & -0.5870 & -0.5650 & -0.5678 \\[2.5mm] Diagonal & $q_\phi^\mathrm{Joint}$ & -0.5752 & & & -0.5120 & & & -0.5920 & & \\ & $q_{v,w}^{\mathrm{Branch}}$ & -0.5749 & -0.5601 & -0.6320 & -0.5120 & -0.5261 & -0.5702 & -0.5921 & -0.5691 & -0.6029 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -0.5749 & -0.5602 & -0.5716 & -0.5120 & -0.5264 & -0.5360 & -0.5921 & -0.5691 & -0.5716 \\ \bottomrule \end{tabular} } \end{table} \subsection{Synthetic problem} \label{app sec: synthetic details} \paragraph{Details of the model} We use the hierarchical regression model \begin{align*} p(\theta, z, y \vert x) &= \mathcal{N}(\theta \vert 0, I) \prod_{i=1}^{N} \mathcal{N}(z_i \vert \theta, I) \prod_{j=1}^{n_i}\mathcal{N}(y_{ij} \vert x_{ij}^\top z_i, 1) \end{align*} for synthetic experiments. For simplicity, we use $n_i = 100$ for all $i$; we vary $N$ to create different scale variants---we use $N = 10$ for small scale, $N = 1000$ for moderate scale, and $N = 100000$ for large scale experiments; we set $x_{ij} \in \R^{10}$ and thus $\theta \in \R^{10}$ and $ z_i \in \R^{10}$; $y_{ij} \in \R$. \paragraph{Expression for posterior} \begin{align*} p(\theta \vert x, y) &= \mathsmaller{\displaystyle \N \Bigg(\left[I_D + \sum_i x_i^\top (I_{M_i} + x_i x_i^\top)^{-1} x_i\right]^{-1} \left[\sum_i x_i^\top (I_M + x_i x_i^\top)^{(-1)}y_i\right],} \\ & \mathsmaller{\displaystyle \phantom{Something something something ething} \left[ I_D + \sum_i x_i^\top (I_M + x_i x_i^\top)^{-1} x_i\right]^{-1}\Bigg)}\\ p(z_i \vert \theta, x_i, y_i) &= \mathsmaller{\N ([I_D + x_i^\top x_i]^{-1} [x_i^\top y_i + \theta], [I_D + x_i^\top x_i]^{-1})}\\ \end{align*} \paragraph{Expression for marginal likelihood} \begin{align*} p(y|x) & =\mathcal{N}\left(0,\begin{bmatrix}I_{M}+2x_{1}x_{1}^{\top} & \dots & x_{n}x_{1}^{\top}\\ \vdots & \ddots & \vdots\\ x_{n}x_{1}^{\top} & \dots & I_{M}+2x_{n}x_{n}^{\top} \end{bmatrix}\right)\\ \end{align*} \begin{figure*}[!h] \centering \resizebox*{\textwidth}{!}{ \begin{subfigure}[b]{\textwidth} \centering \includegraphics[trim=0 0 0 0,clip,width=\textwidth]{./figures/synthetic_full_300__train_trace_G__w_marginal_.pdf} \end{subfigure} } \resizebox*{\textwidth}{!}{ \begin{subfigure}[b]{\textwidth} \centering \includegraphics[trim=0 0 0 0,clip,width=\textwidth]{./figures/synthetic_full_300__train_trace_BG__w_marginal_.pdf} \end{subfigure} } \resizebox*{\textwidth}{!}{ \begin{subfigure}[b]{\textwidth} \centering \includegraphics[trim=0 0 0 0,clip,width=\textwidth]{./figures/synthetic_full_300__train_trace_D__w_marginal_.pdf} \end{subfigure} } \caption{ Training ELBO trace for the synthetic problem. Top to bottom: dense, block diagonal, and diagonal Gaussian (for each, we have $q_\phi^\mathrm{Joint}$, $q_{v,w}^{\mathrm{Branch}}$, and $q_{v,u}^{\mathrm{Amort}}$ method.) Left to right: small, moderate, and large scale of the synthetic problem. For clarity, we plot the exponential moving average of the training ELBO trace with a smoothing value of 0.001. For the small setting, we also plot the true log-marginal $\log p(y \vert x)$ for reference (black horizontal line): ELBO for dense approach is exactly same as the log-marginal, it's slightly lower for block, and is much less for the diagonal (see first column.) Note, calculating the log-marginal was computationally prohibitive for the moderate and large setting.} \label{fig: synthetic results} \end{figure*} \section{Introduction} Hierarchical Bayesian models are a general framework where parameters of ``groups'' are drawn from some shared distribution, and then observed data is drawn from a distribution specified by each group's parameters. After data is observed, the inference problem is to infer both the parameters for each group and the shared parameters. These models have proven useful in various domains \cite{gelman2020most} including hierarchical regression amd classification \cite{gelman2006data}, topic models \cite{blei2003latent,lafferty2006correlated,blei2012probabilistic}, polling \cite{gelman2009red,lax2012democratic}, epidemiology \cite{lawson2008bayesian}, ecology \cite{cressie2009accounting}, psychology \cite{vallerand1997toward}, matrix-factorization \cite{tipping1999probabilistic}, and collaborative filtering \cite{lim2007variational,salakhutdinov2008bayesian}. A proven technique for scaling variational inference (VI) to large datasets is subsampling. The idea is that if the target model has the form $p(z,y)=p(z)\prod_i p(y_i \vert z)$ then an unbiased gradient can be estimated while only evaluating $p(z)$ and $p(y_i \vert z)$ at a few $i$ \cite{hoffman2013stochastic,kingma2013auto,pmlr-v32-rezende14,ranganath14,titsias2014doubly,hoffman2015ssvi}. This paper addresses hierarchical models of the form $p(\theta,z,y)=p(\theta)\prod_i p(z_i, y_i \vert \theta)$, where only $y$ is observed. There are two challenges. First, the number of local latent variables $z_i$ increases with the dataset, meaning the posterior distribution increases in dimensionality. Second, there is often a dependence between $z_i$ and $\theta$ which must be captured to get strong results \cite{hoffman2015ssvi}. The aim of this paper is to develop a black-box variational inference scheme that can scale to large hierarchical models without losing benefits of a joint approximation. Our solution takes three steps. First, in the true posterior, the different latent variables $z_i$ are conditionally independent given $\theta$, which suggests using a variational family of the same form. We confirm this intuition by showing that for any joint variational family $q(\theta,z)$, one can define a corresponding "branch" family $q(\theta)\prod_i q(z_i \vert \theta)$ such that inference will be equally accurate (\cref{thm: branch q better than q for hbd}). We call inference using such a family the "branch" approach. Second, we observe that if using the branch approach, the optimal local variational parameters can be computed only from $\theta$ and local data (\cref{eq: optimal local wi}). Thus, we propose to amortize the computation of the local variational parameters by learning a network to approximately solve that optimization. We show that when the target distribution is symmetric over latent variables, this will be as accurate as the original joint family, assuming a sufficiently capable amortization network (\cref{claim: amortization}). Third, we note that in many real hierarchical models, there are many i.i.d. data generated from each local latent variable. This presents a challenge for learning an amortization network, since the full network should deal with different numbers of data points and naturally reflect the symmetry between the inputs (that is, without having to relearn the symmetry.) We propose an approach where a preliminary "feature" network processes each datum, after which they are combined with a pooling operation which forms the input for a standard network (\cref{sec: locally iid}). This is closely related to the "deep sets" \cite{deepsets} strategy for permutation invariance. We validate these methods on a synthetic model where exact inference is possible, and on a user-preference model for the MovieLens dataset with 162K users who make 25M ratings of different movies. At small scale (2.5K ratings), we show similar accuracy using a dense joint Gaussian, a branch distribution, or our amortized approach. At moderate scale (180K ratings), joint inference is intractable. Branch distributions gives a meaningful answer, and the amortized approach is comparable or better. At large scale (18M ratings) the amortized approach is thousands of nats better on test-likelihoods even after branch distributions were trained for almost ten times as long as the amortized approach took to converge (\cref{fig: real problem results}). \section{Hierarchical Branched Distributions} \label{sec: branch distributions} \begin{figure*}[ht] \begin{subfigure}[b]{0.25\textwidth} \centering \resizebox*{0.65\textwidth}{!}{ \input{./model_hbd.tex} } \end{subfigure} \hfill \begin{subfigure}[b]{0.75\textwidth} \centering \resizebox*{!}{0.35\textwidth}{ \input{./model_hbd_expanded.tex} } \end{subfigure} \caption{ The graphical model for the HBDs. On the left, we have plate notation for the generic HBD from \cref{eq: branch distributions alternate}. Note, we can have an edge from $\theta$ to $y_{ij}$ (we skip it for clarity.) On the right, we have an example model with $N=3$. } \label{fig: graph model hbd} \end{figure*} We focus on two-level hierarchical distributions. A generic model of this type is given by \begin{align} p(\theta, z, y\vert x) & = p(\theta)\prod_{i=1}^{N}p (z_i \vert \theta) p (y_{i} \vert \theta, z_i, x_{i}), \label{eq: branch distributions} \end{align} where $\theta$ and $z=\{z_i\}_{i=1}^{N}$ are latent variables, $y=\{y_i\}_{i=1}^{N}$ are observations, and $x=\{x_i\}_{i=1}^{N}\allowbreak$ are covariates. As the visual representations of these models resemble branches, we refer them as \emph{hierarchical branch distributions (HBDs)}. \paragraph{Symmetric.} \phantomsection \label{sec: symmetric HBD} We call an HBD symmetric if the conditionals are symmetric, i.e., if $z_i = z_j, x_i = x_j,$ and $y_i = y_j$, it implies that \begin{align} p(z_i \vert \theta) & = p(z_j \vert \theta) \text{, and }\nonumber\\ p(y_i \vert \theta, z_i, x_i) & = p(y_j \vert \theta, z_j, x_j). \label{eq: symmetry condition} \end{align} \paragraph{Locally i.i.d.} Often local observations $y_i$ (and $x_i$) are a collection of conditionally i.i.d observations. Then, an HBD takes the form of \begin{align} p(\theta, z, y\vert x) & = p(\theta)\prod_{i=1}^{N}p (z_i \vert \theta) \prod_{j=1}^{n_i}p (y_{ij} \vert \theta, z_i, x_{ij}), \label{eq: branch distributions alternate} \end{align} where $y_i=\{y_{ij}\}_{j=1}^{n_i}$ and $x_i = \{x_{ij}\}_{j=1}^{n_i}$ are collections of conditionally i.i.d observations and covariates; $n_i \ge 1$ is the number of observations for branch $i$. \paragraph{No local covariates.} Some applications do not involve the covariates $x_i$. In such cases, HBDs have a simplified form of \begin{align} p(\theta, z, y) & = p(\theta)\prod_{i=1}^{N}p (z_i \vert \theta) p (y_{i} \vert \theta, z_i). \end{align} In this paper, we will be using \cref{eq: branch distributions} and \cref{eq: branch distributions alternate} to refer HBDs---the results extend easily to case where there are no local covariates. (For instance, in \cref{sec: amortized dist}, we amortize using $(x_i, y_i)$ as inputs. When there are no covariates, we can amortize with just $y_i$.) \subsection{Related Work} Bayesian inference in hierarchical models is an old problem. The most common solutions are Markov chain Monte Carlo (MCMC) and VI. A key advantage of VI is that gradients can sometimes be estimated using only a subsample of data. \citet{hoffman2013stochastic} observe that inference in \emph{hierarchical} models is still slow at large scale, since the number of parameters scales with the dataset. Instead, they assume that $\theta$ and $z_i$ from \cref{eq: branch distributions} are in conjugate exponential families, and observe that for a mean-field variational distribution $q(\theta)\prod_{i} q(z_i)$, the optimal $q(z_i)$ can be calculated in closed form for fixed $q(\theta)$. This is highly scalable, though it is limited to factorized approximations and requires a conditionally conjugate target model. A structured variational approximation like $q(\theta) \prod_{i} q(z_i \vert \theta)$ can be used which reflects the dependence of $z_i$ on $\theta$ \cite{hoffman2015ssvi, sheth2016monte, ambrogioni2021automatic, johnson2016composing}. However, this still has scalability problems in general since the number of parameters grows in the size of the data (\cref{sec: experiments}). To the best of our knowledge, the only approach that avoids this is the framework of structured stochastic VI \cite{hoffman2015ssvi, johnson2016composing}, which assumes the target is conditionally conjugate, and that for a fixed $\theta$ an optimal "local" distribution $q(z_i \vert \theta)$ can be calculated from local data. \citet{hoffman2015ssvi} address matrix factorization models and latent Dirichlet allocation, using Gibbs sampling to compute the local distributions. \citet{johnson2016composing} use amortization for conjugate models but do not consider the setting where local observations are a collection of i.i.d observations. Our approach is not strictly an instance of either of these frameworks, as we do not assume conjugacy or that amortization can exactly recover optimal local distributions \cite[Eq. 7]{hoffman2015ssvi}. Still the spirit is the same, and our approach should be seen as part of this line of research. Amortized variational approximations have been used to learn models with local variables \cite{kingma2013auto,edwards2016towards,ilse2019diva,bouchacourt2018multi}. A particularly related instance of model learning is the Neural Statistician approach \cite{edwards2016towards}, where a ``statistics network'' learns representations of closely related datasets--the construction of this network is similar to our ``pooling network'' in \cref{sec: locally iid}. However, in the Neural Statistician model there are no global variables $\theta$, and it is not obvious how to generalize their approach for HBDs. In contrast, our ``pooling network'' results from the analysis in \cref{sec: amortized dist}, reducing the architectural space when $\theta$ is present while retaining accuracy. Moreover, \emph{learning} a model is strictly different from our ``black-box" setting where we want to approximate the posterior of a given model, and the inference only has access to $\log p$ or $\nabla_{\theta, z}\log p$ (or their parts) \cite{ranganath14,kucukelbir2017automatic,ambrogioni2021automatic,aagrawal2020}. \section{Joint approximations for HBD} When dealing with HBDs, a non-structured distribution does not scale. To see this, consider the naive VI objective---Evidence Lower Bound (ELBO, $\mathcal L$). Let $q_\phi^\mathrm{Joint}$ be a joint variational approximation over $\uptheta$ and $\mathsf{z}$; we use sans-serif font for random variables. Then, \begin{align} \ELBO{q_\phi^\mathrm{Joint}}{p} = \mathbb{E}_{q_\phi^\mathrm{Joint}(\uptheta, \mathsf{z})} \left[ \log \frac{p(\uptheta, \mathsf{z}, y \vert x)}{q_\phi^\mathrm{Joint}(\uptheta, \mathsf{z})} \right] , \label{eq: joitn elbo} \end{align} where $\phi$ are variational parameters. Usually the above expectation is not tractable and one uses a Monte-Carlo estimator. A single sample estimator is given by \begin{align} \widehat{\mathcal {L}} = \log \frac{p(\uptheta, \mathsf{z}, y \vert x)}{q_\phi^\mathrm{Joint}(\uptheta, \mathsf{z})} , \label{eq: joint elbo estimate} \end{align} where $(\uptheta, \mathsf{z}) \sim q_\phi^\mathrm{Joint}$ and $ \widehat{\mathcal {L}}$ is unbiased. Since $q_\phi^\mathrm{Joint}$ need not factorize, even a single estimate requires sampling all the latent variables at each step. This is problematic when there are a large number of local latent variables. One encounters the same scaling problem when taking the gradient of the ELBO. We can estimate the gradient using any of the several available estimators \cite{ranganath14, kingma2013auto,pmlr-v32-rezende14, roeder2017sticking}; however, none of them scale if $q_\phi^\mathrm{Joint}$ does not factorize \cite{hoffman2013stochastic}. \section{Branch approximations for HBD} It is easy to see that the posterior distribution of the HBD \cref{eq: branch distributions} takes the form $$ p(\theta, z \vert y, x) = p(\theta \vert y, x)\prod_{i=1}^{N}p (z_i \vert \theta, y_i, x_i) \label{eq: branch posterior}. $$ As such, it is natural to consider variational distributions that factorize the same way (see \cref{fig:q visual}.) In this section, we confirm this intuition---we start with any joint variational family which can have any dependence between $\theta$ and $z_1, \cdots, z_N$. Then, we define a corresponding ``branch'' family where $z_1, \cdots ,z_N$ are conditionally independent given $\theta$. We show that inference using the branch family will be at least as accurate as using the joint family. We formalize the idea of branch distribution in the next definition. \begin{defn} Let $q_\phi^\mathrm{Joint}$ be any variational family with parameters $\phi$. We define $q_{v,w}^{\mathrm{Branch}}$ to be a corresponding branch family if, for all $\phi$, there exists $(v, \{w_i\}_{i=1}^{N})$, such that, \begin{align} q_{v,w}^{\mathrm{Branch}}(\theta, z) = q_v(\theta) \prod_{i=1}^{N} q_{w_i} (z_i \vert \theta) = q_\phi^\mathrm{Joint} (\theta) \prod_{i=1}^{N} q_\phi^\mathrm{Joint} (z_i \vert \theta). \label{eq: q branch definition} \end{align} \label{def: branch dists} \end{defn} \begin{wrapfigure}{r}{0.25\textwidth} \vspace{0pt} \centering \resizebox*{!}{0.09\textwidth}{ \input{./model_q.tex} } \caption{$\ qb$ as in \cref{eq: q branch definition}.} \vspace{-12pt} \label{fig:q visual} \end{wrapfigure} Given a joint distribution, a branch distribution can always be defined by choosing $w$ and $v_i$ as the components of $\phi$ that influence $q_\phi^\mathrm{Joint}(\theta)$ and $q_\phi^\mathrm{Joint}(z_i \vert \theta)$, respectively, and choosing $q_w (\theta)$ and $q_{w_i}(z_i \vert \theta)$ correspondingly. However, the choice is not unique (for instance, the parameterization can require transformations---different transformations can create different variants.) The idea to use $q_{v,w}^{\mathrm{Branch}}$ is natural \cite{hoffman2015ssvi,ambrogioni2021automatic}. However, one might question if the branch variational family is as good as the original $q_\phi^\mathrm{Joint}$; in \cref{thm: branch q better than q for hbd}, we establish that this is indeed true. \begin{thm} \label{thm: branch q better than q for hbd}Let $p$ be a HBD, and $q_\phi^\mathrm{Joint}\pp{\theta,z}$ be a joint approximation family parameterized by $\phi$. Choose a corresponding branch variational family $q_{v,w}^{\mathrm{Branch}}(\theta, z)$ as in \cref{def: branch dists}. Then, \[ \min_{v,w}\KL{q_{v,w}^{\mathrm{Branch}}}p\leq\min_{\phi}\KL{q_\phi^\mathrm{Joint}}p. \] \end{thm} We stress that $q_{v,w}^{\mathrm{Branch}}$ is a new variational family derived from but not identical to $q_\phi^\mathrm{Joint}$. \Cref{thm: branch q better than q for hbd} implies that we can optimize a branched variational family $q_{v,w}^{\mathrm{Branch}}$ without compromising the quality of approximation (see \cref{app sec: proof of theorem} for proof.) In the following corollary, we apply \cref{thm: branch q better than q for hbd} to a joint Gaussian to show that using a branch Gaussian will be equally accurate. \begin{cor} \label{cor: branch gaussian} Let $p$ be a HBD, and let \( q_\phi^\mathrm{Joint}\pp{\theta,z}=\N\pars{\pp{\theta,z}\vert\mu,\Sigma} \) be a joint Gaussian approximation (with $\phi=\pp{\mu,\Sigma}$). Choose a variational family \[ q_{v,w}^{\mathrm{Branch}}\pp{\theta,z}=\N\pp{\theta\vert\mu_{0},\Sigma_0}\prod_{i=1}^N \N\pp{z_{i}\vert\mu_{i}+A_{i}\theta,\ \Sigma_i} \] with $v=\pp{\mu_{0},\Sigma_{0}}$ and $w_{i}=\pp{\mu_{i},\Sigma_{i},A_{i}}.$ Then, $\displaystyle \min_{v,w}\KL{q_{v,w}^{\mathrm{Branch}}}p\leq\min_{\phi}\KL{q_\phi^\mathrm{Joint}}p.$ \end{cor} In the above corollary, the structured family $q_{v,w}^{\mathrm{Branch}}$ is chosen such that it can represent any branched Gaussian distribution. Notice, the mean of the conditional distribution is an affine function of $\theta$. This affine relationship appears naturally when you factorize the joint Gaussian over $\left(\uptheta,\mathsf{z}\right)$. For more details see \cref{app sec: derivation of branch gaussian}. \begin{figure*}[!h] \centering \hspace{-40pt} \hspace{-10pt} \subcaptionbox{Estimation with $q_\phi^\mathrm{Joint}$ as in \cref{eq: joint elbo estimate}\label{fig: pseudocode joint}} [0.5\linewidth]{ \resizebox*{0.175\textwidth}{!}{ \hspace{-50pt} \begin{minipage}[t][0.105\textheight]{0.3\textwidth} \begin{algorithmic} \State \texttt{JointELBO}$(\phi, y, x)$ \State \hspace{5mm}$\theta, z \sim q_\phi^\mathrm{Joint}(\uptheta, \mathsf{z})$ \State \hspace{5mm}{${\displaystyle \widehat{\mathcal L} \gets \log \frac{p(\theta, z, y \vert x)}{q_\phi^\mathrm{Joint} (\theta, z)} }$} \end{algorithmic} \end{minipage} }} \subcaptionbox{ Estimation with $q_{v,w}^{\mathrm{Branch}}$ as in \cref{eq: branch elbo estimate} \label{fig: pseudocode branch}} [0.5\linewidth]{ \resizebox*{0.425\textwidth}{!}{ \begin{minipage}[t][0.105\textheight]{0.45\textwidth} \begin{algorithmic} \State \texttt{BranchELBO}$(v, w, y, x)$ \State \hspace{5mm}$\theta \sim q_{v}(\uptheta)$ \State \hspace{5mm}$z_i \sim q_{w_i}(\mathsf{z}_i \vert \theta)$ for $i \in \{1, \cdots, N\}$. \State \hspace{5mm}{${\displaystyle \widehat{\mathcal{L}} \gets \log\frac{p\left(\theta\right)}{q_v \left(\theta\right)}+\sum_{i = 1}^{N}\log\frac{p\left(z_{i},y_{i}\vert\theta,x_{i}\right)}{q_{w_i}\left(z_{i}\vert\theta\right)} }$} \end{algorithmic} \end{minipage} }} \vspace{10pt} \\ \hspace{-30pt} \subcaptionbox{Estimation with $q_{v,w}^{\mathrm{Branch}}$ as in \cref{eq: branch susbsamples elbo estimate} \label{fig: pseudocode branch subsampled}} [0.48\linewidth]{ \resizebox*{0.45\textwidth}{!}{ \begin{minipage}[t][0.125\textheight]{0.49\textwidth} \begin{algorithmic} \State \texttt{SubSampledBranchELBO}$(v, w, y, x)$ \State \hspace{5mm}$\theta \sim q_{v}(\uptheta)$ \State \hspace{5mm}$B \sim \texttt{Minibatch($\mathsf{B}$)}$ \State \hspace{5mm}$z_i \sim q_{w_i}(\mathsf{z}_i \vert \theta)$ for $i \in B$ \State \hspace{5mm}{${\displaystyle \widehat{\mathcal{L}} \gets \log\frac{p\left(\theta\right)}{q_v \left(\theta\right)}+\frac{N}{\verts{B}}\sum_{i\in B}\log\frac{p\left(z_{i},y_{i}\vert\theta,x_{i}\right)}{q_{w_i}\left(z_{i}\vert\theta\right)} }$} \end{algorithmic} \end{minipage} } } \hspace{0pt} \subcaptionbox{\label{fig: pseudocode amort}Estimation with $q_{v,u}^{\mathrm{Amort}}$ for $p$ as in \cref{eq: symmetry condition}} [0.48\linewidth]{ \resizebox*{0.45\textwidth}{!}{ \begin{minipage}[t][0.125\textheight]{0.49\textwidth} \begin{algorithmic} \State \texttt{AmortizedSubSampledBranchELBO}$(v, u, y, x)$ \State \hspace{5mm}$\theta \sim q_{v}(\uptheta)$ \State \hspace{5mm}$B \sim \texttt{Minibatch($\mathsf{B}$)}$ \State \hspace{5mm}$w_i \gets {\normalfont \texttt{net}}_u (x_i, y_i )$ for $i \in B$ \State \hspace{5mm}$z_i \sim q_{w_i}(\mathsf{z}_i \vert \theta)$ for $i \in B$ \State \hspace{5mm}{${\displaystyle \widehat{\mathcal{L}} \gets \log\frac{p\left(\theta\right)}{q_v \left(\theta\right)}+\frac{N}{\verts{B}}\sum_{i\in B}\log\frac{p\left(z_{i},y_{i}\vert\theta,x_{i}\right)}{q_{w_i}\left(z_{i}\vert\theta\right)} }$} \end{algorithmic} \end{minipage} }} \caption{Pseudo codes for ELBO estimation with different variational methods; $w=\{w_i\}_{i=1}^N$, $y = \{y_i\}_{i=1}^{N}$, and $y_i = \{y_{ij}\}_{j=1}^{n_i}$ ($x$ is defined similar to $y$.) (a) Estimates ELBO for a joint approximation; (b) to (d) estimate ELBO for branch approximations; (c, d) use subsampling to estimate ELBO; (d) uses amortized conditionals; (a) to (c) work for any HBD, and (d) assumes $p$ is a symmetric HBD as in \cref{eq: symmetry condition}. For models where $n_i > 1$, we use the ${\normalfont \texttt{net}}_u$ as in \cref{fig: featnet}. \texttt{Minibatch} is some distribution over the set of possible minibatches and $\verts{B}$ denotes the number of samples in a minibatch $B$. \label{fig: pseudocodes} } \end{figure*} \subsection{Subsampling in branch distributions} In this section, we show that if $p$ is an HBD and $q_{v,w}^{\mathrm{Branch}}$ is as in \cref{def: branch dists}, we can estimate ELBO using local observations and scale better. Consider the ELBO \begin{align} \ELBO{q_{v,w}^{\mathrm{Branch}}}{p} & =\E_{q_{v,w}^{\mathrm{Branch}}\left(\uptheta,\mathsf{z}\right)}\left[\log\frac{p\left(\uptheta,\mathsf{z},y\vert x\right)}{q_{v,w}^{\mathrm{Branch}}\left(\uptheta,\mathsf{z}\right)}\right] \nonumber\\ & =\E_{q_{v}\left(\uptheta\right)}\left[\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}\right]+\sum_{i=1}^{N}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\theta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\theta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\theta\right)}\right]. \label{eq: branch elbo decomposition} \end{align} Without assuming special structure (e.g. conjugacy) the above expectations will not be available in closed form. To estimate the ELBO, let $(\uptheta,\left\{ \mathsf{z}_{i}\right\} _{i=1}^{N})\sim q_{v,w}^{\mathrm{Branch}}$. Then, an unbiased estimator is \begin{align} \widehat{\mathcal{L}} & =\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}+\sum_{i=1}^N\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right]. \label{eq: branch elbo estimate} \end{align} Unlike the joint estimator of \cref{eq: joint elbo estimate}, one can subsample the terms in \cref{eq: branch elbo estimate} to create a new unbiased estimator. Let\textbf{ $\mathsf B$} be randomly selected minibatch of indices from $\{1,2,\dots,N\}$. Then, \begin{align} \widehat{\mathcal{L}} & =\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}+\frac{N}{\verts{\mathsf{B}}}\sum_{i\in \mathsf B}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right], \label{eq: branch susbsamples elbo estimate} \end{align} is another unbiased estimator of ELBO. In \cref{sub@fig: pseudocode branch,,sub@fig: pseudocode branch subsampled}, we present the complete pseudocodes for ELBO estimation with and without subsampling in branch distributions. Unsurprisingly, the same summation structure appears for gradients estimators of branch ELBO, allowing for efficient gradient estimation. With subsampled evaluation and training, branch distributions are immensely computationally efficient---in our experiments, we scale to models with $10^3$ \emph{times} more latent variables by switching to branch approximations (see \cref{fig: real problem results}). While branch distributions are immensely more scalable than joint approximations, the number of parameters still scales as $\mathcal O (N)$. In the next section, we demonstrate that for symmetric HBDs, we can share parameters for the local conditionals (amortize) to allow further scalability. \section{Amortized branch approximations} \label{sec: amortized dist} In this section, we discuss how one can amortize the local conditionals of a branch approximations when the target HBD is symmetric (see \cref{eq: symmetry condition}.) We first formally introduce the amortized branch distributions in the next definition and then justify the amortization for symmetric HBD. \begin{defn} Let $q_\phi^\mathrm{Joint}$ be a joint approximation and let $q_{v,w}^{\mathrm{Branch}}$ be as in \cref{def: branch dists}. Suppose ${\normalfont \texttt{net}}_u(x_i, y_i)$ is some parameterized map (with parameters $u$) from local observations $(x_i, y_i)$ to space of $w_i$. Then, \begin{align} q_{v,u}^{\mathrm{Amort}} (\theta, z) = q_v (\theta) \prod_{i=1}^{N} q_{{\normalfont {\normalfont \texttt{net}}}_u(x_i, y_i)}(z_i \vert \theta) \end{align} is a corresponding amortized branch distribution. \label{def: amort branch dist} \end{defn} The idea to amortize is natural once you examine the optimization for symmetric HBDs. Consider the optimization for objective in \cref{eq: branch elbo decomposition}. \begin{align*} \max_{v,w}\ELBO{q_{v,w}^{\mathrm{Branch}}}p &=\max_{v,w} \bracs{\E_{q_{v}\left(\uptheta\right)}\left[\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}\right]+\sum_{i=1}^{N}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right]}\\ & =\max_v \bracs{\E_{q_{v}\left(\uptheta\right)}\left[\log\frac{p\left(\uptheta\right)}{q_{v}\left(\uptheta\right)}\right]+\sum_{i=1}^{N}\max_{w_i}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right]}. \end{align*} The crucial observation in the above equation is that for any given $v$, the optimal solution of inner optimization depends only on local data points $\left(x_{i},y_{i}\right)$, i.e., \begin{align} w^*_i &= \argmax_{w_i}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right ]. \label{eq: optimal local wi} \end{align} Now, notice that if $p$ and $q_{v,w}^{\mathrm{Branch}}$ have symmetric conditionals, then, for each $i$, we solve the same optimization over $w_{i}$, just with different parameters $y_i$ and $x_i$. Thus, one could replace the optimization over $w_i$ with an optimization over a parameterized function from $(x_i, y_i)$ to the space of $w_i$. Formally, when the network ${\normalfont \texttt{net}}_u$ is sufficiently capable, we make the following claim. \begin{claim} Let $p$ be a symmetric HBD and let $q_\phi^\mathrm{Joint}$ be some joint approximation. Let $q_{v,u}^{\mathrm{Amort}}$ be as in \cref{def: branch dists}. Suppose that for all $v$, there exists a $u$, such that, \begin{align} {\normalfont {\normalfont \texttt{net}}}_u (x_i, y_i) = \argmax_{w_i}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right ]. \end{align} Then, \begin{align} \min_{v, u} \KL{q_{v,u}^{\mathrm{Amort}}}p \le \min_{\phi} \KL{q_\phi^\mathrm{Joint}}p \end{align} \label{claim: amortization} \end{claim} Note, we only amortize the conditional distribution $q_{w_{i}}\left(z_{i}\vert\theta\right)$ and leave $q_{v}\left(\theta\right)$ unchanged. In practice, of course, we do not have perfect amortization functions. The quality of the amortization depends on our ability to parameterize and optimize a powerful neural network. In other words, we make the following approximation \begin{align} {\normalfont {\normalfont \texttt{net}}}_u (x_i, y_i) \approx \argmax_{w_i}\E_{q_{v}\left(\uptheta\right)}\E_{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\left[\log\frac{p\left(\mathsf{z}_{i},y_{i}\vert\uptheta,x_{i}\right)}{q_{w_{i}}\left(\mathsf{z}_{i}\vert\uptheta\right)}\right ]. \end{align} In our experiments, we found the amortized approaches work well even with moderately sized networks. Due to parameter sharing, the amortized approaches converge much faster than other alternatives (especially, true for larger models; see \cref{fig: real problem results} and \cref{tab: movielens results}). \section{Amortized branch approximations for i.i.d. observations} \label{sec: locally iid} In the previous section, we discussed how we could amortize branch approximations for symmetric HBDs. However, in some applications, the construction of amortization network ${\normalfont \texttt{net}}_u$ is not as straightforward. Consider the case when we have a varying number of local i.i.d observations for each local latent variable. In this section, we highlight the problem with naive amortization for locally i.i.d HBDs, and present a simple solution to alleviate them. Mathematically, for locally i.i.d HBDs we have $y_{i} = \{y_{ij}\}_{j=1}^{n_i}$ and $x_i = \{x_{ij}\}_{j=1}^{n_i}$, such that the conditional over $y_i$ factorizes as \[ p\left(y_{i}\vert x_{i},z_{i},\theta\right)=\prod_{j=1}^{n_{i}}p\left(y_{ij}\vert x_{ij},z_{i},\theta\right). \] Now, if $x_{i}$ and $y_{i}$ are directly input to the amortization network ${\normalfont \texttt{net}}_u$, the input size to the network would change for different $i$ (notice we have $n_{i}$ observations for $i^{\text{th}}$ local variable.) Another problem is that the optimal variational parameters are invariant to the order in which the i.i.d. observations are presented. For instance, consider two data points: $(x_i, y_i) = [(x_{i1}, y_{i1}), \dots, (x_{i n_i}, y_{i n_i})]$ and $(x'_i, y'_i) = [(x_{i n_i}, y_{i n_i}), \dots, (x_{i1}, y_{i1})]$. A naive amortization scheme will evaluate very different conditionals for these two data points because ${\normalfont \texttt{net}}_u (x_i, y_i)$ and ${\normalfont \texttt{net}}_u (x'_i, y'_i)$ will be different. \begin{wrapfigure}{r}{0.33\textwidth} \vspace{-0pt} \begin{algorithmic} \State ${\normalfont \texttt{net}}_u(x_i, y_i)$ \State \hspace{5mm}\textbf{for} {$j$\textbf{ in }$\{1, 2, \dots, n_i\}$} \State \hspace{5mm}\hspace{5mm}\resizebox{0.7\hsize}{!}{$e_j \gets \texttt{feat\_net}_u (x_{ij}, y_{ij})$} \State \hspace{5mm}$e \gets \texttt{pool}(\{e_j\}_{j=1}^{n_i})$ \State \hspace{5mm}$w_i \gets \texttt{param\_net}_u (e)$ \State \hspace{5mm}\textbf{return} $w_i$ \end{algorithmic} \caption{Psuedocode for ${\normalfont \texttt{net}}_u$ for locally i.i.d symmetric HBD. \label{fig: featnet}} \vspace{-10pt} \end{wrapfigure} To deal with both issues: variable length input and permutation invariance, we suggest learning a ``feature network'' and "pooling function" based amortization network; this is reminiscent of "deep sets" \cite{deepsets} albeit here intended not just to enforce permutation invariance but also to deal with inputs of different sizes. Firstly, a feature network \texttt{feat\_net} takes each $\pp{x_{ij},y_{ij}}$ pair and returns a vector of features $e_j$. Secondly, a pooling function \texttt{pool} takes the collection $\{e_j\}_{j=1}^{n_i}$ and achieves the two aims. First, it collapses $n_i$ feature vectors into a single fixed-sized feature $e$ (with the same dimensions as $e_j$). Second, pooling is invariant by construction to the order of observations (for example, pooling function would take a dimension-wise mean or sum across $j$.) Finally, this pooled feature vector $e$ is input to another network \texttt{param\_net} that returns the final parameters $w_{i}$. The pseudocode for a ${\normalfont \texttt{net}}_u$ with feature networks is available in \cref{fig: featnet}. In \cref{tab: method applicability}, in appendix, we summarize the applicability of proposed variational methods to different HBD variants. \begin{table}[t] \caption{All variational families used in our experiments. $\Sigma$ denotes a generic covariance matrix and $\sigma^2$ denotes a diagonal covariance.} \label{tab: methods summary} \begin{center} \resizebox*{\textwidth}{!}{ \begin{tabular}[!h]{@{} llll @{}} \toprule \textbf{Gaussian Family} & $q_\phi^\mathrm{Joint}$ as in \cref{eq: joitn elbo} & $q_{v,w}^{\mathrm{Branch}}$ as in \cref{eq: q branch definition} & $q_{v,u}^{\mathrm{Amort}}$ as in \cref{def: amort branch dist}\\ \midrule Dense & $\N (\theta, z \vert \mu, \Sigma)$ & \resizebox{0.35\hsize}{!}{$\mathsmaller{\displaystyle \N (\theta \vert \mu_0, \Sigma_0) \prod_{i=1}^{N} \N (z_i \vert \mu_i + A_i \theta, \Sigma_i)}$} & \resizebox{0.35\hsize}{!}{${\displaystyle \N (\theta \vert \mu_0, \Sigma_0) \prod_{i=1}^{N} \N (z_i \vert \mu_i + A_i \theta, \Sigma_i)}$}\\ & {\small $\phi = (\mu, \Sigma)$}& {\small $v = (\mu_0, \Sigma_0)$, $w_i = (\mu_i, A_i, \Sigma_i)$}& {\small $v = (\mu_0, \Sigma_0), (\mu_i, A_i, \Sigma_i) = {\normalfont \texttt{net}}_{u}(x_i, y_i)$}\\[1.5mm] Block Diagonal & $\N (\theta \vert \mu_0, \Sigma_0)\N (z \vert \mu_1, \Sigma_1)$ & \resizebox{0.3\hsize}{!}{${\displaystyle \N (\theta \vert \mu_0, \Sigma_0) \prod_{i=1}^{N} \N (z_i \vert \mu_i, \Sigma_i)}$} & \resizebox{0.3\hsize}{!}{${\displaystyle \N (\theta \vert \mu_0, \Sigma_0) \prod_{i=1}^{N} \N (z_i \vert \mu_i, \Sigma_i)}$}\\ & {\small $\phi = (\mu_0, \mu_1, \Sigma_0, \Sigma_1)$}& {\small $v = (\mu_0, \Sigma_0)$, $w_i = (\mu_i, \Sigma_i)$} & {\small $v = (\mu_0, \Sigma_0) \text{, }(\mu_i, \Sigma_i) = {\normalfont \texttt{net}}_{u}(x_i, y_i)$}\\[1.5mm] Diagonal & $\N (\theta, z \vert \mu, \sigma^2)$ & \resizebox{0.3\hsize}{!}{${\displaystyle \N (\theta \vert \mu_0, \sigma_0^2) \prod_{i=1}^{N} \N (z_i \vert \mu_i, \sigma_i^2)}$} & \resizebox{0.3\hsize}{!}{${\displaystyle \N (\theta \vert \mu_0, \sigma^2_0) \prod_{i=1}^{N} \N (z_i \vert \mu_i, \sigma^2_i)}$}\\[1.5mm] & {\small $\phi = (\mu, \sigma^2)$}& {\small $v = (\mu_0, \sigma^2_0)$, $w_i = (\mu_i, \sigma_i^2)$}& {\small $v = (\mu_0, \sigma_0^2)$, $(\mu_i, \sigma_i^2) = {\normalfont \texttt{net}}_{u}(x_i, y_i)$}\\ \bottomrule \end{tabular} } \end{center} \end{table} \section{Experiments} \label{sec: experiments} \begin{wrapfigure}{r}{0.32\textwidth} \vspace{-12pt} \centering \includegraphics[trim = 130 600 120 10, width=0.2\textwidth]{./figures/covariance_visualization.pdf} \caption{ Visualization of covariances of dense, block-diagonal, and diagonal Gaussians. For each, we experiment with $q_\phi^\mathrm{Joint}$, $q_{v,w}^{\mathrm{Branch}}$, and $q_{v,u}^{\mathrm{Amort}}$ methods.} \vspace{-22pt} \label{fig:cov visual} \end{wrapfigure} We conduct experiments on a synthetic and a real-world problem. For each, we consider three inference methods: using a joint distribution, using a branch variational approximation, and using our amortized approach. For each method, we consider three variational approximations a completely diagonal Gaussian, a block-diagonal Gaussian (with blocks for $\theta$ and $z$) and a dense Gaussian; see \cref{fig:cov visual} for a visual. (For each choice of a joint distribution, the corresponding $q_{v,w}^{\mathrm{Branch}}$ is used for the branch variational approximation and the corresponding $q_{v,u}^{\mathrm{Amort}}$ for the amortized approach; see \cref{tab: methods summary} for details.) We use reparameterized gradients \cite{kingma2013auto} and optimize with Adam \cite{kingma2014adam} (see \cref{app sec: experimental details} for complete experimental details.) In \cref{app sec: practicaL challenges}, we discuss some of the observations we had during experimentation involving parameterization, \texttt{feat-net} architecture, batch-size selection, initialization, and gradient estimators. \subsection{Synthetic problem} The aim of the synthetic experiment is to work with models where we have access to closed-form posterior (and the marginal likelihood.) If the variational family contains the posterior, one can expect the methods to perform close to ideal (provided we can optimize well.) For our experiments, we use the following hierarchical regression model \begin{align} p(\theta, z, y \vert x) &= \mathcal{N}(\theta \vert 0, I) \prod_{i=1}^{N} \mathcal{N}(z_i \vert \theta, I) \prod_{j=1}^{n_i}\mathcal{N}(y_{ij} \vert x_{ij}^\top z_i, 1), \end{align} where $\mathcal{N}$ denotes a Gaussian distribution, and $I$ is an identity matrix (see \cref{app sec: synthetic details} for posterior and the marginal closed-form expressions.) To demonstrate the performance of our methods, we experiment with three different problems scale (correspond to three different models with $N =$ 10, 1K, and $100$K.) Synthetic data is created using forward sampling for each of the scale variants independently. We avoid any test data and metrics for the synthetic problem as the log-marginal is known in closed form. The inference results are present in \cref{fig: synthetic results} (in appendix.) In all cases, amortized distributions perform favorably when compared to branch and joint distributions. \begin{table}[b] \centering \caption{ Inference results for the MovieLens25M problem. For both metrics, we draw a fresh batch of 10,000 samples from the final posterior. All values are in nats (higher is better). \vspace{7pt}} \label{tab: movielens results} \resizebox*{0.9\textwidth}{!}{ \begin{tabular}[h]{@{} ll rrr rrr @{}} \toprule \multicolumn{2}{@{}l@{}}{Metric} & \multicolumn{3}{c}{Final ELBO} & \multicolumn{3}{c}{Test likelihood}\\ \multicolumn{2}{@{}l@{}}{$\approx$ \# train ratings} & 2.5K & 180K & 18M & 2.5K & 180K & 18M\\[2.5mm] \multicolumn{2}{@{}l@{}}{Methods (see \cref{tab: methods summary})} & \multicolumn{6}{l}{}\\ \midrule Dense & $q_\phi^\mathrm{Joint}$ & -1572.31 & & & -166.37 & & \\ & $q_{v,w}^{\mathrm{Branch}}$ & -1572.39 & -1.0368e+05 & -1.1413e+07 & -166.66 & -11054.43 & -1.3046e+06 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -1572.45 & -1.0352e+05 & -1.0665e+07 & -166.64 & -10976.38 & -1.1476e+06 \\[3mm] Block & $q_\phi^\mathrm{Joint}$ & -1579.04 & & & -167.36 & & \\ Diagonal & $q_{v,w}^{\mathrm{Branch}}$ & -1579.05 & -1.0350e+05 & -1.1078e+07 & -166.97 & -10987.17 & -1.2538e+06 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -1579.06 & -1.0353e+05 & -1.0665e+07 & -166.96 & -10975.96 & -1.1484e+06 \\[3mm] Diagonal & $q_\phi^\mathrm{Joint}$ & -1592.59 & & & -167.39 & & \\ & $q_{v,w}^{\mathrm{Branch}}$ & -1592.64 & -1.0428e+05 & -1.1325e+07 & -167.31 & -10977.95 & -1.2713e+06 \\ & $q_{v,u}^{\mathrm{Amort}}$ & -1592.64 & -1.0430e+05 & -1.0736e+07 & -167.29 & -10980.75 & -1.1497e+06 \\ \bottomrule \end{tabular} } \end{table} \subsection{MovieLens} Next, we test our method on the MovieLens25M \cite{harper2015movielens}, a dataset of 25 million movie ratings for over 62,000 movies, rated by 162,000 users, along with a set of features (tag relevance scores \cite{vig2012tag}) for each movie. Purely, to make experiments more efficient on GPU hardware, we pre-process the data to drop users with more than 1,000 ratings---leaving around $20$M ratings. Also, for the sake of efficiency, we PCA the movie features to reduce their dimensionality to 10. We used a train-test split such that, for each user, one-tenth of the ratings are in the test set. This gives us $\approx$ 18M ratings for training (and $\approx$ 2M ratings for testing.) \begin{figure*}[!h] \centering \resizebox*{\textwidth}{!}{ \begin{subfigure}[b]{\textwidth} \centering \includegraphics[trim=0 0 0 0,clip,width=\textwidth]{./figures/movielens_gaussian_004__train_trace.pdf} \end{subfigure} } \resizebox*{\textwidth}{!}{ \begin{subfigure}[b]{\textwidth} \centering \includegraphics[trim=0 0 0 0,clip,width=\textwidth]{./figures/movielens_blockgaussian_007__train_trace.pdf} \end{subfigure} } \resizebox*{\textwidth}{!}{ \begin{subfigure}[b]{\textwidth} \centering \includegraphics[trim=0 0 0 0,clip,width=\textwidth]{./figures/movielens_diagonal_003__train_trace.pdf} \end{subfigure} } \caption{ Training ELBO trace for the MovieLens25M problem. Top to bottom: dense, block diagonal, and diagonal Gaussian (for each, we have $q_\phi^\mathrm{Joint}$, $q_{v,w}^{\mathrm{Branch}}$, and $q_{v,u}^{\mathrm{Amort}}$ method.) Left to right: small, moderate, and large scale of the MovieLens25M problem. For clarity, we plot the exponential moving average of the training ELBO trace with a smoothing value of 0.001. These traces correspond to the values reported in \cref{tab: movielens results}.} \label{fig: real problem results} \end{figure*} We use the hierarchical model \begin{align} p(\theta, z, y \vert x) &= \mathcal{N}(\theta \vert 0, I) \prod_{i=1}^{N} \mathcal{N}(z_i \vert \mu(\theta), \Sigma(\theta)) \prod_{j=1}^{n_i}\mathcal{B}(y_{ij} \vert \mathrm{sigmoid} (x_{ij}^\top z_i) ), \end{align} where $\theta$ represents distribution over user preferences; for instance, $\theta$ might represent that users who like action films tend to also like thrillers but tend to dislike musicals; $z_i$ determine the user specific preference; $x_{ij}$ are the features of the $j^{\mathrm {th}}$ movie rated by user $i$; $y_{ij}$ is the binary movie ratings; $n_i$ is the number of movies rated by user $i$, and $\mathcal{B}$ denotes a Bernoulli distribution. Here, $\mu$ and $\Sigma$ are functions of $\theta$, such that, for $\theta=[\theta_\mu, \theta_\Sigma]$, we have $$ \mu(\theta) = \theta_\mu, \quad \quad\text{ and } \quad \quad \Sigma(\theta) = \mathrm{tril}(\theta_\Sigma)^\top \mathrm{tril}(\theta_\Sigma) $$ where $\mathrm{tril}$ is a function that transforms an unconstrained vector into a lower-triangular positive Cholesky factor. As movie features $x_{ij}\in \R^{10}$, we have $\theta_\mu \in \R^{10}, \theta_\Sigma \in \R^{55}$, and $z_i \in \R^{10}$. Note that as $\Sigma$ depends on $\theta$, and the likelihood is Bernoulli, the model is non-conjugate. For inference, we use the methods as described in \cref{tab: methods summary}. Note, we hold the amortization network architecture constant across the scales--the number of parameters remains fixed for $q_{v,u}^{\mathrm{Amort}}$ (for all Gaussian variants) while the number of parameters scale as $\mathcal{O} (N)$ for $q_{v,w}^{\mathrm{Branch}}$ (see \cref{app sec: derivation of branch gaussian} for more details.) In \cref{fig: real problem results}, we plot the training time ELBO trace, and in \cref{tab: movielens results}, we present the final training ELBO and test likelihood values. We approximate the test likelihood $p(y^{\mathrm{test}} \vert x^{\mathrm{test}}, x, y)$ with $\mathbb{E}_q \left[ p(y^{\mathrm{test}} \vert x^{\mathrm{test}}, q) \right]$, and draw a fresh batch of 10,000 samples to approximate the expectation (see \cref{app sec: experimental details} for complete details.) For the smaller model, the amortized and branch approaches perform similar to the joint approach for all three variational approximations; this supports \cref{thm: branch q better than q for hbd} and \cref{claim: amortization}. For the moderate size model, the branch and amortize approaches are very comparable to each other, while joint approaches fail to scale. For the large model (18M ratings), amortized approaches are significantly better than branch methods. We conjecture this is because parameter sharing in amortized approaches improves convergence for models where batch size is smaller compared to total iterates--true only for large model. Interestingly, the performance of amortized Dense and Block Gaussian approximation is very similar in the large and moderate setting (see $q_{v,u}^{\mathrm{Amort}}$ results in \cref{tab: movielens results,tab: extended movielens a,tab: extended movielens b}.) We conjecture this is because the posterior over the global parameters is very concentrated for this problem. As $\theta$ behaves like a single fixed value, Block Gaussian performs just as good as the Dense approach (see \cref{app sec: tradeoffs} for more discussion.) \section{Discussion} In this paper, we present structured amortized variational inference scheme that can scale to large hierarchical models without losing benefits of joint approximations. Such models are ubiquitous in social sciences, ecology, epidemiology, and other fields. Our ideas can not only inspire further research in inference but also provide a formidable baseline for applications. \section*{Acknowledgements and Disclosure of Funding} This material is based upon work supported in part by the National Science Foundation under Grant No. 1908577.
{'timestamp': '2021-11-08T02:04:27', 'yymm': '2111', 'arxiv_id': '2111.03144', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03144'}
arxiv
\section{Introduction} Inferring causal relations from data is a central goal in any empirical science. Yet, in spite of its importance, causality has remained a thorny issue. Misled by the commonplace sentence stating that ``\emph{correlation does not imply causation}'', causal inference persists in the view of many as a noble but practically impossible task. Contrary to that, however, the surge and development of the causality theory \cite{pearl2009causality,spirtes2000causation} has proven formal conditions under which cause and effect relations can be extracted. Consider the simplest and fundamental question of deciding whether observed correlations between two variables, $A$ (also known as treatment) and $B$ (also known as effect), are due to some direct causal influence of the first over the second, or due to a common cause, a third, potentially latent (non-observable) variable $\Lambda$. Both causal models are observationally equivalent, meaning that both models can generate the same set of possible correlations observed between the target variables. Notwithstanding, causal conclusions can be reached if, instead of passively observing the events, we perform interventions \cite{pearl2009causality,Balke1997,janzing2013quantifying}. In particular, interventions on $A$ put this variable under the experimenter's control, turning it independent of any latent common cause. If after the intervention, one still observers correlations between $A$ and $B$, then it is possible to unambiguously conclude that $A$ is a cause of $B$. Interventions, however, are often unavailable for a variety of practical, fundamental, or ethical issues. An elegant way to circumvent such issues are the instrumental variables \cite{pearl2009causality,wright1928tariff,angrist1996identification,greenland2000introduction,rassen2009instrumental,hernan2006instruments,lousdal2018introduction,Kedagni2020}. If a proper instrument $X$, correlated with $A$ but statistically independent of $\Lambda$, can be found, then the causal effect of $A$ over $B$ can be estimated even in the absence of interventions or structural equations. Nevertheless, since the instrumental conditions depend on an unobservable variable, identifying an instrument seems to be a matter of judgment that cannot be supported solely by the data. To cope with that, instrumental inequalities have been introduced \cite{pearl1995testability,bonet2013instrumentality,poderini2020exclusivity}, constraints that should be respected by any experiment in compliance with the instrumental assumptions. Thus, the violation of instrumental inequality is an explicit proof that one does not have a proper instrument. Does that mean, however, that no causal inference at all can be made if an instrumental inequality is violated? Or can we still rely on that instrument, even though imperfect, to infer causal relations? Motivated by these questions, we analyze in detail a generalization of the instrumental causal structure, where we drop the assumption that one has a perfect instrument. More specifically, we relax the assumption that the instrumental variable $X$ should be independent of the latent factor $\Lambda$. Considering the case where $A$ and $B$ are dichotomic and $X$ is also discrete, we derive new instrumental inequalities that take explicitly into account the correlation between $X$ and $\Lambda$. We also generalize the bounds on the average causal effect (ACE) \cite{pearl2009causality,Balke1997,janzing2013quantifying} for more general instruments. Finally, we make a connection with the field of quantum foundations, where violation of instrumental inequalities can appear without relaxing the measurement independence assumption~\cite{hall2016significance,Hall2020,chaves2015unifying,chaves2021causal}. Using our results, we establish the minimal measurement dependence needed in the classical instrumental scenario to explain such violations and, as a result, we analyze the robustness of instrumental tests as witnesses of non-classical behavior. The paper is organized as follows. In Sec.~\ref{sec2} we discuss how instrumental variables can be employed to put lower bounds on the cause and effect relations between two variables. In Sec.~\ref{sec3} we discuss the violations of independence assumption and how modified instrumental inequalities and causal bounds on ACE can be derived to take that into account. In Sec.~\ref{sec4} we discuss quantum violations of the modified inequalities. In Sec.~\ref{sec5} we discuss our findings and point out interesting questions for future research. \textbf{Notations:} Throughout the paper, we denote random variables by capital letters $A,B,X$ and $\Lambda$, as well as $\Lambda_X$,$\Lambda_A$,$\Lambda_B$. Without loss of generally, we consider these random variables taking values in the set of non-negative integers $\mathds{Z}_{0+}$. Probability of an event $E$ is denoted as $p(E)$. We use a common shorthand notation $p(a)=p(A=a)$ to denote the probability of $A$ taking value $a$. Similar shorthand notation is used for conditional probabilities, e.g., $p(a|x) = p(A=a|X=x)$, and interventions, e.g., $p(b|\mathrm{do}(a)) = p(B=b|\mathrm{do}(A=a))$. We use one exception to this rule for probabilities of the form $p(i,j|k)$ and $p(l|\mathrm{do}(m))$, which should be read as $p(A=i,B=j|X=k)$ and $p(B=l|\mathrm{do}(A=m))$, respectively, for any $i,j,k,l,m\in \mathds{Z}_{0+}$. We also use the common notation $[n] = \{0,1,\dots,n-1\}$. \section{Instrumental variables, instrumental inequalities and causal bounds} \label{sec2} Before getting into details and illustrating the power of an instrumental variable as a causal inference tool, we discuss a simple linear structural model, $b=\beta a+ \lambda$, where $\beta$ can be understood as the strength of the causal influence of $A$ over $B$ and $\Lambda$ is a latent factor that might affect both $A$ and $B$. By introducing the instrumental variable $X$ and assuming its statistical independence from $\Lambda$, one can infer the causal strength $\beta$. For that aim, it is enough to multiply both sides of the structural equation by $x$ and compute the observed correlations, defined as $\mathrm{corr}(A,B)=\langle A,B \rangle / \langle A \rangle \langle B \rangle$ where $\langle A,B \rangle=\sum_{a,b}( a\cdot b) p(a,b)$ is the expectation value of $A$ and $B$. By doing that, we obtain that $\beta=\mathrm{corr}(X,B)/\mathrm{corr}(X,A)$. More formally, an instrumental variable $X$ has only a direct causal influence over $A$ and should be independent of any latent factors acting as a common cause for variables $A$ and $B$. This assumption is known by various names such as the independence assumption \cite{rassen2009instrumental}, ignorable treatment assignment \cite{angrist1996identification}, no confounding for the effect of $X$ on $B$ \cite{hernan2006instruments}, and in the literature of quantum foundations is termed as the measurement independence assumption \cite{wood2015lesson,chaves2015unifying,hall2016significance,Hall2020,chaves2021causal}, an issue of crucial relevance for the violation of Bell inequalities \cite{bell1964einstein,big2018challenging}. Furthermore, even though $X$ and $B$ might be correlated, those correlations can only be mediated by $A$, the so-called exchangeability assumption \cite{lousdal2018introduction,Kedagni2020}. That is, $X$ should not have any direct causal influence over $B$. See Fig.~\ref{fig: Instrumental}a) for a directed acyclic graph (DAG) description of the instrumental scenario. Altogether, any observed distribution $p(a,b,x)$ compatible with these instrumental conditions should then be decomposable as \begin{equation} p(a,b,x)=\sum_{\lambda}p(a\vert \lambda,x)p(b\vert \lambda,a)p(x)p(\lambda). \end{equation} Typically, instead of looking at the joint distribution $p(a,b,x)$, one rather considers the conditional distribution $p(a,b \vert x)$ that, under the same causal assumptions, can be decomposed as \begin{equation} \label{eq:instrumental} p(a,b \vert x)=\sum_{\lambda}p(a\vert \lambda,x)p(b\vert \lambda,a)p(\lambda). \end{equation} The set of probability distributions of the form in Eq.~(\ref{eq:instrumental}) is bounded in the space of all possible distributions $p(a,b|x)$. These bounds are given by the so-called \emph{instrumental inequalities}~\cite{pearl1995testability,bonet2013instrumentality,poderini2020exclusivity}. For the simplest case of dichotomic variables there is only one type of instrumental inequalities, which we will call Pearl's inequality~\cite{pearl1995testability} and can be summarized as follows \begin{align}\label{eq:binary_instrumental_ineqs} p(j,0|0)+p(j,1|1)\leq 1,\qquad p(j,0|1)+p(j,1|0)\leq 1, \qquad \text{for } j\in \{0,1\}. \end{align} We have shown above that in the case of linear dependence of $B$ on $A$, the instrumental variable $X$ can be used to determine the strength of this dependence exactly. Importantly, the instrumental variable can be used for causal inference even in the absence of structural models, something typical in the context of quantum information and refereed there as the device-independent framework \cite{pironio2016focus,chaves2018quantum}. In particular, simply from the observed data $p(a,b \vert x)$ one can infer the effect of interventions on the variable $A$ and thus obtain a lower bound on the average causal effect $\mathrm{ACE}_{A \rightarrow B}$ defined as \begin{equation}\label{eq:ACE_def} \mathrm{ACE}_{A \rightarrow B} = \max_{a,a^{\prime},b} \vert p(b\vert \mathrm{do}(a))-p(b\vert \mathrm{do}(a^{\prime})) \vert, \end{equation} in which \begin{eqnarray} p(b|\mathrm{do}(a)) = \sum_{\lambda}p(b|a,\lambda)p(\lambda), \end{eqnarray} and $\mathrm{do}(a)$ represents the intervention over the variable $A$. As shown in Ref.~\cite{Balke1997}, for the case of binary random variables $A,B$ and $X$ the value of the average causal effect in Eq.~(\ref{eq:ACE_def}) can be lower-bounded as \begin{equation}\label{eq: Balke 1} \mathrm{ACE}_{A \rightarrow B} \geq 2p(0,0|0)+p(1,1|0)+p(0,1|1)+p(1,1|1)-2. \end{equation} The bound above is particularly relevant because it shows that the effect of interventions can be inferred simply from the observational data. Thus, instrumental variables offer a central tool for situation where interventions are not possible. The bound in Eq.~(\ref{eq: Balke 1}) is one of the eight expressions given in Ref.~\cite{Balke1997} which are proven to provide non-trivial lower bounds on $\mathrm{ACE}_{A \rightarrow B}$. The three of these eight bounds can be obtained by relabeling the one in Eq.~(\ref{eq: Balke 1}) and the rest four are not interesting for our purposes, since they hold for any causal structure. For the case of more general random variables (not only binary), one can obtain a system of linear inequalities of the form \begin{equation} \mathrm{ACE}_{A \rightarrow B} \geq \max_i\{C_i\}, \end{equation} where $C_i = \sum c^{a,b,x}_ip(a,b|x)$, are linear expressions of the probabilities with $c^{a,b,x}\in \mathds{R}$ and the maximum is taken over all such expressions. These lower bounds $C_i$ can be found using the tools of linear programming \cite{boyd2004convex}. We refer to this type of bounds on the average causal effect as \emph{causal bounds}. The causal bound in Eq.~(\ref{eq: Balke 1}) we denote as $C_1$. Other bounds studied in this work are given in Section~\ref{sec: nonbinary}. In this work, we focus on the case where the variables $A$ and $B$ are binary, i.e., taking values $a,b=0,1$ but the instrumental variable can take more values (we resort to an arbitrary set of values when discussing the instrumental inequalities and the following two cases $x \in\{0,1\}$ and $x \in\{0,1,2\}$, when referring to the problem of causal bounds). At the same time, the methods developed in this paper are applicable to the general case where all the random variables take values in arbitrary finite sets. \begin{figure} \centering \includegraphics[scale = .60]{Instrumental_sc.pdf} \caption{Causal graphs describing the instrumental scenario and its relaxations. Circular nodes correspond to observed variables, and rectangular ones are latent. Directed edges represent the causal links. (a) The instrumental scenario: the controlled variable $X$ is completely independent of a latent variable $\Lambda$. (b) A relaxed instrumental scenario, where the exchangeability assumption is relaxed, in other words, there is a direct causal influence of $X$ over $B$. We are not focusing on this relaxation. (c) A relaxed instrumental scenario, where the independence assumption is relaxed. Differently from (a), there is a causal link from $\Lambda$ to $X$. Consequently, we no longer assume that the instrumental variable $X$ and the common cause $\Lambda$ are independent, that is, $p(x,\lambda) \neq p(x)p(\lambda)$. We are focusing on this relaxation.} \label{fig: Instrumental} \end{figure} \section{Relaxing the independence assumption} \label{sec3} For the causal bounds such as in Eq.~\eqref{eq: Balke 1} to hold, one has to guarantee that the instrumental causal assumptions are fulfilled. If any instrumental inequality such as in Eq.~\eqref{eq:binary_instrumental_ineqs} is violated by the observed data $p(a,b\vert x)$, then one can unambiguously conclude that at least one of the instrumental assumptions does not hold. Such a violation can have two distinct roots. As shown in Refs.~\cite{chaves2018quantum,nery2018quantum,van2019quantum,agresti2020experimental}, even if one imposes the instrumental causal structure to a quantum experiment, still some instrumental inequalities can be violated. This can be seen as a stronger version of Bell's theorem \cite{bell1964einstein}, showing that correlations mediated via quantum entanglement can fail to have a description in terms of standard causal models. The second kind of mechanism, purely classical, and the one we mainly focus on in this paper, is the failure of causal assumptions. For instance, the violation of an instrumental inequality could be motivated by a direct causal influence of $X$ over $B$, a violation of the exchangeability assumption shown in Fig.~\ref{fig: Instrumental}b), a scenario analyzed in Ref.~\cite{chaves2018quantum}. Here, as shown in Figs.~\ref{fig: Instrumental}c) we focus on the violation of the independence assumption. Differently from the typical scenario, we no longer assume that the instrumental variable $X$ and the common source $\Lambda$ are independent, that is, $p(x,\lambda) \neq p(x)p(\lambda)$. In order to facilitate our analysis, we focus on the DAG including an additional causal link between a latent variable $\Lambda$ and instrument $X$ (see Fig.~\ref{fig: Instrumental}c)). We treat a realization of $\Lambda$ as a vector $(\lambda_x,\lambda_a,\lambda_b)$, where $\lambda_x\in[m_x]$, $\lambda_a$ takes its values in $[k_a^{m_x}]$, and $\lambda_b\in [k_b^{k_a}]$. In this relaxed case, any distribution $p(a,b|x)$ factorizes as follows, \begin{align} \label{eq: Instrumental_md} \nonumber p(a,b|x) = & \frac{1}{p(x)}\sum_{\lambda_{x},\lambda_{a},\lambda_b}p(a|x,\lambda_a)p(b|a,\lambda_b)p(x|\lambda_x)p(\lambda_x,\lambda_{a},\lambda_b)\\ = & \frac{1}{p(x)}\sum_{\lambda_{a},\lambda_b}p(a|x,\lambda_a)p(b|a,\lambda_b)p(x,\lambda_{a},\lambda_b), \end{align} where we use the same notation $p(\cdot)$ for different response functions in order to avoid cumbersome expressions. Moreover, we took, without loss of generality, that $p(x|\lambda_x)=\delta_{x,\lambda_x}$, $\delta_{\cdot,\cdot}$ representing the Kronecker delta. Similarly, conditional probabilities $p(a|x,\lambda_a)$ and $p(b|a,\lambda_b)$ can be chosen to be deterministic, leading to, \begin{equation} \label{eq: Instrumental_md deterministic} p(a,b|x) = \frac{1}{p(x)}\sum_{\lambda_{a},\lambda_b}\delta_{a,f_{\lambda_a}(x)}\delta_{b,g_{\lambda_b}(a)}p(x,\lambda_{a},\lambda_b) \end{equation} where $f_i(\cdot)$ and $g_i(\cdot)$ denote deterministic functions, specified by $\lambda_a$ and $\lambda_b$, respectively. In analogy to Ref.~\cite{chaves2015unifying}, we use a common measure of dependence between $X$ and $\Lambda$ for the instrumental scenario given by \begin{align}\label{eq: meas dep def} \mathcal{M}_{X:\Lambda} = & \sum_{x,\lambda_a,\lambda_b}|p(x,\lambda_a,\lambda_b) - p(x)p(\lambda_a,\lambda_b)|. \end{align} Crucially to our subsequent analysis, we cast it as the $l_1$-norm of the following vector, \begin{eqnarray} \label{eq: md} \mathcal{M}_{X:\Lambda} & = & \norm{M\mathbf{q}}_{l_1}, \end{eqnarray} where $\mathbf{q}_{\lambda_x,\lambda_a,\lambda_b}=p(\lambda_x,\lambda_a,\lambda_b)$ and for the canonical basis $\{\mathbf{e}_{i,j,k}\}_{i,j,k}$ in $\mathbbm{R}^{m_x k_a^{m_x}k_b^{k_a}}$, we have a matrix $M$, \begin{equation} M = \sum_{x}\sum_{\lambda_x,\lambda_a,\lambda_b}\left(\delta_{x,\lambda_x} - p(x)\right) \mathbf{e}_{x,\lambda_a,\lambda_b}\cdot \mathbf{e}_{\lambda_x,\lambda_a,\lambda_b}^T. \end{equation} \subsection{Quantifying violation of the independence assumption} The observed correlations in the instrumental experiment given by the observed probability distribution $p(a,b \vert x)$, as discussed in previous sections, allow us to evaluate the instrumental inequalities or lower bound the strength of the causal influence from $A$ to $B$. Violation of these inequalities implies that the instrumental assumptions were not met in the experiment. As mentioned before, it is important to note that this claim only works if all the latent variables are classical. Curiously, the theory of causality has recently been generalized to quantum causal modeling ~\cite{leifer2013towards,fritz2016beyond,henson2014theory,chaves2015information,pienaar2015graph,costa2016quantum,allen2017quantum}. In the latter case, the latent variables are quantum states that may be entangled, and the classical variables are obtained through quantum measurements. Quantum causal modeling differs from classical causal modeling in its predictions and as recently demonstrated in Refs.~\cite{chaves2018quantum,Gachechiladze2020,agresti2021experimental}, if the hidden common cause is allowed to be a quantum entangled state, the bounds obtained for classical instrumental causal structure can be violated. This is true for both instrumental inequalities and causal bounds. In this paper, taking a purely classical perspective on causality, we aim to quantify how much of the above-mentioned violation translates into a relaxation of the independence assumption. More precisely, we aim to find the minimal amount of dependence necessary to explain the violation of either instrumental inequalities or causal bounds. Given a linear inequality valid for the instrumental scenario $K_{\text{inst}} \geq 0$, (e.g., $K_{\text{inst}} =\mathrm{ACE}_{A\rightarrow B}- C_i$), if it is violated by a fixed amount $\alpha$, we want to establish what is the minimal amount of dependence, $\mathcal{M}_{X:\Lambda}$ that could reproduce this violation. Here, we cast this as an optimization problem, \begin{align} \begin{split} \min_{\mathbf{q}} \quad & \norm{M\mathbf{q}}_{l_1} \\ \text{s.t.} \quad & K_{\text{inst}}\leq -\alpha, \\ & \sum_{\lambda_a,\lambda_b}\mathbf{q}_{x,\lambda_a,\lambda_b} = p(x), \quad \forall x\in [m_x],\\ & \mathbf{q}\geq0 . \label{Optimization: causal} \end{split} \end{align} Note that the normalization of $\mathbf{q}$ is implied by the normalization of $p(x)$. We are ready to state our first result. \begin{observation}\label{obs:linear_dependency} The minimal dependence needed to explain a fixed violation $\alpha$ of a linear inequality valid for the instrumental scenario is a monotonic convex piecewise linear function in $\alpha$. \end{observation} To see that this statement holds, first we bring the problem in Eq.~(\ref{Optimization: causal}) to a standard primal form of a linear program (LP)~\cite{Chaves2015}. \begin{align} \begin{split} \max_{\mathbf{q, t}} \quad &- \mathbf{1}^T\cdot \mathbf{t}\\ \text{s.t.} \quad & \bm{[} M,-\openone \bm{]} \left[\begin{array}{c} \mathbf{q}\\ \mathbf{t} \end{array}\right]\leq \mathbf{0},\\ & \bm{[}-M,-\openone\bm{]}\left[\begin{array}{c} \mathbf{q}\\ \mathbf{t} \end{array}\right]\leq \mathbf{0},\\ &K\cdot P\cdot \mathbf{q} \leq -\left[\begin{array}{c} \alpha\\ \mathbf{0} \end{array}\right],\\ & \Delta \cdot \mathbf{q}\leq \mathbf{p}_x,\\ -&\Delta\cdot \mathbf{q}\leq -\mathbf{p}_x,\\ -&\mathbf{q}\leq \mathbf{0}. \end{split}\label{eq: primal LP} \end{align} In the above LP, we used the following notations. $\mathbf{1}$ is the vector of $1$s, and similarly, $\mathbf{0}$ is the vector of $0$s. The matrix $K$ specifies the coefficients in the inequality $K_{\text{inst}}$ and some additional conditions that need to be specified for a specific problem (E.g., the condition on the do-probabilities, under which $\mathrm{ACE}_{A\rightarrow B}$ becomes a linear function. If $\mathrm{ACE}_{A\rightarrow B} = |p(0|do(0))-p(0|do(1))|$, then the aforementioned condition is either $p(0|do(0)-p(0|do(1))\geq 0$ or $p(0|do(0)-p(0|do(1))\leq 0$). A matrix $P$ is a probability matrix such that its columns correspond to the deterministic assignments given by $f_{\lambda_a}(x)$ and $g_{\lambda_b}(a)$ in Eq.~\eqref{eq: Instrumental_md deterministic}. Finally, $\Delta$ denotes a matrix with entries equal to $1$ if the corresponding value of $\lambda_x$ in $\mathbf{q}$ is $x$ and $0$ otherwise for all values of $x\in [m_x]$. $\mathbf{p}_x$ is a vector of probabilities $p(x)$. Below, we give the corresponding dual LP to the one in Eq.~\eqref{eq: primal LP}, \begin{align} \begin{split} \min_{\mathbf{y},u,v,\mathbf{z}} \quad & - \alpha u + \mathbf{p}_x^T \cdot \mathbf{z} \\ \text{s.t.} \quad & M^T\cdot\mathbf{y}+P^T\cdot K^T \left[\begin{array}{c} {u}\\ \mathbf{v} \end{array}\right] +\Delta^T\cdot \mathbf{z} \geq \mathbf{0},\\ & \mathbf 0\leq \mathbf y \leq \mathbf 2,\\ & u \geq 0,\quad \mathbf{v} \geq 0. \end{split}\label{eq: MD dual LP} \end{align} In the above, we introduced the notation $\mathbf{2}$, which is a vector of all $2$s and $\mathbf{y,z,v}$ and $u$ are the dual variables. We can see from the above dual formulation of the LP that the solution must be piecewise linear in $\alpha$. Indeed, since the feasibility region of the above LP is a polytope defined by a finite set of constraints, there is a finite set of possibly optimal assignments to $u$ and $\mathbf{z}$. Hence, if we change $\alpha$ slowly from $0$ to its maximal value, the solution for $u$ might change in at most a finite number of points for $\alpha$. Moreover, it must be clear that for $\alpha=0$, i.e., in case the inequality $K_{\mathrm{inst}}\geq 0$ is valid, no dependence is required, and thus the output of the optimization problem should be $0$. Thus, it must also hold that $\mathbf{p}_x^T \cdot \mathbf{z}=0$ in the vicinity of $\alpha=0$. Since any solution of the above LP, defining the slope $u$, remains a solution for all valid values of $\alpha$, it follows that even though the whole function can be piecewise linear, i.e., have different slopes, these slopes may only increase. In other words, the resulting dependence of $\mathcal{M}_{X:\Lambda}$ on $\alpha$ is convex and monotonic. Finally, we must note that the primal problem is feasible, if the violation $\alpha$ is at most the maximum possible, which can be attained by one of the deterministic assignments given by $f_{\lambda_a}(x)$ and $g_{\lambda_b}(a)$ in Eq.~\eqref{eq: Instrumental_md deterministic} expressed as columns of matrix $P$. \subsection{Dependencies in the simplest instrumental scenario} Building on the results of this section, here we investigate the minimal required dependence for a fixed violation of instrumental inequalities and bounds on ACE in the simplest instrumental scenario when all the observed random variables are binary. For the both types of inequalities, namely instrumental inequality in Eq.~(\ref{eq:binary_instrumental_ineqs}) and causal bound in Eq.~(\ref{eq: Balke 1}) we give exact solutions to the corresponding linear programs in Eq.~(\ref{eq: MD dual LP}). \begin{lemma}\label{lemma:instr_ineq} For the instrumental scenario with binary observed random variables $X,A,B$ and a latent variable $\Lambda$, the minimal dependence required to explain a violation of the instrumental inequality by $\alpha$ is $\mathcal{M}_{X:\Lambda} = 4p(X=0)p(X=1)\alpha$. \end{lemma} \begin{proof} All the binary instrumental inequalities are given in Eq.~(\ref{eq:binary_instrumental_ineqs}). We choose one of them (the results work for any other choice too, due to symmetry present in the problem) and insert it into the primal problem, \begin{equation}\label{eq:Instrumental_binary} K_{\text{inst}}=-p(00|0)-p(01|1)+1. \end{equation} In the dual LP in Eq.~(\ref{eq: MD dual LP}), the matrix $K$ is $1\times 8$, which is a matrix representation of the expression $K_{\text{inst}}$ above. The matrix $P$ is $8\times 32$ with each column corresponding to a deterministic assignment of $X,A$ and $B$ given $\lambda$. The vector $\mathbf{z}$ has two components, which we call $z_0$ and $z_1$ and the vector $\mathbf{y}=[y_0,y_1,\dots,y_{31}]$ is $32$-dimensional. Finally, there is no vector $\mathbf{v}$ in our LP, as there are no additional linear constraints in $K$. From the definition of $M$, we derive that $M^T \mathbf{y}=\left[\begin{array}{c} {\ \ p(X=1) \mathbf{\tilde{y}}}\\ {-p(X=0) \mathbf{\tilde{y}}} \end{array}\right]$, where $-\mathbf{2}\leq\mathbf{\tilde{y}}\leq \mathbf{2}$ is a column vector, $\mathbf{\tilde{y}}^T=[\tilde{y}_0\dots\tilde{y}_{15}]$, where $\tilde{y}_i = y_i-y_{i+16},\; i\in [16]$. Moreover, note that $\Delta^T \mathbf{z}= \left[\begin{array}{c} {z_0 \mathbf{1}}\\ {z_1 \mathbf{1}} \end{array}\right]$. Taking all the above into account, the LP takes the following form, \begin{align}\label{eq:dual_linear_program_instr} \begin{split} \min_{\mathbf{\tilde y},u,z_0,z_1} \quad & - \alpha u +p(X=0)z_0+p(X=1)z_1 \\ \text{s.t.} \quad & p(X=1)\tilde y_i+[P^T\cdot K^T]_i \,u +z_0 \geq 0, \quad \forall i\in [16],\\ \quad - & p(X=0)\tilde y_i+[P^T\cdot K^T]_{i+16}\, u +z_1 \geq 0, \quad \forall i\in [16],\\ - &\mathbf 2 \leq \mathbf {\tilde{y}} \leq \mathbf 2, \quad u \geq 0. \end{split} \end{align} Here $[P^T\cdot K^T]_i$ is the $i$-th term of the vector $P^T\cdot K^T$. For $i [16]$, the expression $[P^T\cdot K^T]_i$ can take one of the two possible values, either $\left(1-\frac{1}{p(X=0)}\right)$ or $1$, and for $i \in \{16,\dots,31\}$, it can take one of the two possible values $\left(1-\frac{1}{p(X=1)}\right)$ or $1$. This simplifies the problem and by erasing redundant constraints we arrive at the final form of the LP which we solve explicitly. \begin{align}\label{eq: lemma 1 final LP} \begin{split} \min_{\tilde{y}_0,\tilde{y}_1,\tilde{y}_2,u,z_0,z_1} \quad & - \alpha u+ p(X=0)z_0+p(X=1)z_1 \\ \text{s.t.} \quad & p(X=1)\tilde y_0 - \frac{p(X=1)}{p(X=0)}\,u +z_0 \geq 0,\quad p(X=1)\tilde y_i+u+z_0 \geq 0,\quad i\in\{1,2\},\\ \quad - & p(X=1)\tilde y_1-u +\frac{P(X=1)}{P(X=0)} z_1\geq 0, \quad -p(X=1)\tilde y_i + \frac{p(X=1)}{p(X=0)}\, u +\frac{p(X=1)}{p(X=0)}z_1 \geq 0, \ i\in\{0,2\},\\ - &2 \leq \tilde{y}_i \leq 2,\quad i\in \{0,1,2\}, \qquad u \geq 0. \end{split} \end{align} By summing the first and the last inequalities for $i=0$, we directly get, $p(X=0)z_0+p(X=1)z_1\geq 0$. Finally, summing up the two inequalities, where the variable $u$ has a negative coefficient, we obtain an upper-bound on $u$, \begin{align} u\leq & (\tilde y_0-\tilde y_1) p(X=0) p(X=1)+p(X=0)z_0+p(X=1)z_1\\ \leq & 4 p(X=0) p(X=1)+p(X=0)z_0+p(X=1)z_1. \end{align} Using the upper-bound on $u$ we get that the objective function can be lower-bounded by the expression \begin{align} \begin{split} -4 \alpha p(X=0) p(X=1)+\left(p(X=0)z_0+p(X=1)z_1\right)(1-\alpha)\geq -4 \alpha p(X=0)P(X=1). \end{split} \end{align} As the final step, we note that the assignment: $u = 4p(X=0) p(X=1)$, $\tilde y_0=2$, $\tilde y_1=-2$, $\tilde{y}_2=0$, $z_0= 2p(X=1)(1-2p(X=0))$ and $z_1=-\frac{p(X=0)}{p(X=1)}z_0$ is a feasible point of the LP. Thus, $\mathcal{M}_{X:\Lambda} = 4p(X=0)p(X=1)\alpha$. \end{proof} We conclude that for a given violation $\alpha$, the uniformly distributed instrumental variable $X$ requires the highest dependence. The reverse also holds true: if the instrumental variable is uniformly random, a given dependence will permit the lowest amount of violation. Our result implies that even though we do not have direct empirical access to the common source between $A$ and $B$, from observational data $p(a,b\vert x)$ alone we can lower-bound the amount of dependence $\mathcal{M}_{X:\Lambda}$ present in a given experiment. Next we investigate how the violation of the lower bound on ACE as in Eq.~(\ref{eq: Balke 1}) translates to the required measurement dependence. \begin{lemma}\label{lemm: ace meas dep} For the instrumental scenario with binary observed random variables $X,A,B$ and a latent variable $\Lambda$, the minimal measurement dependence required to explain a violation of the lower bound on ACE as in Eq.~(\ref{eq: Balke 1}) by $\alpha$ is $\mathcal{M}_{X:\Lambda} = \frac{4p(X=0)p(X=1)}{2-p(X=0)}\alpha$. \end{lemma} \begin{proof} The proof has a similar structure as the previous one, however it is more involving. The main reason for this is that the expression $K_{\text{inst}}=\mathrm{ACE}_{A\rightarrow B}-C_1$ is written not only in terms of probabilities $p(a,b|x)$, but also in terms of do-probabilities. Additionally, by definition ACE is not linear in do-probabilities, but we can linearize it without loss of generality by requesting that $p(0|\mathrm{do}(0))-p(0|\mathrm{do}(1))\geq 0.$ In the dual LP in Eq.~(\ref{eq: MD dual LP}), the matrix $K$ is then $2\times 12$, which is a matrix representation of the expression $K_{\text{inst}}=\mathrm{ACE}_{A\rightarrow B}-C_1$ . The matrix $P$ is $12\times 32$ with each column corresponding to a deterministic assignment of $X,A$ and $B$ given $\lambda$ (which also gives deterministic assignments to the do-probabilities). The vector $\mathbf{z}$ has two components, which we call $z_0$ and $z_1$ and the vector $\mathbf{y}=[y_0,y_1,\dots,y_{31}]$ is $32$-dimensional. Finally, there is only a single element in vector $\mathbf{v}$ in our LP, which corresponds to the positivity of $p(0|\mathrm{do}(0))-p(0|\mathrm{do}(1))\geq 0$. The matrix $M$ is the same as in Lemma~\ref{lemma:instr_ineq}, $M^T \mathbf{y}=\left[\begin{array}{c} {\ \ p(X=1) \mathbf{\tilde{y}}}\\ {-p(X=0) \mathbf{\tilde{y}}} \end{array}\right]$, where $-\mathbf{2}\leq\mathbf{\tilde{y}}\leq \mathbf{2}$ is a column vector, $\mathbf{\tilde{y}}^T=[\tilde{y}_0\dots\tilde{y}_{15}]$, where $\tilde{y}_i = y_i-y_{i+16},\; i\in [16]$ and $\Delta^T \mathbf{z}= \left[\begin{array}{c} {z_0 \mathbf{1}}\\ {z_1 \mathbf{1}} \end{array}\right]$. We need to solve the following LP, \begin{align} \begin{split} \min_{\mathbf{\tilde y},u,v,z_0,z_1} \quad & - \alpha u +p(X=0)z_0+p(X=1)z_1 \\ \text{s.t.} \quad & p(X=1)\tilde y_i+[P^T\cdot K^T]_{i,0} \,u+[P^T\cdot K^T]_{i,1} \,v + z_0 \geq 0, \quad \forall i\in [16],\\ \quad - & p(X=1)\tilde y_i+\frac{p(X=1)}{p(X=0)}\left([P^T\cdot K^T]_{i+16,0}\, u+[P^T\cdot K^T]_{i+16,1}\, v\right) +\frac{p(X=1)}{p(X=0)}z_1 \geq 0, \quad \forall i\in [16],\\ - &\mathbf 2 \leq \mathbf {\tilde{y}} \leq \mathbf 2, \quad u \geq 0, \quad v \geq 0, \end{split} \end{align} where we denoted by $[P^T\cdot K^T]_{i,j}$ the element of the matrix $P^T\cdot K^T$ on $i$-th row and $j$-th column (counting from $0$). We give rows of $[K\cdot P]$ here for completeness: $ [K\cdot P]_{0} = \Big[\frac{2p(X=0)-2}{p(X=0)}$ , $\frac{3p(X=0)-2}{p(X=0)} , 1 , 2 , \frac{2p(X=0)-2}{p(X=0)} , \frac{3p(X=0)-2}{p(X=0)},$ $1,$ $2,$ $2,$ $\frac{3p(X=0)-1}{p(X=0)} , 1 , \frac{2p(X=0)-1}{p(X=0)} , 2, $ $ \frac{3p(X=0)-1}{p(X=0)} , 1 , \frac{2p(X=0)-1}{p(X=0)},2,1,\frac{p(X=1)-1}{p(X=1)},\frac{2p(X=1)-1}{p(X=1)},2,\frac{3p(X=1)-1}{p(X=1)},1,\frac{2p(X=1)-1}{p(X=1)},2,3,$ $\frac{p(X=1)-1}{p(X=1)},$ $\frac{2p(X=1)-1}{p(X=1)},$ $2,$ $\frac{3p(X=1)-1}{p(X=1)},$ $1,\frac{2p(X=1)-1}{p(X=1)}\Big]$, $[K\cdot P]_{1} = [0, -1, 1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0,$ $-1,$ $1,$ $0,$ $0,$ $-1,$ $1,$ $0,$ $0,$ $-1,$ $1, 0]$. First, we derive an upper-bound on $u$. For the feasibility region the following must hold true for any $i,j\in [16]$ (which one gets simply by summing the two types of constraints above), \begin{align} \begin{split} p(X=1)(\tilde y_i-\tilde{y_j})&+u\left([P^T\cdot K^T]_{i,0}+\frac{p(X=1)}{p(X=0)}[P^T\cdot K^T]_{j+16,0} \right)\\ +z_0+\frac{p(X=1)}{p(X=0)}z_1 &+v\left([P^T\cdot K^T]_{i,1} +\frac{p(X=1)}{p(X=0)}[P^T\cdot K^T]_{j+16,1} \right)\geq 0. \end{split} \end{align} For $i=5$ and $j=5$, the values $[P^T\cdot K^T]_{5,0}=\frac{3p(X=0)-2}{p(X=0)}$, $[P^T\cdot K^T]_{21,0}=\frac{3p(X=1)-1}{p(X=1)}$, $[P^T\cdot K^T]_{5,1}=-1$, and $[P^T\cdot K^T]_{21,1}=-1$ lead to the condition $p(X=0)z_0+p(X=1)z_1\geq v$. For $i=0$ and $j=2$, for which $[P^T\cdot K^T]_{0,0} = 2-\frac{2}{p(X=0)}$ and $[P^T\cdot K^T]_{18,0} = 1-\frac{1}{p(X=1)}$, $[P^T\cdot K^T]_{0,1}=0$, $[P^T\cdot K^T]_{18,1}=1$, we get \begin{equation} (\tilde{y}_0-\tilde{y}_2)p(X=1)+ u \frac{p(X=0)-2}{p(X=0)}+\frac{P(X=1)}{P(X=0)}v +z_0+\frac{p(X=1)}{p(X=0)}z_1\geq 0, \end{equation} which means that $u\leq \frac{1}{2-p(X=0)}\left(4p(X=0)p(X=1)+p(X=1)v+p(X=0)z_0+p(X=1)z_1\right)$, since $\tilde{y}_0-\tilde{y}_2\leq 4$. Inserting this value in the objective function, we get, \begin{align} & \frac{-\alpha}{2-p(X=0)}\left(4p(X=0)p(X=1)+p(X=1)v+p(X=0)z_0+p(X=1)z_1\right)+(p(X=0)z_0+p(X=1)z_1)\\ \geq & \frac{-\alpha 4p(X=0)p(X=1)}{2-p(X=0)}+\left(p(X=0)z_0+p(X=1)z_1\right)\left(1-\frac{\alpha}{2-p(X=0)}\right)-\frac{\alpha p(X=1)v}{2-p(X=0)}\\ \geq & \frac{-\alpha 4p(X=0)p(X=1)}{2-p(X=0)}+v\left(1-\alpha \right)\geq \frac{-\alpha 4p(X=0)p(X=1)}{2-p(X=0)}. \end{align} The last step follows as $\alpha\leq 1$. As the final step, we note that the assignment: $u=\frac{4p(X=0)p(X=1)}{2-p(X=0)}$, $v=0$, $\tilde y_0=\tilde y_1 = \tilde y_4 = \tilde y_8 = \tilde y_9=\tilde y_{12} = 2$, $\tilde y_2 = \tilde y_3 = \tilde y_6 = \tilde y_7=\tilde y_{10}= \tilde y_{14} = -2$, $\tilde y_5 = \tilde y_{13} = 2-\frac{4p(X=0)}{2-p(X=0)}$, $\tilde y_{11} = \tilde y_{15} =-\frac{2p(X=0)}{2-p(X=0)}$, and $z_0= -2p(X=1)(1-\frac{4P(X=1)}{2-p(X=0)})$, $z_1=-\frac{p(X=0)}{p(X=1)}z_0$ is a feasible point of the LP, which means that the lower bound of $-\alpha\frac{4p(X=0)p(X=1)}{2-p(X=0)}$ on the objective function is achievable. \end{proof} Until now we asked a question which degree of measurement dependence is required to explain violation of a linear inequality (e.g., instrumental inequalities or causal bounds) and we gave an analytical solution for the simplest scenario with binary observed variables. One can, however, ask the reverse question of how the linear inequalities change in the simplest instrumental scenario, if some level of measurement dependence is present in a given setup. This is the \emph{inverse} problem to the one considered in this section. Since both of these problems aim at estimating the same dependency, they have the same solution, namely the piecewise linear dependence in Observation~\ref{obs:linear_dependency}. As a result, we can derive adapted linear inequalities (e.g., binary instrumental inequalities and causal bounds) that accounts for the dependence between $X$ and $\Lambda$, explicitly. \begin{corollary}\label{lemma:mod_inequalities} Given a linear inequality valid for the simplest instrumental scenario, $K_{\text{inst}} \geq 0$, the \textit{adapted} linear inequality in terms of the measurement dependency is, \begin{equation} K_{\text{inst}}+\frac{\mathcal{M}_{X:\Lambda}}{u}\geq 0, \end{equation} where $u$ is the optimization parameter of the dual LP in Eq.~(\ref{eq: MD dual LP}). \end{corollary} The above corollary shows that one can still infer cause and effect relations even with non-perfect instruments. Also note that in case of independence, $\mathcal{M}_{X:\Lambda}=0$, we directly recover the inequalities valid in instrumental scenario (Pearl's inequality in Eq.~\eqref{eq:binary_instrumental_ineqs} and the causal bound in Eq.~\eqref{eq: Balke 1}). For a more general case, when the instrumental variable can take more than two values, adapting a linear inequality valid for the perfect instrumental scenario is also possible. However, it is a more involving task as the minimal measurement dependence does not have to be linear in the observed violation, as pointed out in Observation~\ref{obs:linear_dependency}. We give numerical treatment for this problem in Section~\ref{sec: nonbinary} and in Fig.~\ref{fig: Beyond_binary}. \subsection{Informational cost} Above we used the $l_1$-norm (see Eq.~(\ref{eq: meas dep def})) to quantify the level of dependence in the instrumental scenario. Another common measure used to quantify the dependence between two random variables is the \emph{information cost} \cite{Hall2020,chaves2021causal}, given by the Shannon mutual information, a measure of particular relevance in the entropic approach to causal inference \cite{fritz2012entropic,chaves2014inferring,budroni2016indistinguishability}. In this case, we are interested in quantifying $I(X;\Lambda) = H(X)-H(X|\Lambda)$, where $H(X)=-\sum_{x}p(x)\log{p(x)}$ is the Shannon entropy of $X$ and $H(X|\Lambda)$ is the conditional Shannon entropy of $X$ given $\Lambda$, respectively, and logarithm is taken to be base $2$. In particular, we ask a question of the minimal required information cost $I(X;\Lambda)$ that would allow for a violation of instrumental inequality in Eq.~(\ref{eq:binary_instrumental_ineqs}). For convenience, let us again use the notation \begin{equation} K_{\mathrm{inst}} = -p(0,0|0)-p(0,1|1)+1. \end{equation} If no dependence between $X$ and $\Lambda$ is allowed, then $K_{\mathrm{inst}}\geq 0$. We are now ready to present our next result. \begin{lemma}\label{lemma:inf_cost_binary} For the instrumental scenario with binary observed random variables $X,A,B$ and a latent variable $\Lambda$, with $X$ uniformly distributed, the minimal informational cost required to explain a value $K_{\mathrm{inst}} < 0$ of instrumental inequality is $I(X;\Lambda) = 1-h\left(\frac{1-K_{\mathrm{inst}}}{2}\right)$, where $h(p) = -p\log(p)-(1-p)\log(1-p)$ is the binary entropy. \end{lemma} \begin{proof} We rewrite the conditional join probabilities occurring in the expression $K_{\mathrm{inst}}$ using decomposition in Eq.~(\ref{eq: Instrumental_md}) and the following notations for the deterministic assignments $\Lambda^{(0)}_b=\{\lambda_b\ |\ p(B=0|X=0, \lambda_b) =1 \}$ and $\Lambda^{(1)}_b=\{\lambda_b\ |\ p(B=1|X=1, \lambda_b) =1 \}$. \begin{align}\begin{split} \frac{1-K_{\mathrm{inst}}}{2} & = \sum_{\lambda_a}\sum_{\lambda_b\in \Lambda_b^{(0)}} p(A=0|X=0, \lambda_a)p(X=0,\lambda_a, \lambda_b)+\sum_{\lambda_a}\sum_{\lambda_b\in \Lambda_b^{(1)}} p(A=0|X=1, \lambda_a)p(X=1,\lambda_a, \lambda_b)\\ & \leq \sum_{\lambda_a}\sum_{\lambda_b\in \Lambda_b^{(0)}} p(X=0,\lambda_a, \lambda_b)+\sum_{\lambda_a}\sum_{\lambda_b\in \Lambda_b^{(1)}} p(X=1,\lambda_a, \lambda_b) \\ &=\sum_{ \lambda_b\in \Lambda_b^{(0)}} p(X=0, \lambda_b)+\sum_{ \lambda_b\in \Lambda_b^{(1)}} p(X=1, \lambda_b)\\ & = p(X=0,\lambda_b\in \Lambda_b^{(0)})+p(X=1,\lambda_b\in \Lambda_b^{(1)})= p(X=E), \end{split}\label{eq:inf_cost_binary_proof} \end{align} where $E$ is a random variable such that $E=0$ if $\lambda_b \in \Lambda_b^{(0)}$, and $E=1$ if $\lambda_b \in \Lambda_b^{(1)}$. Since $E$ concerns a particular grouping of latent variable $\Lambda$, we can first use the data processing inequality and then Fano's inequality to obtain, \begin{align} I(X;\Lambda)\geq I(X;E)= H(X)-H(X|E)\geq 1- h(X=E) \geq 1-h\left(\frac{1-K_{\mathrm{inst}}}{2}\right). \end{align} The last inequality follows since we are only interested in the cases when $K_{\mathrm{inst}} < 0$. The above lower bound is tight for all $K_{\mathrm{inst}} < 0$, since we can always set the following assignments: $p(A=0|X=0, \lambda_a) = p(A=0|X=1, \lambda_a) = 1$, and $p(X=0|\lambda_a,\lambda_b)=\frac{1-K_{\mathrm{inst}}}{2}$, $p(X=1|\lambda_a,\lambda_b)=1-\frac{1-K_{\mathrm{inst}}}{2}$, $\forall \lambda_a,\lambda_b \in \Lambda$. \end{proof} The same result applies to any of the four instrumental inequalities in Eq.~(\ref{eq:binary_instrumental_ineqs}). \subsection{Beyond the binary case}\label{sec: nonbinary} So far we have restricted our attention to the case where all variables are binary. Here, we generalize the results for the instrumental variable, which can take more values. Concerning instrumental inequalities, if the variables $A$ and $B$ are binary, it is known that the instrumental scenario is completely characterized by three inequalities up to the relabelings of the variables, $I_i\leq 0$, $i= 1,2,3$~\cite{Kedagni2020}. The inequality $I_1\leq 0$ corresponds to Pearl's inequality and was already discussed in the binary case (See Eq.~(\ref{eq:binary_instrumental_ineqs})), the second one is known as Bonet's inequality~\cite{bonet2013instrumentality}, \begin{equation}\label{eq:Bonet} p(0,1|0)-p(0,1|1)-p(1,1|1)-p(1,0|2)-p(0,1|2)\leq 0, \end{equation} and the third one is Kedagni's inequality~\cite{Kedagni2020}, \begin{equation}\label{eq:Kegani} p(0,0|0)+p(1,0|0)-p(0,1|1)-p(1,0|1)-p(0,0|2)-p(1,0|2)-p(0,0|3)-p(1,1|3)\leq 0. \end{equation} One can obtain other inequalities from Refs.~\cite{bonet2013instrumentality,Kedagni2020} by relabeling inputs and outputs and by coarse graining values of $X$. Considering the case where $X$ assumes up to three possible values, we obtained two new classes of causal bounds, for which we give two representatives below. All the other causal bounds for three inputs can be obtained by relabeling inputs or outputs in these two inequalities. \begin{eqnarray} \label{eq:ace34} C_2 & = & p(0,0|0) + p(0,0|2) + p(1,0|0) + p(1,1|1) + p(1,1|2) - 2.\\ C_3 & = & p(0,0|0)+p(0,0|1)-p(0,1|1)+p(0,1|2)+p(1,0|0)-p(1,0|1)+p(1,1|1)+p(1,1|2)-2. \end{eqnarray} For all the causal bounds and the instrumental inequalities we use the LP in Eq.~(\ref{Optimization: causal}) to estimate the minimal measurement dependency in order to explain the violation by the amount of $\alpha$. The results are summarized in Fig.~\ref{fig: Beyond_binary}. Even though we only provide closed formula solutions of the LPs in the simplest binary case, in more general scenarios, for a given distribution $p(x)$, it is sufficient to solve the LP in a very few points due to the nature of the functional dependence being convex piecewise linear. For example, for the instrumental inequality $I_2\leq 0$, the numerical results in Fig.~\ref{fig: Beyond_binary} suggest that for the chosen fixed distributions of $X$, the minimal measurement dependence $\mathcal{M}_{X:\Lambda}$ is linear in $\alpha$. We could, however, reach the same conclusion by solving the LP for two different values of $\alpha$ in the interval $\alpha\in(0,1]$ for the same fixed distributions of $X$. The first value of $\alpha$ can be arbitrary, but the second one must be equal to $\alpha=1$. Additionally, we know that for $\alpha=0$, the measurement dependence $\mathcal{M}_{X:\Lambda}=0$. If the values of the minimal measurement dependence corresponding to these three points belong to the same straight line, we invoke the convexity property, and conclude that, $\mathcal{M}_{X:\Lambda}=u\alpha$, where $u$ is the slope of the obtained straight line. For example, for the uniformly distributed $X$, $\mathcal{M}_{X:\Lambda}=\frac{2}{3}\alpha$, where the coefficient of $\frac{2}{3}$ can be obtained from the LP up to the numerical precision. \begin{figure} \centering {\includegraphics[width = .33\textwidth]{I2.pdf}} {\includegraphics[width = .33\textwidth]{C2.pdf}} {\includegraphics[width = .33\textwidth]{C3.pdf}} \caption{Measurement dependence $\mathcal{M}_{X:\Lambda}$ for violations $\alpha$ of instrumental inequality $I_2$ (left), and causal bounds $C_2$ (center) and $C_3$ (right). The maximal violation of each inequality attainable in quantum theory is marked by $Q_{\mathrm{max}}$ (See Section~\ref{sec4}).} \label{fig: Beyond_binary} \end{figure} \section{Quantum violations of instrumental tests} \label{sec4} We saw that the instrumental and causal bounds can be violated if a certain amount of measurement dependence is present between an instrumental variable and a classical common cause $\Lambda$. However, a violation is also possible if we do not assume any relaxation on the instrumental scenario, but instead we consider the case, when the unobserved common cause can be a quantum state~\cite{chaves2018quantum, Gachechiladze2020, agresti2021experimental}. More precisely, in the quantum instrumental scenario considered here, all three observable variables, $X$, $A$ and $B$, are still classical random variables, but instead of the latent variable $\Lambda$, we have a latent quantum state $\rho_{AB}$. This type of quantum causal model produces observable correlations using the \textit{Born rule} for measurements in quantum mechanics, \begin{equation} p_Q(a,b|x)=\tr\left[(M^x_a\otimes N^a_b )\rho_{AB}\right]. \end{equation} Here $\rho_{AB}$ is a quantum state of two subsystems, represented by the so-called \textit{density matrix} that is a positive, trace-$1$ linear operator acting on the tensor product of two Hilbert spaces $\mathcal{H}_A\otimes \mathcal{H}_B$, $M^x_a$ is a positive operator acting on the first subsystem (Hilbert space $\mathcal{H}_A$) and describes a measurement depending on the choice $x$ with outcome $a$. Similarly, $N^a_b$ is a positive operator acting on the second subsystem (Hilbert space $\mathcal{H}_B$) and describes a measurement depending on the choice $a$ (which is the measurement outcome obtained on the first subsystem) with outcome $b$. In the case of the simplest instrumental scenario, the statistics obtained from a latent quantum state cannot violate the instrumental inequalities in Eq.~(\ref{eq:binary_instrumental_ineqs}). Remember, that such inequalities can be violated if the measurement dependence is present. However, it was shown in Refs.~\cite{chaves2018quantum,Gachechiladze2020} that in the case of binary variables, the causal bound in Eq.~(\ref{eq: Balke 1}) can be violated without any measurement dependence if the intervention on $A$ is made in the quantum instrumental scenario. In a full analogy with the classical case, one can define quantum interventions as \begin{equation} p_Q(b|\mathrm{do}(a))=\tr\left[\left(\mathbbm{1}\otimes N^a_b \right)\rho_{AB}\right], \end{equation} where a measurement is performed only on the second subsystem. This implies that if an actual intervention is made, the observed quantum average causal effect (qACE) is given by, \begin{equation} \mathrm{qACE}_{A \rightarrow B}=\max_{a,a',b}\left|\tr\left[\left(\mathbbm{1}\otimes (N^a_b-N^{a'}_b) \right)\rho_{AB}\right]\right|. \end{equation} Ref.~\cite{Gachechiladze2020} showed that any pure entangled quantum state $\rho_{AB}=\ket{\psi}\bra{\psi}$, where $\ket{\psi}=\sin\alpha\ket{0}\otimes \ket{0} +\cos{\alpha} \ket{1} \otimes \ket{1}\in \mathbbm{C}^2\otimes \mathbbm{C}^2$ and appropriate incompatible quantum measurements, $M_a^x=\frac{1}{2}\left(\mathbbm{1}+(-1)^a(\sin\theta_x\sigma_X+\cos\theta_x\sigma_Z)\right)$ and $N_b^a=\frac{1}{2}\left(\mathbbm{1}+(-1)^b(\sin\eta_a\sigma_X+\cos\eta_a\sigma_Z)\right)$, where $\sigma_X$ and $\sigma_Z$ are Pauli matrices and the vectors $\ket{0}$ and $\ket{1}$ are normalized eigenstates of $\sigma_Z$, can violate the bound in Eq.~(\ref{eq: Balke 1}). The maximal possible violation was numerically obtained (and was verified by the hierarchy of semidefinite programs~\cite{navascues2007bounding}) to be $3-2\sqrt2\approx 0.1716$. Using the results of the previous sections, we can conclude that in order to explain such a quantum violation, the amount of minimum measurement dependency in the classical instrumental causal structure must at least be $\mathcal{M}_{X:\Lambda}=\frac{4p(X=0)p(X=1)}{2-p(X=0)}(3-2\sqrt{2})$ and is maximal for $P(X=0)=(2-\sqrt{2})$ and is equal to $\mathcal{M}_{X:\Lambda}=(68 - 48 \sqrt{2})\approx0.1177 $. In case of more general instrumental scenario, where $X$ can take more than two values, $I_2\leq 0$ and $I_3\leq 0$ can be violated by quantum states and measurements~\cite{chaves2018quantum}, both by the maximally entangled state (that is when $\sin{\alpha}=\frac{1}{\sqrt{2}}$) with the amount of $\left(\frac{1}{\sqrt{2}}-\frac12 \right)\approx0.2071$ and $ \sqrt2-1\approx 0.4142$, respectively. See Fig.~\ref{fig: Beyond_binary}~(left) for the relation between the minimal required measurement dependence in classical instrumental scenario and the amount of violation of $I_2\leq 0$ for various probability distributions of the instrumental variable. In particular, for the uniformly distributed instrumental variable, the minimal measurement dependence required to explain the quantum violation is $\mathcal{M}_{X:\Lambda}=\frac13 (\sqrt{2}-1)\approx0.1381$. The minimal measurement dependence needed to explain the maximal quantum violation of $I_3\leq 0$ for the uniformly distributed instrumental variables is $\mathcal{M}_{X:\Lambda}=\left(\frac{1}{\sqrt{2}}-\frac12 \right)\approx0.2071$. Finally, we consider the quantum violation of the causal bounds for the instrument that takes three values. The inequality $\mathrm{ACE}_{A\rightarrow B}\geq C_2$ can be violated by the maximally entangled state with the amount of $\left(\frac{1}{\sqrt{2}}-\frac12 \right)\approx0.2071$ and the inequality $\mathrm{ACE}_{A\rightarrow B}\geq C_3$ with the amount of $ \sqrt2-1\approx 0.4142.$ In order to explain these violations, the amount of minimum measurement dependency in the classical instrumental causal structure depends on a probability distribution of the instrumental random variable. See Fig.~\ref{fig: Beyond_binary} ~(center) and (right) for the particular examples of such distributions. We highlight that even though the violations of causal bounds match with the violations of instrumental inequalities, these quantities are of a very different nature. In particular, the violation of causal bounds required both interventional and observational probability distributions while the violation of instrumental inequalities rely solely on observational data. \section{Discussion} \label{sec5} Instrumental variables offer ways to estimate causal influence even under confounding effects and without the need for interventions. Strikingly, as discovered in Ref.~\cite{Balke1997}, one can infer the effect of interventions, without resorting to any structural equations, simply from observational data obtained with the help of an instrument. As already recognized long ago \cite{johnston1963econometric}, however, ``the real difficulty in practice of course is actually finding variables to play the role of instruments''. Since the potential correlation of the instrument with any latent variables is in principle unobservable, it might seem that the exogeneity of a given instrument is a matter of trust and intuition rather than a fact supported by the data. Motivated by this fundamental problem, the data from an instrumental test \cite{pearl1995testability,bonet2013instrumentality,Kedagni2020,poderini2020exclusivity} can be employed to benchmark the amount of dependence the instrument can have with a confounding variable. More precisely, we quantify such correlations via a $l1$-norm, measuring by how much the instrumental variable fails to be exogenous. The violation of an instrumental inequality allows us then to put lower bounds on this dependence. In turn, we derive bounds for the average causal effect \cite{pearl2009causality} taking into account that some level of dependence, lower bounded by the violation of instrumental inequality, is present. That is, we turn the causal bounds in a reliable tool even if the instrument is not really exogenous. Relying on a linear program description, we obtain fully analytical results for the simplest instrumental scenario where all variables are binary. We study a more general case of trinary instrumental variable numerically using our linear programming technique. In parallel, we also derived new bounds for the average causal effect (Eq. \eqref{eq:ace34}), that to the best of our knowledge, are new to the literature. We also consider applications of our generalized instrumental inequalities and causal bounds to consider the problem of measurement independence (also known as ``free-will'') in the foundations of quantum physics. It is worth noting that the effect of imperfect instruments has previously been considered~\cite{bartels1991instrumental}. There, however, the study was limited to regression bivariate models, while here our results are free of any structural equations and valid for any causal mechanisms between the variables. Even though, we have focused on the case where treatment and effect variables are binary, the linear program framework we propose can also be extended to variables assuming any discrete number of values (limited, of course, by the computational complexity of the problem). Another interesting question for future research is to understand whether similar results may hold for the case of continuous variables, a direction that we hope might be triggered by our results. \begin{acknowledgments} N.M.~acknowledges the support by the Foundation for Polish Science (IRAP project, ICTQT, contract no. 2018/MAB/5, co-financed by EU within Smart Growth Operational Programme) and the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) via the Emmy Noether grant 441423094. This work was supported by the John Templeton Foundation via the grant Q-CAUSAL No 61084 (the opinions expressed in this publication are those of the author(s) and do not necessarily reflect the views of the John Templeton Foundation) Grant Agreement No. 61466, by the Serrapilheira Institute (grant number Serra – 1708-15763), by the Simons Foundation (Grant Number 884966, AF), the Brazilian National Council for Scientific and Technological Development (CNPq) via the National Institute for Science and Technology on Quantum Information (INCT-IQ) and Grants No. 406574/2018-9 and 307295/2020-6, the Brazilian agencies MCTIC and MEC. M.G.~is funded by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) under Germany’s Excellence Strategy – Cluster of Excellence Matter and Light for Quantum Computing (ML4Q) EXC 2004/1 – 390534769. \end{acknowledgments}
{'timestamp': '2021-11-05T01:21:57', 'yymm': '2111', 'arxiv_id': '2111.03029', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03029'}
arxiv
\section{Introduction} Learning the temporal evolution of a complex dynamical system from noisy time series data is a long-stand research topic across many disciplines, including statistics, physics, engineering, and computer science \cite{Box08,Lim21,Mudelsee19,Wang16}. While there has been much progress in the time series models for nonlinear dynamical systems with at least a partial knowledge on the underlying time marching structure \cite{Arula02,Wiljes19,Evensen03,Hamilton15}, modeling of a nonlinear dynamical system without prior knowledge on the governing equations still remains as a challenging topic. Recently, deep learning approaches have shown promising results in the data-driven learning of complex dynamics due to the strong capability of artificial neural networks in learning nonlinear structures in the data \cite{Champion19,Genty21,Pathak18,Yeo19}. There are two major deep-learning approaches in the data-driven modeling of dynamical systems. In the first approach, deep learning models are developed to approximate / discover the time marching operator of a dynamical system from a time series data \cite{Champion19,Lu21,Lusch18,Qin19}. On the other hand, the second approach focuses on directly modeling the time series data by a variant of recurrent neural network (RNN) \cite{Agarwal21,Pathak18,Vlachas18,Yeo21}. Although the previous studies demonstrate a potential of deep learning model in the data-driven modeling of complex dynamical systems, data-driven modeling of a \emph{random} dynamical system remains as a challenging topic, particularly when the time marching operator exhibits a time-delay dynamics or the noise process has a complex probability distribution. In this study, we consider the second class of deep learning approaches; we aim to develop a noble RNN model for inference and simulation of time series data from a random dynamical system without a prior knowledge on the system dynamics. Let $\bm{x}_t \in \mathbb{R}^d$ denote a $d$-dimensional stochastic process at time step $t$. In the time series inference problem, we aim to find the data generating distribution, $p(\bm{x}_1,\cdots,\bm{x}_T)$, from the time series data of length $T$. As discussed in \cite{GoodfellowBengio16}, RNN is a nonlinear extension of the state-space model. Using RNN, the challenging inference problem of learning the full joint probability distribution, $p(\bm{x}_1,\cdots,\bm{x}_T)$, can be converted into a set of simpler inference problems of estimating $p(\bm{x}_t|\bm{h}_t)$ for $t=1,\cdots,T$, in which $\bm{h}_t$ is the hidden state of RNN \cite{Yeo21}. Since the hidden state of RNN is a function of the past trajectory, \emph{i.e.}, $\bm{h}_t = f(\bm{x}_1,\cdots,\bm{x}_{t-1})$, RNN is capable of capturing a time-delay dynamics in the time series data \cite{Gers00}. Although RNN has shown outstanding performances in learning the long-time dependence and nonlinear time-marching operator from the data, this formulation still requires an assumption on the distributional property of the random variable, $\bm{x}_t$. Usually, a multivariate Gaussian distribution with a diagonal covariance is assumed, \emph{i.e.}, \[ p(\bm{x}_t|\bm{h}_t) = \prod_{i=1}^d p(x_{i_t}|\bm{h}_t) = \prod_{i=1}^d \mathcal{N}(x_{i_t};\mu_i(\bm{h}_t),\sigma^2_i(\bm{h}_t)), \] in which $\mu_i(\cdot)$ and $\sigma_i(\cdot)$ denote the functions for the mean and standard deviation of the Gaussian distribution \cite{chung15,Salinas20}. This assumption on the probability distribution of $\bm{x}_t$ significantly restricts the capability of RNN, as it only captures a unimodal distribution and also makes an independence assumption. To relax these restrictions, \cite{Yeo19} developed a RNN model to directly approximate the probability distribution using a numerical discretization, and \cite{Salinas19} proposed to use a low-dimensional Gaussian Copula to model the joint probability distribution. Since its introduction \cite{Goodfellow14}, the Generative Adversarial Network (GAN) has attracted great attention due to its strength in (implicitly) learning a complex probability distribution \cite{Goodfellow20,Hong19,Saxena21}. Recently, the GAN and its variants have been successfully applied to a wide range of physics problems \cite{Ahmed21,Kim21,Otten21,Paganini18,Yang20}. In contrast, GANs for the sequential time series inference of noisy observations of complex dynamical systems are not relatively well studied. While there are numerous studies about GANs for time series prediction \cite{Wu20,Yoon19,Yu17}, most of the previous studies focus on generating ``realistic'' looking time series or direct applications of GANs to time series data. Hence, the behaviors of GANs in the data-driven predictions of a stochastic process are not well understood. Here, we aim to develop a more general deep learning framework to learn a complex multi-dimensional joint probability distribution of a stochastic process, $\bm{x}_t$, without a distributional assumption and to simulate the learned stochastic dynamics to predict the probability distribution of the future system state. Here, we propose to use a RNN to learn the time evolution of the stochastic process and a GAN to learn and draw samples from the conditional distribution, $p(\bm{x}_{t+1}|\bm{x}_{1:t})$, in wihch $\bm{x}_{a:b} = (\bm{x}_a,\cdots,\bm{x}_b)$. Although a GAN does not explicitly provide the probability distribution, since a Monte Carlo simulation is used to evaluate the future system state of a nonlinear stochastic process, it is enough to be able to draw a sample from the complex probability distribution of the time series data. We propose a regularization strategy based on the consistency between the conditional and marginal distributions of the time series data. This paper is organized as follows; the problem set up is described in section \ref{sec:Prob}. Then, a brief review of GAN is given in section \ref{sec:GAN}. Section \ref{sec:CR-GAN} describes our GAN approach to learn and simulate a random dynamical system. The numerical experiments of our GAN model are showed in section \ref{sec:results}. Finally, the conclusions are given in section \ref{sec:summary}. \section{Methodology}\label{sec:numerics} \subsection{Problem formulation}\label{sec:Prob} Let $\bm{x}(t) \in \mathbb{R}^d$ denote the state of a physical system. The time evolution of $\bm{x}(t)$ is governed by the following stochastic differential equation \begin{equation} \frac{d\bm{x}(t)}{dt} = \mathcal{F}(\bm{x}(t),\bm{x}(t-\tau)) + \bm{\epsilon}(t), \end{equation} in which $\bm{\epsilon}(t)$ is a noise process, $\tau$ is a delay time, and $\mathcal{F}(\cdot)$ is a deterministic time marching operator. Here, we assume no prior knowledge about the system, \emph{i.e.}, $\mathcal{F}$, $\tau$, and $\bm{\epsilon}$. The time series data set ($\bm{\mathcal{X}}$) is generated by sampling $\bm{x}(t)$ with a fixed sampling interval, $\delta t$: $\bm{\mathcal{X}} =\{ \bm{x}_0,\cdots,\bm{x}_T \}$, where $\bm{x}_t = \bm{x}(t_0 + t \delta t)$ and $t_0$ is the sampling start time. We consider learning conditional probability density functions, $p(\bm{x}_t|\bm{x}_{0:t-1})$ for $t\in[1,T]$, from $\bm{\mathcal{X}}$ by using a recurrent neural network supplemented by GAN. Once the conditional probability distribution is learned, the simulation is performed by successively computing the conditional probability distribution functions, \[ p(\bm{x}_{t+n},\cdots,\bm{x}_{t+1}|\bm{x}_{0:t}) = \prod_{i=1}^n p(\bm{x}_{t+i}|\bm{x}_{0:t-1},\bm{x}_{t:t+i-1}). \] The future joint probability distribution is evaluated by using a Monte Carlo simulation, and we use GAN to draw the samples from the conditional distribution. \subsection{Review of Generative Adversarial Network} \label{sec:GAN} A Generative Adversarial Network is trained by the mini-max game between two functions, discriminator and generator to find a Nash equilibrium \cite{Goodfellow20}. The discriminator, $D: \mathbb{R}^m \rightarrow (0,1)$, estimates the probability of the input $\bm{y} \in \mathbb{R}^m$ being a sample from the data set, and the generator, $G:\mathbb{R}^n \rightarrow \mathbb{R}^m$, outputs $\bm{y}^* \in \mathbb{R}^m$, from an input, $\bm{z} \in \mathbb{R}^n$. Typically, artificial neural networks are used to parameterize both $D(\bm{y})$ and $G(\bm{z})$. The input to the generator, $\bm{z}$, is usually chosen as a random variable with a simple probability distribution, such as an isotropic Gaussian distribution. The optimization problem to train GAN is \begin{equation} \label{eqn:GAN_loss} \min_{G}\max_D E_{\bm{y}\sim p_d} \left[ \log D(\bm{y}) \right] + E_{\bm{z} \sim p_z} \left[ \log \left(1-D(G(\bm{z}))\right) \right], \end{equation} in which $p_d(\bm{y})$ is the data generating distribution and $p_z(\bm{z})$ is the probability distribution of $\bm{z}$. The mini-max optimization problem aims to make the discriminator better at identifying the true samples (from data) and fake samples (from $G(\bm{z})$) and, at the same time, to make the generator generate outputs closer to the data so that $D(\cdot)$ fails to distinguish between true and fake samples. It was shown that at the global minimum, $p_d(\bm{y}) =p_g(\bm{y})$, in which $p_g(\bm{y})$ is the probability distribution of the generated samples. Theoretical analysis of GAN is an active area of research \cite{Fedus18,Heusel17,Nagarajan17,Sun20_NIPS}. Since the majority of the applications of GANs is either in image or text generations, it is typical to use ``real'' and ``fake'' to explain how GANs work, \emph{e.g.}, the discrniminator distinguishes between ``real'' and ``fake'' samples. However, when $\bm{y}$ is a real-valued random variable, the discussions based on ``real'' and ``fake'' samples are not straightforward. Here, we provide a simpler analysis of GAN for a real-valued random variable, $\bm{y}$. Without loss of generality, we consider a one-dimensional random variable $y \in \mathbb{R}$. While the true data generating distribution, $p_d$, may not have a compact support, we can identify the range of a data set, $\mathcal{Y} = \{ y_1,\cdots,y_N \}$, in which $N$ is the total number of data, \[ Supp(p_d) = [y_{min},y_{max}]. \] Here, $y_{min}$ and $y_{max}$ denote the minimum and maximum of $\mathcal{Y}$, respectively, and, with a slight abuse of the notation, we use $Supp(p_d)$ to denote the range of the data. We can define a set of ordered real numbers, $\bm{\alpha} = \{ \alpha_1,\cdots,\alpha_{K-1} \}$, such that \[ y_{min} < \alpha_1 < \cdots < \alpha_{K-1} < y_{max}, \] and associated partitions, $\mathcal{A} = \{A_i; A_i = [\alpha_{j-1},\alpha_j), i\in\mathbb{N}_{>0}, i \le K\}$, where $\alpha_0 = y_{min}$ and $\alpha_K = y_{max}$. Then, we can define a discrete probability distribution, \[ P_i = \frac{1}{N} \sum_{j=1}^N \chi_{A_i}(y_j), \] where $\chi_{A_i}(y)$ is an indicator function that returns one if $y \in A_i$ and zero otherwise. Similarly, we can define a discrete probability distribution of the generated samples for a random variable $\mathcal{Z} = \{z_1,\cdots,z_M\}$, \[ Q_i = \frac{1}{M} \sum_{j=1}^M \chi_{A_i}(G(z_j)). \] Now, the optimization problem of the GAN (\ref{eqn:GAN_loss}) is simplified as \begin{equation} \min_{\bm{Q}}\max_{\bm{D}} \sum_{i=1}^K P_i \log D_i + Q_i \log (1-D_i), \end{equation} in which $D_i$ is a discriminator function for the partition $A_i$. In the training of a GAN, usually a stochastic gradient descent method is used alternating between two steps; first update $D$ for $G$ fixed (D-Step) and update $G$ for $D$ fixed (G-Step). The optimization problem of D-Step, \begin{equation} \max_{\bm{D}} \sum_{i=1}^K P_i \log D_i + Q_i \log (1-D_i), \end{equation} has a simple solution, \begin{equation} D_i = \frac{1}{1+Q_i/P_i}~\text{for}~1\le i \le K. \end{equation} It suggests that the discriminator score is based on the relative frequency of the samples observed in each partition. If we assume $M=N$, $D_i$ becomes larger than 0.5 when we have more data than generated samples in $A_i$, \emph{i.e.}, $P_i > Q_i$, and vice versa. On the other hand, in G-Step, the optimization problem becomes \begin{equation} \label{eqn:g_step} \min_{\bm{Q}} \sum_{i=1}^K Q_i \log(1-D_i)~\text{subject to}~\sum_{i=1}^K Q_i = 1, \end{equation} of which solution is simply $Q_i = \delta_{ik}$ for $k = \max_{j} D_j$ when $\bm{D}$ has only one maximum. If $\bm{D}$ has multiple maxima, $\bm{Q}$ cannot be uniquely determined. When D-Step and G-Step are considered simultaneously, the equilibrium solution is given as \begin{equation} D_1=\cdots=D_K = 0.5,~\text{and}~P_i = Q_i~\text{for}~1 \le i \le K. \end{equation} In the limit $M\rightarrow \infty$, $N \rightarrow \infty$ and $K \rightarrow \infty$, the above analysis converges to the results in \cite{Goodfellow14}. However, it is important to note that, in the analysis above, we implicitly assumed that $\bm{P}$ and $\bm{Q}$ have the same support. Let $Supp(p_g)$ denote the support of the distribution of the generated samples. If $Supp(p_g) \setminus Supp(p_d) \neq \emptyset$, $\bm{Q}$ in $Supp(p_g) \setminus Supp(p_d)$ will be penalized by $\bm{D}$, which will shrink $Supp(p_g)$. On the other hand, when $Supp(p_d) \setminus Supp(p_g) \neq \emptyset$, because the optimization problem of G-Step (\ref{eqn:g_step}) is defined only within $Supp(p_g)$, there is no mechanism to make $Supp(p_g)$ bigger to cover $Supp(p_d)$. And, when it happens, the optimization problem will not converge. There are two major concerns in training a GAN. First, because the discriminator score at a point $\bm{y}$ depends on the number of data around $\bm{y}$, training of a GAN suffers from the curse of dimensionality. As the dimension of $\bm{y}$ increases, the number of data required to uniformly cover the space increases exponentially. Second, while it is required to have $Supp(p_d) = Supp(p_g)$ for the training of a GAN to converge, it is difficult to achieve because the optimization in G-Step is defined only over $Supp(p_g)$. Because of these issues, training a GAN often fails. To overcome such difficulties, much efforts have been focused on regularizing the behavior of the discriminator \cite{Fedus18,Roth17,Thanh-Tung19,Zhang20}. On the other hand, regularizing the generator has not been widely explored. \subsection{Consistency-Regularized Generative Adversarial Network} \label{sec:CR-GAN} \subsubsection{Generative Adversarial Network} \begin{figure} \includegraphics[width=0.99\textwidth]{figures/sketch.png} \caption{Sketches of the Generator (left) and the Discriminator (right). $\bm{x}^*_t$ indicates a sample drawn from $p_g(\bm{x}_t|\bm{x}_{0:t-1})$, and $s_t$ denotes the discriminator score at time step $t$.} \label{fig:sketch} \end{figure} Here, we aim to learn the conditional probability distribution, $p_d(\bm{x}_{t+1}|\bm{x}_{0:t})$, of a $d$-dimensional stochastic process $\bm{x}_t\in\mathbb{R}^d$ for the data-driven simulation. Since the fully connected graph structure of the conditional distribution, \emph{i.e.}, the dependence on the entire historical sequence, $\bm{x}_{0:t}$, makes the inference problem difficult, we use a RNN and exploit the conditional independence given the hidden state of the RNN, such that \begin{equation} p_g(\bm{x}_{t+1}|\bm{x}_{0:t}) = p_g(\bm{x}_{t+1}|\bm{h}^G_{t+1}). \end{equation} The hidden state is updated as \begin{equation} \bm{h}^G_{t+1} = \Psi_G(\bm{x}_t,\bm{h}^G_t), \end{equation} in which $\Psi_G(\cdot)$ denotes a nonlinear transformation defined by the RNN. On top of the RNN, we add a feedforward network, $F_G(\bm{z},\bm{h}^G_{t+1})$, which aims to draw a sample from $p_g(\bm{x}_{t+1}|\bm{x}_{0:t})$ by using a random variable, $\bm{z}\in\mathbb{R}^n$, as an input variable. We use an isotropic Gaussian distribution for $\bm{z}$; $\bm{z} \sim \mathcal{N}(\bm{0},\bm{I})$. A sketch of the generative model, or generator $G(\bm{x}_t,\bm{h}^G_t,\bm{z})$, is shown in the left panel of Fig. \ref{fig:sketch}. As discussed in section \ref{sec:GAN}, given a data at time $t+1$, $\widetilde{\bm{x}}_{t+1}$, the discriminator aims to approximate the ratio between the data and generator distributions at $\widetilde{\bm{x}}_{t+1}$ given the historical sequence, $\bm{x}_{0:t}$, \emph{i.e.}, $p_g(\widetilde{\bm{x}}_{t+1}|\bm{x}_{0:t}) / p_d(\widetilde{\bm{x}}_{t+1}|\bm{x}_{0:t})$. Hence, we again use a RNN, $\Psi_D(\cdot)$, and its associated hidden state, $\bm{h}^D_t$, \begin{equation} \bm{h}^D_{t} = \Psi_D(\bm{x}_{t-1},\bm{h}^D_{t-1}). \end{equation} Then, a feedforward neural network, $F_D(\widetilde{\bm{x}}_t,\bm{h}^D_t)$, is added to compute the discriminator score, $s_t$. The right panel of Fig. \ref{fig:sketch} shows a sketch of the discriminator. When training a GAN for a time series problem, it is typical to follow the original GAN training approach \cite{Wu20,Yoon19,Yu17}. In other words, first compute the first term of the objective function in (\ref{eqn:GAN_loss}) by using the data $\bm{x}_{0:t}$, and then generate a sequence, $\bm{x}^*_{0:t}$ from $\bm{z}$ to compute the second term of (\ref{eqn:GAN_loss}) from $\bm{x}^*_{0:t}$. However, in this approach, the optimization problem of the time series problem becomes \begin{align} \max_{G}\min_{D}~ E_{\bm{x}_{0:t} } [ \log D(\bm{x}_{0:t}) ] + E_{\bm{x}^*_{0:t} } [ \log (1-D(\bm{x}^*_{0:t})) ] \end{align} in which $E_{\bm{x}}[\cdot]$ and $E_{\bm{x}^*}[\cdot]$ denote expectations over the data distribution and the generator distribution, respectively. Note that the generator in the second term is replaced by the expectation over the generator distribution, $p_g$. Then, it is clear that, for each time step $t$, the discriminator tries to learn the ratio between the full joint probability distribution, $p_g(\bm{x}_{0:t})/p_d(\bm{x}_{0:t})$. As shown in section \ref{sec:GAN}, learning the full joint probability distribution is challenging due to the high dimensionality. Here, we propose to use the following objective function to learn the conditional distribution, not the full joint probability distribution. At time step $t$, we propose to train a GAN using the following objective function, \begin{equation} \label{eqn:GAN_loss_new} \max_{G}\min_{D}~ E_{\bm{x}_{0:t-1}} [\mathcal{L}(\bm{x}_{0:t-1})], \end{equation} in which \begin{equation} \label{eqn:GAN_loss_new_2} \mathcal{L}(\bm{x}_{0:t-1}) = \int p_d(\bm{x}_t|\bm{x}_{0:t-1}) \log D(\bm{x}_t|\bm{x}_{0:t-1}) +p_g(\bm{x}_t|\bm{x}_{0:t-1}) \log (1- D(\bm{x}_t|\bm{x}_{0:t-1})) d\bm{x}_t. \end{equation} Note that the GAN loss (\ref{eqn:GAN_loss_new_2}) is computed over the expectation of the data generating distribution, $p_d(\bm{x}_{0:t-1})$ in (\ref{eqn:GAN_loss_new}). The major difference from the previous methods is, instead of evaluating the second term by a sequence of generated samples as in (\ref{eqn:GAN_loss}), we use the data $\bm{x}_{0:t-1}$, draw a sample $\bm{x}^*_t$ by using the generator, and evaluate the discriminator with $\bm{x}^*_t$. Now, the objective of the discriminator at time step $t$ becomes comparing the conditional distributions, $p_g(\bm{x}_t|\bm{x}_{0:t-1})/p_d(\bm{x}_t|\bm{x}_{0:t-1})$. In other words, the discriminator is used to distinguish between the data, $\bm{x}_t$, and a generated sample, $\bm{x}^*_t$, conditioned on a sequence from the data, $\bm{x}_{0:t-1}$, instead of comparing a sequence, $\bm{x}_{0:t}$, to a sequence, $\bm{x}^*_{0:t}$. \subsection{Consistency Regularization} In this section, we propose regularization strategies to regularize the behaviors of the generator to overcome the difficulties in the training of GANs discussed in section \ref{sec:GAN}. In the time series problem, there can be multiple ways of representing the probability distribution of the data. While we are interested in learning the conditional distribution, $p(\bm{x}_t|\bm{x}_{0:t-1})$, for the data-driven simulation, the conditional distribution should be consistent with the marginal distribution, $p(\bm{x}_t)$, through an integral constraint; \begin{equation} \int p(\bm{x}_t|\bm{x}_{0:t}) p(\bm{x}_{0:t}) d\bm{x}_{0:t} = p(\bm{x}_t). \end{equation} Based on this consistency condition, we aim to regularize the generator such that the marginal distribution of the generated samples, $p_g(\bm{x}_t)$, becomes closer to $p_d(\bm{x}_t)$, \emph{i.e.}, \begin{equation} \label{eqn:cond_marginal} \int p_g(\bm{x}_t|\bm{x}_{0:t}) p_d(\bm{x}_{0:t}) d\bm{x}_{0:t} = p_d(\bm{x}_t). \end{equation} However, since we do not know $ p_g(\bm{x}_t|\bm{x}_{0:t}) $ and $p_d(\bm{x}_t)$ explicitly, we cannot directly evaluate (\ref{eqn:cond_marginal}). Here, we use the maximum mean discrepancy (MMD) to compare the left and right hand sides of (\ref{eqn:cond_marginal}) from the samples drawn from the data and the generator. The MMD is a two-sample test to compare two distributions in a reproducing kernel Hilbert space \cite{Gretton12}. Using the Gaussian kernel, MMD for the samples from two distributions, $\bm{x} \sim p_d(\bm{x})$ and $\bm{x}^* \sim p_g(\bm{x})$, is computed as \begin{equation} \text{MMD}(\bm{x},\bm{x}^*) = \frac{1}{T^2} \left[ \sum_{i=1}^T\sum_{j=1}^T k(\bm{x}_i,\bm{x}_j) + \sum_{i=1}^T\sum_{j=1}^T k(\bm{x}^*_i,\bm{x}^*_j) - 2\sum_{i=1}^T\sum_{j=1}^T k(\bm{x}_i,\bm{x}^*_j) \right], \end{equation} in which \begin{equation} \label{eqn:mmd_kernel} k(\bm{x},\bm{y}) = \exp \left( -\frac{1}{\gamma} \|\bm{x} - \bm{y}\|^2_2 \right). \end{equation} Here, we assume that the sizes of the two samples, $\bm{x}$ and $\bm{x}^*$, are the same ($T$). With the MMD regularization, the optimization problem becomes \begin{equation} \label{eqn:CR-GAN_loss_1} \max_{G}\min_{D} \left\{ \sum_{t=1}^T E_{\bm{x}_{0:t-1} } [\mathcal{L}(\bm{x}_{0:t-1})]\right\} + \lambda \mathop{E}_{\substack{\bm{x} \sim p_d \\ \bm{x}^* \sim p_g}} [ \text{MMD}(\bm{x},\bm{x}^* )], \end{equation} in which $\lambda$ is a regularization coefficient. In this formulation, the modified GAN objective function makes the generator to learn the temporal evolution of the underlying probability distribution, while the MMD regularization enforces the marginal distribution of the generated samples to be similar to the marginal distribution of the data. Now, we introduce another consistency condition based on the predictive distributions of a multiple-step prediction. In this study, we are interested in predicting the future system state as, \begin{equation} \bm{x}_{t+1},\cdots,\bm{x}_{t+H} \sim p(\bm{x}_{t+1},\cdots,\bm{x}_{t+H}|\bm{x}_{0:t}), \end{equation} where $H$ is the prediction horizon. Instead of directly drawing a sample from the future joint probability distribution, the samples are sequentially drawn from the condition distributions, \begin{align} \bm{x}^*_{t+1} &\sim p(\bm{x}_{t+1}|\bm{x}_{0:t}), \nonumber \\ \bm{x}^*_{t+2} &\sim p(\bm{x}_{t+2}|\bm{x}_{0:t},\bm{x}^*_{t+1}), \nonumber \\ &\vdots \nonumber \\ \bm{x}^*_{t+H} &\sim p(\bm{x}_{t+H}|\bm{x}_{0:t},\bm{x}^*_{t+1:t+H-1}). \nonumber \end{align} While this sequential sampling procedure is straightforward, there may be an accumulation of the error in each sequential sampling step, which makes the predictive distribution diverge from the ground truth. To reduce such divergence, we impose a second consistency condition through a regularization on the generator. The second consistency condition is motivated to enforce \begin{align} \label{eqn:multistep_pdf} p_g(\bm{x}^*_{t+n}|\bm{x}_{0:t}) & = \int p_g(\bm{x}^*_{t+1}|\bm{x}_{0:t}) \prod_{i=1}^{n-1} p_g(\bm{x}^*_{t+i+1}|\bm{x}_{0:t},\bm{x}^*_{t+1:t+i}) d\bm{x}^*_{t+1:t+i}\\ &=p_d(\bm{x}_{t+n}|\bm{x}_{0:t}). \nonumber \end{align} However, it is challenging to impose a regularization by directly comparing conditional distributions. Instead, we propose to regularize the marginal distributions for the temporal difference. Define a $n$-th order temporal difference as, \[ \Delta_n \bm{x}_t = \bm{x}_{t+n} - \bm{x}_t. \] Then, we can impose a consistency condition by comparing $p_g(\Delta_n \bm{x}_t)$ and $p_d(\Delta_n \bm{x}_t)$, instead of directly dealing with the predictive distribution (\ref{eqn:multistep_pdf}). Here, we propose two models to impose the second consistency condition. In the first method, we can simply add another MMD regularizer in the optimization formulation in (\ref{eqn:CR-GAN_loss_1}); \begin{align} \label{eqn:CR-GAN_loss_MMD} \max_{G}\min_{D} \left\{ \sum_{t=1}^T E_{\bm{x}_{0:t-1} } [\mathcal{L}(\bm{x}_{0:t-1})]\right\} &+ \lambda_1 \mathop{E}_{\substack{\bm{x} \sim p_d \\ \bm{x}^* \sim p_g}} [ \text{MMD}(\bm{x},\bm{x}^* )] \\ &+ \lambda_2 \mathop{E}_{\substack{\Delta_n \bm{x} \sim p_d \\ \Delta_n \bm{x}^* \sim p_g}} [ \text{MMD}(\Delta_n \bm{x},\Delta_n \bm{x}^* )] . \nonumber \end{align} In the second approach, we can use another discriminator and add a new GAN objective function for the marginal distribution; \begin{align} \label{eqn:CR-GAN_loss_GAN} \max_{G}\min_{D,F_\Delta }& \left\{ \sum_{t=1}^T E_{\bm{x}_{0:t-1} } [\mathcal{L}(\bm{x}_{0:t-1})]\right\} + \lambda_1 \mathop{E}_{\substack{\bm{x} \sim p_d \\ \bm{x}^* \sim p_g}} [ \text{MMD}(\bm{x},\bm{x}^* )] \\ &+ E_{\Delta_n \bm{x}}[\log F_\Delta(\Delta_n \bm{x})] + E_{\Delta_n\bm{x}^*}[\log (1-F_\Delta(\Delta_n\bm{x}^*))]. \nonumber \end{align} Since $F_\Delta(\cdot)$ does not consider the temporal dependence, we can use a simple multilayer feed-forward neural network. Hereafter, we use CR-GAN (Consistency-Regularized GAN) to denote the time series GAN model with only the first consistency condition (\ref{eqn:CR-GAN_loss_1}), and CR-GAN-M$_n$ and CR-GAN-G$_n$ to denote the GAN models with the MMD (\ref{eqn:CR-GAN_loss_MMD}) and with the marginal discriminator (\ref{eqn:CR-GAN_loss_GAN}), respectively, trained for the $n$-th order temporal difference, $\Delta_n \bm{x}_t$. \subsection{Optimization} In practice, CR-GAN is trained alternating between the discriminator and generator steps to update the weights of the discriminator ($\bm{\theta}_D$) and the generator ($\bm{\theta}_G$) by using a stochastic gradient descent method (SGD). \vspace{0.3cm} \paragraph{Discriminator Step} Given a training data, $ \{\bm{x}_0,\cdots,\bm{x}_T\}$, the objective function is computed as \begin{enumerate} \item Update the hidden states of the generator ($\Psi_G$) and discriminator RNN ($\Psi_D$) using the same data; \begin{align} \bm{h}^G_t &= \Psi_G(\bm{h}^G_{t-1},\bm{x}_{t-1}), \label{eqn:D_Step_1} \\ \bm{h}^D_t &= \Psi_D(\bm{h}^D_{t-1},\bm{x}_{t-1}). \end{align} \item Draw a sample from the generator; \begin{align} \bm{x}^*_t = F_G(\bm{z},\bm{h}^G_t),~\text{where}~\bm{z} \sim \mathcal{N}(\bm{0},\bm{I}). \end{align} \item Compute the objective function; \begin{align} \mathcal{L}_t = \log (F_D(\bm{x}_t,\bm{h}^D_t)) + \log (1-F_D(\bm{x}_t^*,\bm{h}^D_t)) \end{align} \item Update the weights of the discriminator, $\bm{\theta}_D$, by using a SGD; \begin{align} \label{eqn:D_Step_final} \bm{\theta}_D \leftarrow \bm{\theta}_D - \alpha_D\times \text{SGD}\left( \nabla_{\bm{\theta}_D} \frac{1}{T} \sum_{t=1}^T \mathcal{L}_t \right), \end{align} in which $\alpha_D$ is a learning rate. \end{enumerate} \vspace{0.3cm} \paragraph{Generator Step} Given a training data, $ \{\bm{x}_0,\cdots,\bm{x}_T\}$, the objective function and the MMD regularization are computed as \begin{enumerate} \item Repeat the steps 1 $\sim$ 2 of the Discriminator Step to update $\bm{h}^G_t$ and $\bm{h}^D_t$ and draw a sample $\bm{x}^*_t$. \item Compute the objective function; \begin{align}\label{eqn:G_Step_1} \mathcal{L}_t = - \log (F_D(\bm{x}_t^*,\bm{h}^D_t)) \end{align} \item After all $\bm{x}^*_1,\cdots,\bm{x}^*_T$ are sampled in Step 1, compute the MMD loss; \begin{align} \mathcal{R}_{M} = \text{MMD}(\bm{x}_{1:T},\bm{x}^*_{1:T}) \end{align} \item Update the weights of the generator, $\bm{\theta}_G$, by using a SGD; \begin{align}\label{eqn:G_Step_final} \bm{\theta}_G \leftarrow \bm{\theta}_G - \alpha_G\times \text{SGD}\left( \nabla_{\bm{\theta}_G}\left\{ \frac{1}{T}\sum_{t=1}^T \mathcal{L}_t +\mathcal{R}_M\right\} \right), \end{align} in which $\alpha_G$ is a learning rate. \end{enumerate} \vspace{0.3cm} \paragraph{Multiple-step Regularization Step} Given a training data, $ \{\bm{x}_0,\cdots,\bm{x}_T\}$, the regularization is computed by a multiple-step ahead prediction. \begin{enumerate} \item For $t = 1,\cdots,t_f$, update $\bm{h}^G_t$; \begin{equation} \label{eqn:CR_Step_1} \bm{h}^G_t = \Psi_G(\bm{h}^G_{t-1},\bm{x}_{t-1}). \end{equation} \item Draw a sample at $t_f$ from the generator; \begin{equation} \bm{x}^*_{t_f} = F_G(\bm{z},\bm{h}^G_{t_f}),~\text{where}~\bm{z} \sim \mathcal{N}(\bm{0},\bm{I}). \end{equation} \item For $t = t_f+1,\cdots,T$, generate a sequence of prediction; \begin{align} \bm{h}^G_t &= \Psi_G(\bm{h}^G_{t-1},\bm{x}^*_{t-1}), \\ \bm{x}^*_{t} &= F_G(\bm{z},\bm{h}^G_{t}),~\text{where}~\bm{z} \sim \mathcal{N}(\bm{0},\bm{I}). \label{eqn:CR_Step_2} \end{align} \item Prepare the time difference data sets, $\bm{X} =\{\Delta_n \bm{x}_{t_f},\cdots,\Delta_n \bm{x}_{T-n}\}$ and $\bm{X}^* = \{\Delta_n \bm{x}^*_{t_f},\cdots,\Delta_n \bm{x}^*_{T-n}\}$ \item (GAN) Update $\bm{\theta}_\Delta$ (weights of $F_\Delta$) and $\bm{\theta}_G$ from the GAN objective; \begin{align} \bm{\theta}_\Delta &\leftarrow \bm{\theta}_\Delta - \alpha_\Delta \times \text{SGD}\left( \nabla_{\bm{\theta}_\Delta} \frac{1}{m} \sum_{i=1}^m \left\{ \log (F_\Delta (\bm{X}_i)) + \log(1-F_\Delta(\bm{X}_i^*)) \right\} \right), \label{eqn:CR_Step_3} \\ \bm{\theta}_G &\leftarrow \bm{\theta}_G - \alpha_G \times \text{SGD}\left( \nabla_{\bm{\theta}_G} \frac{1}{m} \sum_{i=1}^m \left\{ - \log(F_\Delta(\bm{X}^*_i)) \right\} \right), \label{eqn:CR_Step_4} \end{align} where $m = T-t_f-n+1$, and $\bm{X}_i = \Delta_n\bm{x}_{t_f+i-1}$. \item (MMD) Update $\bm{\theta}_G$ from the MMD regularization \begin{align} \label{eqn:CR_Step_5} \bm{\theta}_G \leftarrow \bm{\theta}_G - \alpha_G \times \text{SGD}\left( \lambda_2 \nabla_{\bm{\theta}_G} \text{MMD}(\bm{X},\bm{X}^*) \right), \end{align} \end{enumerate} A pseudocode for the training algorithm is shown in Algorithm \ref{alg:CR-GAN}. In CR-GAN-G$_n$ the generator should satisfy two discriminators simultaneously, and similarly in CR-GAN-M$_n$ the generator is regularized by two marginal distribution. In these cases, it is found empirically that having multiple generator updates for one discriminator update, \emph{i.e.}, $n_g \ge 2$ in Algorithm \ref{alg:CR-GAN}, provides a better performance. \begin{algorithm}[!tbh] \caption{Training of CR-GAN} \label{alg:CR-GAN} \textbf{Input}: Data ($\mathcal{\bm{X}} = \bm{x}_{0:T}$), size of the mini-batch ($n_b$), length of the training sequence ($t_s$), forecast start time ($t_f$), regularization coefficients ($\lambda_1,\lambda_2$), learning rates ($\alpha_D,\alpha_G,\alpha_{\Delta}$), maximum number of SGD iteration ($k_{max}$), number of the generator sub-iterations ($n_g$) \begin{algorithmic}[1] \STATE Initialize the weights, $\bm{\theta}_G$, $\bm{\theta}_D$, $\bm{\theta}_\Delta$ \FOR{$k=1,k_{max}$} \STATE Randomly sample a mini-batch from $\mathcal{\bm{X}}$; $\bm{x}_{0:t_s}^{(1)},\cdots, \bm{x}_{0:t_s}^{(n_b)}$ \STATE Update $\bm{\theta}_D$ from the Discriminator Step (\ref{eqn:D_Step_final}) \IF{CR-GAN-G} \STATE Update $\bm{\theta}_\Delta$ from the Mutiple-step Regularization Step (\ref{eqn:CR_Step_3}) \ENDIF \FOR{$j=1,n_g$} \STATE Update $\bm{\theta}_G$ from the Generator Step (\ref{eqn:G_Step_final}) \IF{CR-GAN-G} \STATE Update $\bm{\theta}_G$ from the Multiple-step Regularization Step (\ref{eqn:CR_Step_4}) \ELSIF{CR-GAN-M} \STATE Update $\bm{\theta}_G$ from the Multiple-step Regularization Step (\ref{eqn:CR_Step_5}) \ENDIF \ENDFOR \ENDFOR \end{algorithmic} \end{algorithm} \section{Numerical experiments} \label{sec:results} In this section, the behaviors of CR-GAN are studied from numerical experiments for three data sets. The data sets are generated from an autoregressive process of order one with Bi-Gaussian noise, a noisy observation of the Mackey-Glass time series, and a random Lorenz system. The structure of the artificial neural networks is kept the same for all three experiments. We assume that the dimension of the random input, $\bm{z}_t$, is equal to the dimension of the time series data, $\bm{x}_t$, \emph{i.e.}, $\dim(\bm{z}_t) = \dim(\bm{x}_t)$. The artificial neural network is trained by using a variant of SGD, ADAM \cite{Kingma15}, with a minibath size of 100. The initial learning rate is set to $\alpha_D = \alpha_G = \alpha_{\Delta} = 5\times10^{-5}$, and gradually reduced to $10^{-5}$ by using the cosine learning-rate decay schedule \cite{Loshchilov17}. The total number of SGD iterations is set to $40,000$. A scaled variable, $\widehat{\bm{x}}_t$, is used for the input and output of the artificial neural network. The time series data, $\bm{x}_t \in \mathbb{R}^d$, is scaled such that \begin{equation} \widehat{x}_{t_i} = \frac{x_{t_i} - \min(x_i)}{\max(x_i) - \min(x_i)},~\text{for}~i=1,\cdots,d, \end{equation} in which $\max(x_i)$ and $\min(x_i)$, respectively, indicate the maximum and minimum values of the $i$-th dimension of $\bm{x}_t$. In other words, $\widehat{\bm{x}}_t$ is defined in a hypercube, $\widehat{\bm{x}}_t \in [0,1]^{d}$. From this scaling, we use the sigmoid function in the last layer of the generator to guarantee that the generated sample $\bm{x}^*_t \in (0,1)^d$, which also regularizes the behavior of the generator. The detailed model structures are shown in Appendix \ref{sec:arch}. We find that a pre-training of $\Psi_G$ and $\Psi_D$ helps CR-GAN converge faster. The pre-training can be done by adding a linear layer to $\Psi_G$ (and $\Psi_D$) and train as a simple regression model with the standard mean-square loss function. After the pre-training, the linear layers are discarded. Once the whole training is completed, the data-driven forecast is performed by a Monte Carlo simulation \cite{Yeo21,Yeo19}. The Monte Carlos method is outlined in Appendix \ref{sec:MC}. \subsection{Bi-Gaussian Auto-Regressive Process} \label{subsec:AR} \begin{figure} \centering \includegraphics[width=0.95\textwidth]{figures/BiNormal_Traj.pdf} \caption{Trajectories generated by CR-GAN (solid lines). The forecast starts at $t=0$. The solid circles denote the ground truth data.} \label{fig:binorm_traj} \end{figure} For the first numerical experiment, we consider an autoregressive process of order 1; \begin{equation} x_{t+1} = 0.8 x_t + \epsilon_t, \end{equation} where the noise process is \begin{equation} \epsilon_t \sim 0.5 \mathcal{N}(-2 \sigma,\sigma^2) + 0.5 \mathcal{N}(2\sigma,\sigma^2). \end{equation} The noise parameter $\sigma = 0.2$ is used. The length of the time series data used for the training is $5\times 10^4$. Because of the simplicity of the problem, we only consider CR-GAN for the autoregressive process. Fig. \ref{fig:binorm_traj} shows the trajectories generated by CR-GAN together with the ground truth data. The time series data is provided to CR-GAN for $t \in [-50,0]$ and CR-GAN makes predictions for $t \in [1,100]$, \emph{i.e.}, $\bm{x}^*_{1:100}$. \begin{figure} \centering \includegraphics[width=0.95\textwidth]{figures/BiNormal_Comp_Dist.pdf} \caption{Comparison of the estimated probability distribution of $\epsilon_t$. The histograms are computed from (a) data, (b) CR-GAN without any regularization, (c) CR-GAN with $\gamma = 0.2$, and (d) CR-GAN with $\gamma = 1.6$. The regularization parameter is fixed, $\lambda = 100$.} \label{fig:binorm_comp_dist} \end{figure} Fig. \ref{fig:binorm_comp_dist} shows the estimated noise from the generated samples, $\bm{x}^*_{1:100}$. A Monte Carlo simulation with 1,000 samples is performed to compute $x^*_{1:100}$. The histograms in Fig. \ref{fig:binorm_comp_dist} are evaluated by estimating the noise as \begin{equation} \epsilon^*_t = x^*_{t+1} - 0.8 x^*_t~\text{for}~t=1,\cdots,99. \end{equation} In Fig. \ref{fig:binorm_comp_dist} (c), It is shown that CR-GAN makes a very good approximation of the ground truth distribution (Fig. \ref{fig:binorm_comp_dist} a), compared to the GAN model with the consistency regularization (Fig. \ref{fig:binorm_comp_dist} b). As shown in (\ref{eqn:mmd_kernel}), the MMD depends on a scale parameter, $\gamma$, of the Gaussian kernel. Fig. \ref{fig:binorm_comp_dist} (c) and (d) show the effects of $\gamma$ on the estimation of the probability distribution. At $\gamma = 1.6$ (Fig. \ref{fig:binorm_comp_dist} d), although the estimated probability distribution has a bi-modal structure, the overall shape becomes noticeably different from the ground truth. \begin{table} \center{ \caption{Kullback-Leibler divergence for CR-GAN trained with the regularization coefficient, $\lambda = 100$. Here, $\gamma = \infty$ indicates CR-GAN without the MMD regularization.} \label{tbl:binormal_kl} \begin{tabular}{c|ccc} \hline \hline $\gamma$ & 0.2 & 1.6 & $\infty$ \\ \hline $D_{KL}$ & 0.0011 & 0.0178 & 0.1425\\ \hline \hline \end{tabular} } \end{table} To make a quantitative comparison, the Kullback-Leibler (KL) divergence is computed for discrete probability distributions as \begin{equation} D_{KL}(\bm{Q}\|\bm{P}) = \sum_{i=1}^K Q_i \log \frac{Q_i}{P_i}, \end{equation} where $\bm{P}$ and $\bm{Q}$ denote the empirical probability distributions for the data and the generated samples, respectively. The KL divergence is computed in the interval, $(-1.3,1.3]$ with the bin size of $\delta = 0.05$. It is shown that, when $\gamma = 0.2$, the KL divergence is less than 1\% of the $D_{KL}$ of the GAN without the MMD regularization. The KL divergence becomes larger for $\gamma = 1.6$, but it is still about 15\% of $D_{KL}$ without the MMD regularization. \begin{figure} \includegraphics[width=0.99\textwidth]{figures/BiNormal_KL_Loss_2.pdf} \caption{Effects of the MMD parameters. (a) Effects of the scale parameter, $\gamma$, for a fixed regularization coefficient $\lambda = 100$. (b) Effects of $\lambda$ for $\gamma = 0.2$ ({\color{blue}$\circ$}) and $1.6$ ({\color{orange}$\bullet$}). (c) $D_{KL}$ as a function of the loss ratio. } \label{fig:binormal_kl} \end{figure} There are two parameters in the MMD regularization for the first consistency condition; the regularization coefficient, $\lambda$, and the scale parameter of the MMD kernel, $\gamma$. To investigate the effects of $\gamma$, we fix $\lambda = 100$ and calculated $D_{KL}$ for a range of $\gamma$ (Fig. \ref{fig:binormal_kl} a). It is shown that $D_{KL}$ remains almost the same for $\gamma \le 0.4$ and then starts to increase as $\gamma$ becomes larger. In Fig. \ref{fig:binormal_kl} (b), now the effects of $\lambda$ are shown for $\gamma = 0.2$ and 1.6. For a fixed $\gamma$, it is shown that $D_{KL}$ first decreases and then starts to increase, as $\lambda$ increases. To achieve the similar $D_{KL}$, $\lambda$ for $\gamma = 1.6$ needs to be about two orders of magnitude larger than $\lambda$ for $\gamma = 0.2$. The huge difference in the optimal $\lambda$ will make it difficult to tune the regularization parameter in practice. In Fig. \ref{fig:binormal_kl} (c), it is shown that the results in Fig. \ref{fig:binormal_kl} (a -- b) are collapsed into one curve, when scaled by the ratio between the loss function and the regularization in (\ref{eqn:G_Step_final}). Define ``Loss ratio'' as \begin{equation} \text{Loss ratio} = \frac{\mathcal{R}_M}{\frac{1}{T}\sum_{i=1}^T \mathcal{L}_t}. \end{equation} The Loss ratio is computed by the average over the last 5000 iterations of the SGD solver. It is shown that $D_{KL}$ stays almost flat when the Loss ratio is in the range of $(0.002,0.036)$. When the Loss ratio is too small ($<0.002$), the MMD regularization does not play a significant role in the optimization problem, which makes $D_{KL}$ larger. On the other hand, when the Loss ratio becomes too large ($>0.04$), the generator tries to satisfy the marginal distribution, instead of learning the conditional distribution, which again makes $D_{KL}$ grow. Note that Fig. \ref{fig:binormal_kl} (c) encompasses $\gamma \in [0.05,1.6]$ and $\lambda \in [4,10^{4}]$. The results suggest that, instead of trying to find the optimal $\gamma$ or $\lambda$, it is more important to tune the MMD regularization parameters such that the relative magnitude between the MMD regularization and the generator loss function is within the range shown in Fig. \ref{fig:binormal_kl} (c). \subsection{Mackey-Glass Time Series} \label{subsec:MG} The Mackey-Glass dynamical system is a nonlinear dynamical system with a time-delay dynamics \cite{Mackey77}. The equation for the Mackey-Glass dynamical system is \begin{equation} \label{eqn:MG} \frac{d \phi(t)}{dt} = \frac{a \phi(t-\tau)}{1+\phi^b(t-\tau)} - c \phi(t). \end{equation} The data is generated for the the parameters $(a,b,c,\tau) = (0.2,10,0.1,17)$, where the Mackey-Glass dynamical system becomes chaotic \cite{Farmer82,Gers01}. The time interval between consecutive data points is set to $\delta t = 1$. The time delay parameter ($\tau=17$) indicates that the time evolution at time step $t$ depends on the information at $t-\tau$, which is 17 time steps ago. After the noiseless data is generated by solving (\ref{eqn:MG}), noisy observations are made by adding white noise, \begin{equation} x_t = \phi(t_0 + t \delta t)+\epsilon_t, \end{equation} in which \begin{equation} \epsilon_t \sim 0.5 \mathcal{N}(3 \sigma,\sigma^2) + 0.5 \mathcal{N}(-3\sigma,13\sigma^2). \end{equation} Here, we use $\sigma = sd(\phi)\times 0.05$, in which $sd(\phi)$ denotes the standard deviation of the noiseless data, $\phi(t)$. Then, the standard deviation of $\epsilon_t$ becomes 20\% of $sd(\phi)$. The time series data and the probability distribution of $\epsilon_t$ are shown in Fig. \ref{fig:MG_traj}. Five different models are trained; CR-GAN, CR-GAN-M$_1$, CR-GAN-M$_5$, CR-GAN-D$_1$, and CR-GAN-D$_5$. The MMD regularization coefficient of the first consistency condition, $p_g(\bm{x})$, is set to $\lambda_1 = 500$. The second MMD regularization coefficients for CR-GAN-M$_1$ and CR-GAN-M$_5$ are set to $\lambda_2=500$ and 200, respectively. Note that, contrary to CR-GAN-M$_n$, CR-GAN-D$_n$ does not have the second regularization coefficient, $\lambda_2$. For all the cases, the MMD kernel scale parameter is fixed at $\gamma = 0.2$. \begin{figure} \centering \includegraphics[width=0.99\textwidth]{figures/MG_Data.pdf} \caption{Noisy observation of the Mackey-Glass time series. In (a), the solid line is the noiseless Mackey-Glass time series and the hollow circles denote the noisy observations, and (b) shows the probability distribution of the observation noise.} \label{fig:MG_traj} \end{figure} Fig. \ref{fig:MG_pred} shows a 500-step prediction of the noisy Mackey-Glass time series data by CR-GAN-D$_5$. The time series data is provided to CR-GAN-D$_5$ for $t = -100 \sim 0$, and a Monte Carlos simulation with 1,000 samples is performed to compute the mean and 95\% prediction intervals for $t = 1 \sim 500$. Since the Mackey-Glass time series is chaotic, it is shown that, in general, the prediction interval widens as the time increases. Also, the mean of the prediction stays very close to the ground truth data up to $t=200$, then starts to deviate. As observed in the previous studies using RNN, the width of the prediction interval is not a monotonically increasing function of time \cite{Yeo19}. The width of the prediction interval may increase or decrease following the oscillatory pattern of the time series data. \begin{figure} \centering \includegraphics[width=0.99\textwidth]{figures/MG_GAN_Pred.pdf} \caption{500-step prediction of the noisy Mackey-Glass time series. The solid line and two dashed lines indicate the mean and 95\% prediction intervals, respectively. The time series data are shown as the solid circles. The prediction starts at $t=0$.} \label{fig:MG_pred} \end{figure} For a quantitative study, we estimate the empirical coverage probabilities (ECP) for five prediction intervals, $\text{PI}(p)$ for $p \in \{0.6,0.7,0.8,0.9,0.95\}$. The empirical coverage probability is computed as \begin{equation} \text{ECP}(p) = \frac{1}{N H}\sum_{i=1}^N \sum_{t=1}^H \chi_{\text{PI}^i_t(p)}(x^{* (i)}_t). \end{equation} Here, $\text{PI}^i_t(p)$ is the prediction interval with the coverage probability $p$ at time step $t$ for the $i$-th trajectory, $\chi_A(x)$ is an indicator function, which is one if $x \in A$ and zero otherwise. In other words, $\text{ECP}(p)$ is estimated by computing the fraction of the ground truth data covered by $\text{PI}(p)$. The prediction interval, $\text{PI}^i_t(p)$, is evaluated by a Monte Carlo simulation with $1,000$ samples. The total number of trajectories to compute ECP is $N=500$ and the prediction horizon is set to $H = 1000$. The difference, $\text{ECP}(p) - p$, provides a quantitative measure for an error in the predictive probability distribution. \begin{table} \center{ \caption{Empirical Coverage Probability (ECP) for $1000$-step prediction of the noisy observation of the Mackey-Glass time series. SAD indicates the Sum of Absolute Difference between ECP and $p$.} \label{tbl:MG_Emp_Cov} \begin{tabular}{c|cccccc} \hline \hline $p$ & RNN & CR-GAN & $\text{CR-GAN-M}_1$ & $\text{CR-GAN-G}_1$ & $\text{CR-GAN-M}_5$ &$\text{CR-GAN-G}_5$ \\ \hline 0.60 & 0.659 & 0.634 & 0.566 & 0.619 & 0.608 & 0.599\\ 0.70 & 0.760 & 0.731 & 0.662 & 0.712 & 0.702 & 0.693\\ 0.80 & 0.854 & 0.825 & 0.763 & 0.802 & 0.797 & 0.791\\ 0.90 & 0.936 & 0.915 & 0.870 & 0.894 & 0.892 & 0.890\\ 0.95 & 0.973 & 0.958 & 0.928 & 0.942 & 0.943 & 0.942\\ \hline SAD & 0.232 & 0.113 & 0.161 & 0.047 & 0.028 & 0.035\\ \hline \hline \end{tabular} } \end{table} The empirical coverage probability is shown in Table \ref{tbl:MG_Emp_Cov}. Here, RNN refers to a standard RNN model with the Gaussian distribution assumption. A two-layer Gated Recurrent Unit with 128 hidden states is used for the RNN, which is the same RNN structure used in CR-GAN models. It is shown that ECPs of RNN are always larger than $p$. At $p=0.6$ and 0.7, there are about 6\% difference between PI and ECP. CR-GAN shows a better performance compared to RNN. The sum of absolute difference, \[ \text{SAD} = \sum_p |\text{ECP}(p) - p|,~\text{for}~p \in \{0.6,0.7,0.8,0.9,0.95\}, \] of CR-GAN is less than half of SAD of RNN. Still, CR-GAN shows about 3\% difference at $p = 0.6$ and 0.7. When the second consistency condition is imposed by the first-order temporal difference, $p(\Delta_1 x_t)$, CR-GAN-M$_1$ does not show noticeable improvement over CR-GAN in terms of SAD, while SAD of CR-GAN-G$_1$ is less than half of CR-GAN. When the fifth-order temporal difference, $p(\Delta_5 x_t),$ is used for the regularization, CR-GAN-M$_5$ and CR-GAN-D$_5$, SAD is reduced further. While CR-GAN-M$_5$ shows the best performance in terms of SAD, the difference between CR-GAN-M$_5$ and CR-GAN-D$_5$ is only marginal. It should be noted that, while CR-GAN-M$_5$ require a careful tuning of both $\lambda_1$ and $\lambda_2$, CR-GAN-D$_5$ has one less tuning parameter, \emph{i.e.}, only $\lambda_1$, which makes it easier to train. It is also found that using a higher order temporal difference, \emph{e.g.}, $p(\Delta_{10} x_t)$, does not improve the prediction accuracy. SADs of CR-GAN-M$_{10}$ and CR-GAN-D$_{10}$ are 0.041 and 0.072, respectively. \subsection{Lorenz System} \label{subsec:Lorenz} We now investigate the behaviors of CR-GAN by using the random Lorenz system \cite{Gradisek00}; \begin{equation} \frac{d}{dt} \begin{bmatrix} x \\ y \\ z \end{bmatrix} = \begin{bmatrix} 10(y - x) \\ x(28-z)-y \\ xy - \frac{8}{3}z \end{bmatrix} + \begin{bmatrix} 4 & 5 & 3 \\ 5 & 5 & 6 \\ 3 & 6 & 10 \end{bmatrix} \begin{bmatrix} \eta_x(t) \\ \eta_y(t) \\ \eta_z(t) \end{bmatrix}, \end{equation} in which $\eta_i$ denotes the Gaussian white noise. The sampling interval of the time series data set is $\delta t = 0.01$. Fig. \ref{fig:Lorenz_data} shows the time series data. For the random Lorenz system, we mainly consider CR-GAN, CR-GAN-D$_1$ and CR-GAN-D$_5$, because, while CR-GAN-M$_n$ shows a similar performance with CR-GAN-D$_n$, it is difficult to tune the two free parameters, $\lambda_1$ and $\lambda_2$. In the training, $\lambda_1 = 500$ and $\gamma = 0.2$ are used for all the models. \begin{figure} \centering \includegraphics[width=0.7\textwidth]{figures/Lorenz_Data.pdf} \caption{Sample trajectories of the random Lorenz system. The horizontal axis is the time steps.}\label{fig:Lorenz_data} \end{figure} Fig. \ref{fig:Lorenz_sample} shows ten trajectories from the Monte Carlo simulation of CR-GAN-D$_5$. The time series data for $t\in[-100,0]$ are used to make a prediction of the next 200 time steps. In Fig. \ref{fig:Lorenz_sample} (a), it is shown that there is a bifurcation of the trajectories of $x_t$ right after the prediction begins. On the other hand, the trajectories of $z_t$ show oscillatory patterns similar to the ground truth data. \begin{figure} \centering \includegraphics[width=0.99\textwidth]{figures/Lorenz_sample_traj.pdf} \caption{Monte Carlo samples for the prediction of the random Lorenz system. The hollow circles denote the ground truth data. The horizontal axes are the time steps.}\label{fig:Lorenz_sample} \end{figure} Fig. \ref{fig:Lorenz_pred} shows a 500-step prediction of the random Lorenz system by using CR-GAN-D$_5$. It is shown that the prediction intervals of both $x_t$ and $y_t$ rapidly increase from the beginning of the prediction, which is consistent with the bifurcation observed in Fig. \ref{fig:Lorenz_sample} (a). For all the components of the Lorenz system ($x_t,y_t,z_t$), the 95\% prediction intervals first increase and then decrease before reaching a stationary state for $t > 150$. \begin{figure} \centering \includegraphics[width=0.7\textwidth]{figures/Lorenz_Pred.pdf} \caption{500-step ahead prediction of the random Lorenz system by using CR-GAN-D$_5$. The solid line and two dashed lines indicate the mean and 95\% prediction intervals, respectively. The time series data are shown as the solid circles. The prediction starts at $t=0$. The horizontal axes are the time steps.} \label{fig:Lorenz_pred} \end{figure} The average empirical coverage probability (AECP) is shown in Table \ref{tbl:Lorenz_Emp_Cov}. Here, AECP is computed by an average of ECPs for $x_t$, $y_t$, and $z_t$. Again, it is shown that CR-GAN models have much smaller AECP compared to RNN. Although AECP of CR-GAN-G$_5$ is smaller than that of CR-GAN-G$_1$, the difference is only marginal. CR-GAN-M$_5$ is trained with $\lambda_2 = 50$ and $\gamma = 0.2$. It is shown that AECP of CR-GAN-M$_5$ is much larger than that of CR-GAN-D$_1$, CR-GAN-D$_5$, or even CR-GAN, which may be due to a suboptimal choice of the regularization coefficients, $\lambda_1$ and $\lambda_2$. Because of the interaction of the two MMD regularizations in CR-GAN-M$_n$, it is difficult to find an optimal $\lambda_1$ and $\lambda_2$. On the other hand, CR-GAN-D$_n$ has only one regularization coefficient, $\lambda_1$, which can be chosen, as suggested in Fig. \ref{fig:binormal_kl} (c). \begin{table} \center{ \caption{Average Empirical Coverage Probability. SAD indicates the Sum of Absolute Difference.} \label{tbl:Lorenz_Emp_Cov} \begin{tabular}{c|ccccc} \hline \hline $p$ & RNN & CR-GAN & $\text{CR-GAN-G}_1$ & $\text{CR-GAN-G}_5$ & $\text{CR-GAN-M}_5$\\ \hline 0.60 & 0.568 & 0.602 & 0.599 & 0.603 & 0.619 \\ 0.70 & 0.671 & 0.707 & 0.704 & 0.701 & 0.721\\ 0.80 & 0.770 & 0.812 & 0.805 & 0.800 & 0.824\\ 0.90 & 0.867 & 0.908 & 0.902 & 0.898 & 0.918\\ 0.95 & 0.919 & 0.954 & 0.949 & 0.946 & 0.955\\ \hline SAD & 0.155 & 0.033 & 0.013 & 0.010 & 0.087\\ \hline \hline \end{tabular} } \end{table} The empirical coverage probability is computed based on the marginal distribution of each component, \emph{e.g.}, $p(x_{t+n}|x_{0:t},y_{0:t},z_{0:t})$. To demonstrate the capability of CR-GAN in the estimation of the joint probability distribution, joint probability distributions between two components are shown in Fig. \ref{fig:Lorenz_density}. The joint probability distributions are computed for the 10-th order temporal difference, \emph{e.g.}, $p(\Delta_{10} x_t, \Delta_{10} y_t)$, of the generated trajectories. Total 1,000 trajectories are generated from different initial sequences. For each trajectory, the ground truth trajectory is used for the first 100 time steps, and CR-GAN-D$_5$ generates the next 500 time steps. A two-dimensional kernel density estimation with a Gaussian kernel is used to compute the joint probability distribution from randomly selected 50,000 samples. It is shown that the joint probability distributions from CR-GAN-D$_5$ are very close the those of the data, while the joint probability distributions from the standard RNN are noticeably different from the ground truth distribution. \begin{figure} \includegraphics[width=0.99\textwidth]{figures/Lorenz_2d_density.pdf} \caption{ Two-dimensional joint probability density functions of the 10-th order temporal difference, $p(\Delta_{10} \bm{x}_t)$, from the ground truth data (a,d), RNN (b,e), and CR-GAN-G$_5$ (c,f). The color contours denote the probability density estimated by a kernel density estimation.}\label{fig:Lorenz_density} \end{figure} The maximum mean discrepancy is used to make a quantitative comparison about the joint probability distributions between different CR-GAN models. The Gaussian kernel used for the computation of MMD, \begin{equation} k(\bm{u},\bm{u}^*) = \exp\left\{ \sum_{i=1}^d -\frac{(u_i-u^*_i)^2}{2\, \sigma_i^2} \right\}, \end{equation} in which $\bm{u}$ and $\bm{u}^*$ denote $d$-dimensional random variables and $\sigma_i$ is the standard deviation of $u_i$. Here, the standard deviations for $(x_t,y_t,z_t)$ are computed from the data. Because the value of MMD is difficult to interpret, a ratio of MMD values between CR-GAN models and RNN is investigated, \[ \Lambda = \frac{\text{MMD(CR-GAN)}}{\text{MMD(RNN)}}. \] Here, $\Lambda$ can be thought as a relative error. The same data to make Fig \ref{fig:Lorenz_density} are used to compute $\Lambda$. Fig. \ref{fig:Lorenz_mmd} shows $\Lambda$ with respect to the order of the temporal difference. The order of the temporal difference is varied from $n=1$ to $n=64$. It is shown that, when the second consistency condition is not imposed (CR-GAN), $\Lambda$ grows rapidly as $n$ increases. At $n=64$, $\Lambda$ of CR-GAN becomes larger than 0.8. On the other hand, CR-GAN-D$_5$ shows only a mild growth of $\Lambda$. Although the second consistency condition is imposed only for the 5-th order temporal difference, $\Lambda$ for $n=32$ still remains less than 0.05. CR-GAN-D$_1$ initially shows similar $\Lambda$ with CR-GAN-D$_5$, which increases rapidly for $4 \le n \le 16$. However, contrary to CR-GAN, $\Lambda$ of CR-GAN-D$_1$ does not increase for for $n ge 32$. At $n=64$, $\Lambda$'s of CR-GAN-D$_1$ and CR-GAN-D$_5$ become roughly the same. \begin{figure} \centering \includegraphics[width=0.8\textwidth]{figures/Lorenz_MMD_Ratio.pdf} \caption{MMD Ratios of CR-GAN (${\color{blue}\bigcirc}$), CR-GAN-D$_1$ (${\color{orange}\bigtriangledown}$), and CR-GAN-D$_5$ (${\color{green}\Box}$) as a function of the order ($n$) of the temporal difference, $\Delta_n \bm{x}_t$.} \label{fig:Lorenz_mmd} \end{figure} \section{Summary} \label{sec:summary} The consistency-regularized generative adversarial network (CR-GAN) is proposed for the data-driven simulation of random dynamical system. The CR-GAN consists of a RNN and a feedforward neural network. The RNN aims to learn the time marching operator, while the feedforward neural network, which takes a white noise as one of the input variables, aims to learn the joint probability distribution of the stochastic process without a distributional assumption and draw a sample from the probability distribution. While GAN provides a flexible framework to learn a complex, high-dimensional joint probability distribution, training a GAN model is notoriously difficult. It is important to note that GAN is not free from the curse of dimensionality, which requires an exponential growth in the number of training samples as the dimensionality of the problem increases. While many of the previous studies focus on regularizing the behavior of the discriminator to facilitate the training, we propose a regularization strategy for the generator, based on the characteristics of the time series problem. The consistency-regularized generative adversarial network aims to learn the conditional distribution of a time series problem, $p(\bm{x}_t|\bm{x}_{0:t})$. The regularization for CR-GAN is based on integral constraints, which relates the conditional to the marginal distributions. The first consistency condition enforces a stationary state condition, \[ \int p_g(\bm{x}_{t+1}|\bm{x}_{0:t})p_d(\bm{x}_{0:t}) d\bm{x}_{0:t} = p_d(\bm{x}_{t+1}), \] by using a two sample test, called the Maximum Mean Discrepancy. The second consistency condition is from the stationarity of the predictive distribution, \[ \int p_g(\Delta_n \bm{x}_t|\bm{x}_{0:t})p_g(\bm{x}_{t_0+1:t}|\bm{x}_{0:t_0}) p_d(\bm{x}_{0:t_0}) d\bm{x}_{0:t} = p_d(\Delta_n \bm{x}_t), \] in which $\Delta_n \bm{x}_t = \bm{x}_{t+n} - \bm{x}_t$, and $1 < t_0 < t$ is the length of an initial spin-up data for CR-GAN. We propose to use either MMD (CR-GAN-M$_n$) or a discriminator (CR-GAN-D$_n$) to impose the second consistency condition. The behaviors of CR-GAN are investigated by using three stochastic processes with varying complexities. First, CR-GAN is used to learn an auto-regressive process of order one, of which noise process is given by a bi-Gaussian distribution. It is clearly shown that the first consistency condition improves the accuracy of CR-GAN in learning the bi-Gaussian noise. In CR-GAN, there are two tuning parameters, one is the scale parameter of the kernel of the MMD, $\gamma$, and the other is the magnitude of the MMD regularization term, $\lambda_1$. In the numerical experiments, it is shown that the ratio of the MMD regularization to the generator loss is more important parameter in the accuracy of CR-GAN, than the individual value of $\gamma$ and $\lambda_1$. It is shown that the Kullback-Leibler divergence between the generator distribution of CR-GAN and the data distribution stays almost constant when the ratio between the MMD regularization and the generator loss is between 0.002 and 0.4, which increases for a smaller ($< 0.002$) or larger ($>0.4$) values, which provides a guideline to tune the hyperparameters. In the second numerical experiments on the noisy observation of the chaotic Mackey-Glass time series, it is shown that the second consistency condition does improve the accuracy of the multiple-step prediction. It is shown that there is virtually no difference between the accuracies of CR-GAN-M$_n$ and CR-GAN-D$_n$. However, while CR-GAN-M$_n$ requires a careful tuning of two regularization coefficients for the MMDs of the first and second consistency conditions, CR-GAN-D$_n$ is relatively easy to train because it has only one regularization coefficient. Finally, CR-GAN is tested against a random Lorenz system. It is shown that CR-GAN-D$_n$ makes a reliable estimation of the joint probability distribution of $\Delta_n \bm{x}_t$. It is shown that CR-GAN-D$_n$ makes a much more stable estimation of the joint probability distribution of $\Delta_n \bm{x}$. Even though CR-GAN-D$_5$ is trained with only the fifth order temporal difference, the error in the joint probability distribution does not increase noticeably up to $\Delta_{32}\bm{x}_t$, while CR-GAN, which trained with only the first consistency condition, shows a rapid increase in the error as the order of the temporal difference increases. In the present study, we only focus on learning from a multivariate time series data. However, it should be noted that training a GAN for complex spatio-temporal processes will suffer from the same difficulties with the multivariate time series, mainly due to the finite size of the training examples. We expect that the similar regularization strategy can be applied for such kind of problems. Recently, a few promising generative models for time series problems have been proposed by using a normalizing flow \cite{Rasul21} or a Wasserstein auto-encoder \cite{Han21}. We believe that the proposed consistency regularization can be applied for those models to improve the stability in the training. \section{Acknowledgement} This work was supported by the Rensselaer-IBM AI Research Collaboration (http://airc.rpi.edu), part of the IBM AI Horizons Network (http://ibm.biz/AIHorizons). \clearpage
{'timestamp': '2021-11-08T02:03:33', 'yymm': '2111', 'arxiv_id': '2111.03126', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03126'}
arxiv
\section{Introduction} Recent advances in Cloud-based Machine Learning Services (CMLS) capabilities have made it possible for individuals to access state-of-the-art algorithms that until recently were only accessible to few. These capabilities, however, come with two major risks: \textit{a)} the leakage of sensitive data as it's being sent to and/or processed by the cloud, and; \textit{b)} the ability of third parties to gain insight into the organization's data by analyzing the output of the ML model in the cloud. Given that organizations must transmit their data to the cloud to use cloud services, the former are faced with three options: \textit{a)} Send the data in encrypted form to the cloud, where it will be decrypted, analyzed and then sent back in encrypted form (e.g., using asymmetric encryption); \textit{b)} Employ Homomorphic Encryption (HE) techniques that enable the cloud to process the data in its encrypted form; and, \textit{c)} apply differential privacy techniques which introduce varying degrees of noise to the data. Each of these approaches, however, has shortcomings. The first option -- decryption in the cloud -- enables the cloud provider unfettered access to the organization's private data, and is unacceptable in many cases. HE keeps the data private, even when it is being processed in the cloud, but it is slow and puts various limitations on the operations that can be performed so as not to prevent the decryption at the end of the process. Other encryption solutions that offer some or all of the capabilities of HE also exist, but they too require cooperation from the service provider (i.e., the cloud-based service) and often have other prerequisites such as non-collusion among participating servers or dedicated hardware. Finally, differential privacy techniques do prevent attackers from inferring specific details from the data, but they do not prevent obtaining a general sense of the processed data and they come with the price of reduced performance. In this study we propose One Way Scrambling by Deconvolution (OWSD\xspace), an approach that provides the main advantage of Homomorphic encryption---not sharing the unencrypted data with any party, including the CMLS---but with a computational overhead that is smaller by orders of magnitude. Our approach uses a randomly-initialized deconvolutional architecture to scramble the input, which is then sent to the CMLS. The CMLS processes the input in the same manner as it would any unencrypted data, and produces a classification vector. Finally, a small ``translator'' neural architecture within the organization receives the classification vector produced by the cloud and combines it with an embedding of the original image to predict the classification the cloud service would have given to the original image. OWSD\xspace has several important advantages compared to existing methods. First, the use of randomly-initialized deconvolutional networks creates scrambled images that are both incomprehensible to human observers and whose classification in the cloud does not disclose their original label. Secondly, as the deconvolutional network is randomly initialized and not trained, replacing the ``key'' (i.e., network weights values) of our scrambling mechanism is computationally inexpensive, as we only need to retrain our translator architecture. Moreover, multiple scrambling keys can be used simultaneously, thus both improving OWSD\xspace's performance and making decryption efforts more challenging. Thirdly, our approach does not require any coordination with the CMLS. Our contributions in this study are as follows: \begin{itemize} \item We present OWSD\xspace, a scrambling-based approach that has many of the advantages of HE at a fraction of the computational cost. \item We perform extensive evaluation and show that our approach can reach up to 99.9\% of the performance of the CMLS when the number of labels in the confidential data is smaller than that of the cloud. This is also the case when the labels of the confidential data are not in the cloud's training data (i.e., transfer learning). \item We perform an extensive empirical analysis of our approach and provide an upper bound on the number of images that can be securely scrambled by any one key of our approach. \end{itemize} \section{Related Work} Existing solutions can be roughly divided into two groups: encryption-based and differential privacy-based. \subsection{Encryption-based solutions} In this study we focus on approaches that enable the application of privacy-preserving Machine Learning (ML) in the cloud. These solutions can also be divided into two groups: one in which the cloud-based service provider has access to the plaintext, and one in which it does not. The former group of solutions utilizes common public/private key settings (e.g., RSA \cite{milanov2009rsa}) and is in widespread use. In Li, Ping, et al. \cite{li2018privacy}, the authors present a multi-step framework for the exchange of public keys. A semi-honest model -- a scenario where the cloud provider is not compromised -- is also assumed. Similar approaches have also been proposed by \cite{li2018privacy,li2018privacymulti}. The latter group of solutions, where the cloud provider does not have access to the plaintext, can be divided into hardware and software-based solutions. In hardware-based solutions, multiple studies \cite{hunt2018chiron,tramer2018slalom,hynes2018efficient} utilize the SGX architecture which possess a secure enclave for the processing of sensitive information. In Chiron \cite{hunt2018chiron}, for example, the authors demonstrate how SGX could be effectively used to run deep neural architectures. This approach, while effective, requires the installation of a dedicated client both by the client and the service provider, as well as adaptation of the ML model, and are costly and difficult to implement. Software-based encryption solutions that without the plaintext from the CMLS, though diverse, mostly revolve around the use of HE. In \cite{li2017multi} the authors propose two Fully Homomorphic Encryption (FHE) schemes for privacy-preserving deep learning. In \cite{hesamifard2018privacy} and \cite{hesamifard2017privacy}, the authors demonstrated that it is feasible to train neural networks using encrypted data, while in \cite{gilad2016cryptonets} the authors detailed a method to convert learned neural networks to neural networks that can be applied to encrypted data (using leveled HE). While they enable full protection of one's data, Homomorphic solutions are slow, require large amount of memory and require prior knowledge of the type of queries, so that the appropriate HE scheme can be selected to encrypt the raw data \cite{li2017multi}. \subsection{Differential privacy-based solutions} Differential privacy is a general term for techniques that obfuscate the data (i.e., inject noise) in order to ensure that the details of individual records cannot be inferred \cite{dwork2008differential}. Generally, these techniques sacrifice some accuracy in the interest of privacy. The main drawback of this approach is that there is still a way of inferring the general type and characteristics of the data. In \cite{bonawitz2017practical} the authors use aggregations of data collected from mobile devices, which are then sent to a CMLS. A similar approach is presented in \cite{yang2018machine,osia2020hybrid}, who also incorporate the injection of noise into the data. A different approach is presented in \cite{wang2018not}, where a deep architecture is divided into two parts: the smaller (initial part) is installed locally on the client, and the bulk of the architecture is in the cloud. The data passes through the client (compressed and encrypted) and then sent to the cloud. Noise is also added to ensure differential privacy. While the latter solution bears some similarity to our proposed approach, the two networks have to be trained jointly and cooperation between the cloud and the client is necessary. Moreover, the cloud-based provider has access to the final classifications and has some ability to reconstruct the data---a shortcoming not shared by OWSD\xspace. \section{The Proposed Method} \label{sec:proposedMethod} Our proposed approach is presented in Figure \ref{fig:encrypArchitecture}. OWSD\xspace consists of three components: \textit{a)} an \textit{encoder}, that creates an embedding of the original image; \textit{b)} a \textit{generative model}, that receives the embedding as input and creates the encrypted image, and; \textit{c)} an \textit{internal inference network}, which receives the classification vector for the encrypted image from the cloud and infers the labels of the original (unencrypted image). We now review these components.\\ \noindent \textbf{The Encoder.} The goal of this component is to create a meaningful condensed representation of the original (unencrypted) image. Multiple convolutional architectures would be suitable for this task. In our experiments we used several pre-trained and well-known image classification architectures (e.g., ResNet50, ResNet50V2, ResNet101) whose softmax layers were removed to create our embeddings.\\ \noindent \textbf{The Generative Model.} The goal of this component is to create a scrambled version of the original image. We use a deconvolutional architecture that receives the embedding generated by the encoder and outputs a new image. The new image is scrambled because it is generated by a \textit{network whose weights are randomly initialized}. This set of randomly-initialized weights serves as OWSD\xspace's encryption key. Next, the newly-generated (i.e., scrambled) image is sent to the CMLS. The service processes the image as it would any unencrypted input, producing a classification vector. This vector is then sent back to the secure organizational network. It is important to note that \textit{only scrambled images ever leave the organizational network}, both during the training of model (on which we elaborate later in this section) and when it is applied on new data. \\ \noindent \textbf{The Internal Inference Network (IIN).} The goal of this component is to infer the label of the original (unscrambled) image. This dense neural network receives as input the embedding of the original image (produced by the Encoder) and the classification vector produced by the CMLS for the encrypted image. The network then \textit{infers the true label of the original image}. This network can be easily trained using a small number training inputs---training required on average 4-5 minutes on a standard laptop. \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/Project_layout_no_dimensions_Page_2.png} \caption{OWSD\xspace's inference process.} \label{fig:encrypArchitecture} \end{figure} \subsection{The Training Phase} The only component of OWSD\xspace that requires training is the IIN. To train this component in a fully secure manner, the organization requires a small dataset of images $D$ whose real labels are known. These images can then be scrambled, sent to the cloud, and have their classification vectors retrieved. We then use the embedding of each image (the output of the Encoder) and the CMLS's classification vector to train the IIN to predict the true label of the original image. We consider the requirement that organizations have a small labeled dataset to be reasonable, since most organizations have proprietary knowledge they wish to protect and therefore able to leverage for OWSD\xspace's training. If such a dataset is not available, however, it is also possible to use publicly-available images to train the inference network. We explore such a scenario in use-case 3 of Section \ref{subsec:evaluationResults}. \subsection{Why Does Our Approach Work?} The main insight behind OWSD\xspace's encryption process is that convolutional (and deconvolutional) architectures identify and transform latent patterns in the data. These patterns are very difficult to reverse-engineer because of the non-linear nature of the neural net's activation function and the large number of operations, but they are maintained nonetheless. These transformations are performed in a consistent (yet complex) manner, and will therefore elicit consistent behavior from the CMLS (i.e., a classification vector). Our ability to translate the classification vector of the encrypted image into a label for the original image is not without foundations in existing literature. Our work builds upon two areas of research: membership inference attacks \cite{shokri2017membership} and distillation \cite{hinton2015distilling}. In membership inference attacks, an attacker can learn which samples were used to train a black-box model by analyzing its output vector. This field of research shows that one can derive meaningful insights regarding the neural network's inner workings from its output vector. In distillation, a single neural network is used to learn the decision process of an entire ensemble, and is thus able to achieve similar performance at a fraction of the computational resources. The ideas behind these two approaches are combined in OWSD\xspace: we analyze the output vectors for encrypted images, and train a small neural network to distill the performance of the cloud-based model, although for predicting possibly different labels than the cloud's. \subsection{Why is our approach secure?} One-time pad encryption (OPE) is known to be unbreakable, as long as \textit{a)} it is of the same length as the encrypted text, and; \textit{b)} it is used only once \cite{matt2013one}. Our approach builds upon OPE, but with several modifications: first, we use an `encryption pad' (i.e., the deconvolutional network) that is larger by orders of magnitude than the encrypted text. This makes decryption difficult even when the pad is used for scrambling multiple samples. Secondly, the deconvolutional network's use of the ReLU activation function means that negative values generated throughout the network will be transformed to zero. This trait of our network adds another layer of complexity for an attacker, because multiple parameter configurations could be used to generate an input/output pair. Our analysis shows that on average 59\% of the neurons of our deconvolutional network output zeros for any input they receive. Finally, we present a comprehensive empirical analysis of the strength of our approach in Section \ref{subsec:AnalyzingRobustness}, and provide a bound on the number of images that can be safely scrambled by any given key. \section{Experiments} \subsection{Experimental setup} \label{subsec:ExperimentalSetup} \begin{itemize} \item We used four datasets in our experiments: \textit{a)} two variants of ImageNet \cite{deng2009imagenet}: ILSVRC2010 and ILSVRC2012; \textit{b)} CIFAR-100, and; \textit{c)} CIFAR-10 \cite{krizhevsky2009learning}. \item We used the following pre-trained architectures as our CMLS: InceptionV3 \cite{szegedy2016rethinking}, Xception \cite{chollet2017xception}, and VGG16 \cite{simonyan2014very}. The two former architecture were trained on the training set of ILSVRC2012 (i.e., ImageNet), and the latter both on CIFAR10 and CIFAR100. \item For the Encoder component, we used pre-trained architectures of ResNet50 and ResNet101 \cite{he2016deep}, and ResNet50V2 \cite{rahimzadeh2020modified}, that were trained on the training set of ILSVRC2012. The output of this component is an embedding vector with 2,048 entries. Please note that the same pre-trained architecture is \textit{never used simultaneously in the Encoder and as the CMLS in our experiments}. \item For our Generative model, we used the DCGAN's \cite{radford2015unsupervised} generator. The dimensions of the output image were $256x256x3$. \item Our IIN was a dense neural network with a single hidden layer, followed by a softmax layer. The input vector size was $2048 + |V|$, where $V$ is the classification vector of the cloud. We applied batch normalization and dropout, and used ADAM optimization. We used a learning rate of 0.0001 with exponential decay, and trained the network up to 40 epochs, with early stopping. \item We evaluate our approach using two metrics---top-1 and top-5 accuracy---which are the standard in image classification tasks. We calculate these metrics with respect both to the ground truth (i.e., true labels) and to the cloud's classification of the unencrypted image (i.e., we measure our ability to infer the cloud's classifications). \item All experiments in this section (i.e., training the INN) were conducted on a laptop with 16GB RAM and an Intel CPU (Intel(R) Core(TM) i7-8565U). \end{itemize} \subsection{Evaluation Results} \label{subsec:evaluationResults} We evaluate five use-cases: \textit{a)} \textit{same labels in confidential data and cloud} -- in this use-case, the cloud was trained on images with the same labels as confidential data (no overlap between the two sets of images); \textit{b)} \textit{subset of cloud labels} -- the confidential data consists of a subset of the labels on which the cloud was trained -- the goal of these experiments is to assess the impact of the relative number of labels on performance; \textit{c)} \textit{different labels in confidential data and cloud} -- these experiments evaluate our ability to perform transfer learning to new labels; \textit{d)} \textit{ensemble} -- we explore the effects of using several Encoders; \textit{e)} \textit{Varying IIN training set sizes} -- we analyze OWSD\xspace's performance as a function of the IIN's training set size.\\ \noindent \textbf{Use-Case 1: Same Labels in Confidential Data and Cloud.} We conducted three sets of experiment, for ImageNet, CIFAR100, and CIFAR10. Table \ref{tab:Use Case 1 Results} presents the pre-trained models used as the CMLS and the Encoder component in each experiment (see Section \ref{subsec:ExperimentalSetup} for specifics on the training of each architecture). For the ImageNet experiments, we used 90\% of the validation set---45,000 images---to train the INN, and used the remaining 10\% (5,000 images) as our test set. For CIFAR10/100, we used 90\% (9,000 images) of the test set to train the INN, and the remaining 10\% for our evaluation (class ratios were maintained). We performed five experiments for each dataset, with random 90\%/10\% splits, and report the averages of all runs. The results of our evaluation are presented in Table \ref{tab:Use Case 1 Results}. We present the INN's performance with respect to the ground truth and to the CMLS's classifications of the unencrypted images. To place our results in context, we also present the performance of the cloud model on the unencrypted images. these results are, in effect, the upper bound for the performance of our approach. The results clearly show that OWSD\xspace is capable of inferring both the ground truth labels and the cloud's classifications. There is, however, a decrease in performance. For the prediction of true labels, for example, our accuracy was reduced by 6.2\%-9.8\% for ImageNet, by 1.6\%-5.2\% for CIFAR100, and by 0.6\%-6.8\% for CIFAR10. An important observation is that while there is a decrease in performance, it is smaller when the \textit{number of labels in the confidential data is small}. The reason for this phenomenon is simple: as the ratio of labels in the confidential data and that of the cloud $\frac{|L_{conf}|}{|L_{cloud}|}$ becomes smaller, each confidential data label can be expressed in a more nuanced way. This additional ``bandwidth'' is helpful because, as we show in Section \ref{subsec:analyzingCloudOutput}, the use of our scrambling approach results in much higher entropy in the CMLS's classification vector. Our next use-case therefore focuses on further analysis of the effects of $\frac{|L_{conf}|}{|L_{cloud}|}$.\\ \begin{table*}[t] \centering \begin{tabular}{|c|c|c|c|c|c|c|c|c|} \hline \multirow{3}{*}{Dataset} & \multirow{3}{*}{\makecell{Cloud\\ Architecture}} & \multirow{3}{*}{\makecell{Encoder\\ Architecture}} & \multicolumn{4}{c|}{Internal Inference}& \multicolumn{2}{c|}{Cloud Performance} \\ & & & \multicolumn{2}{c|}{Real Labels} & \multicolumn{2}{c|}{Cloud Class.} & \multicolumn{2}{c|}{Un-encrypted images} \\ & & & Top-1 & Top-5 & Top-1 & Top-5 & Top-1 & Top-5 \\ \hline ImageNet&Xception&ResNet101& \makecell{67.9\% \\(0.007)} & \makecell{87.6\% \\(0.006)}& \makecell{69.3\% \\(0.008)}& \makecell{88.8\% \\(0.004)}& \makecell{77.7\% \\(0.005)}& \makecell{93.8\% \\(0.004)}\\ \hline CIFAR100&VGG16&ResNet50V2& \makecell{64.3\% \\(0.013)}& \makecell{88.5\% \\(0.015)}& \makecell{58.1\% \\(0.004)}& \makecell{81.6\% \\(0.015)}& \makecell{69.5\% \\(0.011)}& \makecell{90.1\% \\(0.004)}\\ \hline CIFAR10&VGG16&ResNet50V2& \makecell{86.5\% \\(0.017)}& \makecell{99.2\% \\(0.004)}& \makecell{84.8\% \\(0.014)}& \makecell{98.8\% \\(0.004)}& \makecell{93.3\% \\(0.009)}& \makecell{99.8\% \\(0.002)}\\ \hline \end{tabular} \caption{Use Case 1 Results \yiftach{add explanation} } \label{tab:Use Case 1 Results} \end{table*} \noindent \textbf{Use-Case 2: Using a subset of confidential data labels.} Based on use-case 1, we now revisit our ImageNet experiments (in which OWSD\xspace had the largest gap with the original cloud performance). We used the same settings as in use-case 1, but the confidential data contained only a subset of 10/100 labels instead of the original 1,000. For each of these two settings---10 and 100---we performed five experiments, with the labels of each randomly selected. We used a 70\%/30\% train/test split with 50 images per label, resulting in 350/3,500 images for the training of the IIN and 150/1,500 images for evaluation. The results of our evaluation are presented in Table \ref{tab:Use Case 2 Results}. It is clear that our performance on ImageNet improves as the number of labels decreases, with OWSD\xspace's top-1 accuracy rising from 67.9\% to 95.5\%, and its top-5 accuracy rising from 87.6\% to 99.9\%. The improvement in performance shows that we were correct in our hypothesis that $\frac{|L_{conf}|}{|L_{cloud}|}$ is the main factor in determining our method's performance.\\ \begin{table} \begin{tabular}{|c|c|c|} \hline Number of labels & Top-1 & Top-5 \\ \hline 1000 & 67.9\% (0.007)& 87.6\% (0.006)\\ \hline 100 & 87.2\% (0.009)& 96.7\% (0.006)\\ \hline 10 & 95.5\% (0.019)& 99.9\% (0.003)\\ \hline \end{tabular} \caption{Use Case 2: IIN's accuracy compared to ``ground truth''} \label{tab:Use Case 2 Results} \end{table} \noindent \textbf{Use-Case 3: Different labels for confidential data and cloud.} We now evaluate OWSD\xspace's ability to infer labels that did not appear in the CMLS's training set. This use-case is important because it assesses whether our proposed approach is generic and transferable. For these experiments we used VGG16, which was trained on CIFAR 100 as our CMLS, and ResNet101, which was trained on ImageNet, as our Encoder. To generate our confidential dataset, we first identified all ImageNet labels that \textit{did not} appear in CIFAR100. Next we randomly sampled 10 labels from these labels---150 images per class, 1,500 overall. We use 70\% of these images (1,050) to train our Internal Inference agent and use the remaining 30\% for evaluation. This process is repeated five times, and the averaged results are presented in Table \ref{tab:Use Case 3 Results}. For this setting we can only present the results with respect to the original image labels, which clearly show that we are able to reach the same level of performance for images with previously-unseen labels as we do for those on which the CMLS was trained. Additionally, we once again show that our approach is most effective when $\frac{|L_{conf}|}{|L_{cloud}|}$ is small.\\ \begin{table} \begin{tabular}{|c|c|} \hline Metric & Internal Inference to Real Labels \\ \hline Top-1 & 96\% (0.015)\\ \hline Top-5 & 99.9\% (0.002)\\ \hline \end{tabular} \caption{Use Case 3: results on ``ground truth''} \label{tab:Use Case 3 Results} \end{table} \noindent \textbf{Use-Case 4: Using an ensemble of Encoders.} The goal of this use-case is to examine whether an ensemble of Encoders can improve the performance of our proposed approach. To this end, we use multiple pre-trained networks as our Encoders. The resulting encodings are scrambled using the same Generative Model and sent to the CMLS. The classification vectors produced for each individual encoding are then concatenated and fed as a single input the to IIN. The results of our analysis are presented in Table \ref{tab:Use Case 4 Results}. We build upon the experiments presented in Table \ref{tab:Use Case 1 Results}, and therefore the results for a single encoder are identical. When using two encoders, the network we added was ResNet50. For our third encoder we used ResNet50v2 for the ImageNet dataset and ResNet101 for CIFAR100/10. The results show that adding encoders indeed improves OWSD\xspace's performance, although the improvement appears to be greater for the CIFAR10/CIFAR100 datasets (which concurs with our conclusion in use case 2). Using the paired-t test, we were able to determine that the two-Encoders setting significantly outperforms the single-Encoder setting with $p<0.001$, and that three-Encoders outperform the two-Encoders with a smaller but still highly significant value of $p<0.01$. \\ \begin{table*}[t] \centering \scriptsize \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c||c|c|} \hline \multirow{3}{*}{} & \multicolumn{12}{c|}{Internal Inference}& \multicolumn{2}{c|}{Cloud Performance} \\ & \multicolumn{6}{c|}{Real Labels} & \multicolumn{6}{c|}{Cloud Class.} & \multicolumn{2}{c|}{Un-encrypted images} \\ & \multicolumn{3}{c|}{Top-1} & \multicolumn{3}{c|}{Top-5} & \multicolumn{3}{c|}{Top-1} & \multicolumn{3}{c|}{Top-5} & Top-1 & Top-5 \\ \makecell{datasets/ \\ \#encoders}& 1 & 2 & 3 & 1 & 2 & 3 & 1 & 2 & 3 & 1 & 2 & 3 & & \\ \hline ImageNet& \makecell{67.9\% \\ (0.007)} & \makecell{68.6\% \\ (0.002)} & \makecell{69.5\% \\ (0.006)} & \makecell{87.6\% \\ (0.006)} & \makecell{88.9\% \\ (0.004)} & \makecell{89.1\% \\ (0.006)} & \makecell{69.3\% \\ (0.008)} & \makecell{69.9\% \\ (0.004)} & \makecell{71.4\% \\ (0.009)} & \makecell{88.8\% \\ (0.004)} & \makecell{90.1\% \\ (0.003)} & \makecell{90.7\% \\ (0.005)} & \makecell{77.7\% \\ (0.005)} & \makecell{93.8\% \\ (0.004)}\\ \hline CIFAR100& \makecell{64.3\% \\ (0.013)} & \makecell{67.2\% \\ (0.01)} & \makecell{68.4\% \\ (0.007)} & \makecell{88.5\% \\ (0.015)} & \makecell{89.8\% \\ (0.004)} & \makecell{90.4\% \\ (0.009)} & \makecell{58.1\% \\ (0.004)} & \makecell{61\% \\ (0.01)} & \makecell{62.4\% \\ (0.009)} & \makecell{81.6\% \\ (0.015)} & \makecell{84.5\% \\ (0.011)} & \makecell{85.7\% \\ (0.015)} & \makecell{69.5\% \\ (0.011)} & \makecell{90.1\% \\ (0.004)}\\ \hline CIFAR10& \makecell{86.5\% \\(0.017)} & \makecell{88.1\% \\ (0.014)} & \makecell{88.9\% \\ (0.009)} & \makecell{99.2\% \\(0.004)} & \makecell{99.3\% \\ (0.004)} & \makecell{99.4\% \\ (0.001)} & \makecell{84.8\% \\ (0.0014)} & \makecell{86.2\% \\(0.015)} & \makecell{87.4\% \\ (0.008)} & \makecell{98.8\% \\(0.004)} & \makecell{99.2\% \\(0.001)} & \makecell{99.1\% \\(0.002)} & \makecell{93.3\% \\(0.009)} & \makecell{99.8\% \\(0.002)}\\ \hline \end{tabular} \caption{Use Case 4 Results -- the effect of using multiple Encoders on performance.} \label{tab:Use Case 4 Results} \end{table*} \noindent \textbf{Use-Case 5: The Effect of the IIN's training size on performance.} We now analyze the effect of the training set size on the performance of the IIN. While it likely that larger training sets will lead to higher accuracy, our goal is to quantify this impact. We conducted our analysis as follows: We used ILSVRC2012's validation set, from which we randomly sampled 100 labels, to train our IIN and evaluate its performance. We used InceptionV3 as our CMLS (this model was trained on ILSVRC2012's \textit{training set}), and ResNet50 as our Encoder. We sampled different numbers of images from each of our selected 100 labels, and used them to train the IIN. We repeat this experiment five times and report the average results, which are presented in Figure \ref{fig:accScore100}. It is clear that an increase in the training set significantly improves the performance of our approach, with top-1 accuracy improving by 8.7\% and top-5 accuracy improving by 5.2\%. It is also clear that the improvement in OWSD\xspace's performance begins to plateau at around 35 images per label, which achieved an accuracy of 90.6\% compared to the 91.2\% for 45 images, indicating that a relatively small number of training samples is needed for maximal performance. The small number of samples that is needed to train our INN is a crucial aspect of our proposed approach. Given that each key (i.e., the randomly-initialized Generator weights) can only be used a limited number of times before an adversary can reconstruct the original images (see Section \ref{subsec:AnalyzingRobustness} for analysis), requiring a limited number of images to train the INN means that each key can be used for a longer period of time. \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/IMMeanAccuracy100classesTrainonreallabels.png} \caption{The top-1 and top-5 accuracy of OWSD on a randomly-sampled subset of ImageNet, consisting of 100 labels. The results are presented as a function of the number of images per label that were used in OWSD’s training set.} \label{fig:accScore100} \end{figure} \section{Confidentiality Analysis} In this section we analyze four aspects of our proposed approach and demonstrate the difficulties an attacker would face when attempting to recover the original images. First, in Section \ref{subsec:originalImage} we show that our scrambled images do not contain any information that can be understood by humans. Secondly, in Section \ref{subsec:analyzingCloudOutput} we analyze the outputs (i.e., classification vectors) produced by the CMLS for our images, and show that the former's entropy is much higher than that of unscrambled images and that the ``true'' label of the image (i.e., the ground truth) is almost never in the top-5 chosen labels. In Section \ref{subsec:scramblingReconstruct} we analyze our scrambled images and show that they are more difficult to reconstruct than their plaintext counterparts. Finally, in Section \ref{subsec:AnalyzingRobustness} we provide an empirical loose upper bound on the number of images that can be scrambled by OWSD\xspace using a single key. \subsection{Comparing Original and Scrambled Images} \label{subsec:originalImage} We begin by addressing a simple question: can humans identify objects in our scrambled images. Figure \ref{fig:encrypted-pair-example} presents an original image and its scrambled counterpart. It is clear that no information in the scrambled image is discernible to humans using the naked eye. Similar grayscale images were produced for all the images we manually examined. \begin{figure}[h!] \centering \includegraphics[width=\columnwidth]{Figures/originalandtransformedimage.png} \caption{left) The original image. right) The same image, scrambled by OWSD\xspace using embeddings by ResNet50.} \label{fig:encrypted-pair-example} \end{figure} \subsection{Analyzing the Cloud Output} \label{subsec:analyzingCloudOutput} Our goal is to determine whether our approach effectively obfuscates the labels of scrambled images. We used the InceptionV3 and ResNet50 architectures as our CMLS and Encoder models, respectively. The training and evaluation image sets were those of use-case 1 in Section \ref{subsec:evaluationResults}. We begin by comparing the classification vectors produced by the CMLS for each image and its scrambled counterpart. Our results, presented in Table \ref{tab:predictions-vectors-results}, show that the probabilities of any intersection of labels in the top-1 and top-5 labels is 0.07\% and 0.52\%, respectively. Moreover, the confidence scores assigned for each of the original top-1/5 labels have been reduced by an average of 76\%-87\% respectively. Finally, an analysis of the entropy of the classification vectors of plaintext and confidential images shows that the entropy of the latter is more than twice that of the former: 4.3 to 1.97. These results indicate that not only are our scrambled images not discernible to humans, but the CMLS's classification vector does not enable an easy inference of the original label(s) assigned to them. Next, we use PCA to reduce the dimensionality of the classification vectors of original and scrambled images. We randomly chose two labels from ImageNet, each consisting of 50 samples. We present our generated 2D representations in Figure \ref{fig:2Ddist}. It is clear that while the classification vectors for the two original groups of images are clearly separated, all the scrambled images are grouped together. Additionally, the scrambled images' representation is clearly separated from both groups of original images. These results further show that our scrambling process is effective in obfuscating the original label of the image. \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/predictions2Ddistribution.png} \caption{The classification vectors of plaintext and scrambled images of two labels, presented in a 2D space. It is clear that plaintext images are clearly separated, while the scrambled ones are mixed together.} \label{fig:2Ddist} \end{figure} \begin{table} \begin{center} \begin{tabular}{|c|c|} \hline Top-1 Mean Intersection Rate & 0.07\% \\ \hline Top-5 Mean Intersection Rate & 0.52\%\\ \hline Top-1 Mean Reduction & 76\%\\ \hline Top-5 Mean Reduction & 87\%\\ \hline \end{tabular} \caption{Comparison of the label intersection and relative confidence scores for plaintext and scrambled images.} \label{tab:predictions-vectors-results} \end{center} \end{table} \begin{comment} \begin{table} \footnotesize \begin{center} \begin{tabular}{|c|c|} \hline Mean Entropy for original images & 1.97\\ \hline Mean Entropy for scrambled images & 4.3\\ \hline \textbf{Mean Entropy Gain} & \textbf{2.33}\\ \hline Maximal possible Entropy & 9.97 \\ \hline \end{tabular} \caption{Analysis of the mean entropy of the cloud-based model’s prediction vectors} \label{tab:mean-etropy-results} \end{center} \end{table} \end{comment} \subsection{Reconstruction of Scrambled Images} \label{subsec:scramblingReconstruct} In previous sections we showed that our scrambled images are not discernible by human users, and that they induce a higher degree of entropy in their classification. Our goal now is to determine whether our scrambled images are more difficult to reconstruct. We used an autoencoder in two experimental settings: \textit{a)} receive the original image as input, and reconstruct it; \textit{b)} receive the scrambled image as input, and reconstruct the original image. As our autoencoder we used the well-known DCGAN architecture \cite{radford2015unsupervised}. We used DCGAN's discriminator, which we augmented with additional residual blocks, as our encoder. DCGAN's generator was used as our decoder. For OWSD\xspace's setup we used the InceptionV3 architecture as our cloud-based model, and ResNet50 as our Encoder. For this experiment we randomly selected 100 labels from ImageNet, and then retrieved all 150 images associated with each label. We therefore created a set of 15,000 images. We than randomly split these 15,000 images into train and test sets, using a 90\%/10\% split. This process was repeated twice, and we present their averaged results in Table \ref{tab:AETrainMse2}. To enable faster convergence (i.e., using less training samples), all images were reduced to a quarter of their original size (128x128 instead of 256x256). We define difficulty to reconstruct as the \textit{number of samples needed for the training of autoencoder}. This definition is crucial for Section \ref{subsec:AnalyzingRobustness}, where we analyze our model's robustness. The results of our evaluation are presented in Table \ref{tab:AETrainMse2} and Figure \ref{fig:70gtest}. While this training set size is sufficient for a decent reconstruction of images when applied on the original images, reconstruction quality for scrambled images is so low that the images are incomprehensible. \begin{figure} \begin{subfigure}{.23\textwidth} \centering \includegraphics[width=\textwidth]{Figures/70otest.png} \caption{} \label{fig:70otest} \end{subfigure} \begin{subfigure}{.23\textwidth} \centering \includegraphics[width=\textwidth]{Figures/70gtest.png} \caption{} \label{fig:70gtest} \end{subfigure} \caption{The inputs ($x$), targets ($y$) and reconstructions ($\hat{y}$) of images. Figure \ref{fig:70otest} presents the use-case where we receive the plaintext image as input, and \ref{fig:70gtest} presents the use-case where we receive the scrambled image.} \label{fig:autoencoder training} \end{figure} \begin{comment} \begin{table} \footnotesize \centering \begin{tabular}{|c|c|c|c|c|} \hline \multirow{3}{*}{Train Set Size} & \multicolumn{2}{c|}{Original Images} & \multicolumn{2}{c|}{Scrambled Images} \\ & Test Loss (MSE) & $\sigma$ & Test Loss (MSE) & $\sigma$\\ \hline 13,500 & 0.021 & 0.004 & 0.061 & 0.001\\ \hline 9,000 &...&...&...&...\\ \hline \end{tabular} \caption{\yiftach{Additional train set sizes performances are interesting (there are more)? if not use the other table or just incorporate in text.} Average of two different subsets of ImageNet ILSVRC2010 test set \yiftach{explained above}} \label{tab:AETrainMse1} \end{table} \end{comment} \begin{table} \footnotesize \centering \begin{tabular}{|c|c|c|} \hline Images Type & Test Loss (MSE) & $\sigma$ \\ \hline Original & 0.021 & 0.004\\ \hline Scrambled & 0.061 & 0.001\\ \hline \end{tabular} \caption{The autoencoder's reconstruction loss when applied on original and scrambled images} \label{tab:AETrainMse2} \end{table} \subsection{Analyzing the Robustness of Our Approach} \label{subsec:AnalyzingRobustness} As explained in Section \ref{sec:proposedMethod}, only the encrypted images ever leave the organizational network. As a result, attackers are likely to have to resort to a practically infeasible brute-force search to discover our randomly-set Generator weights. However, we are unable at this time to provide a theoretical proof to this claim, and therefore provide an \textit{empirical proof}. We do so by creating a scenario in which the adversary has access to \textit{additional information that enables a more effective attack against our approach}. We then use the amount of information required to carry out this attack as a bound on the number of images that can be securely scrambled by any one given key.\\ \noindent \textbf{The proposed attack scenario.} Assume that an adversary has gained access to pairs of original-scrambled images (i.e., not only does the adversary have access to such sets, but she can also pair them accordingly). The adversary can now train a neural architecture---more specifically, an autoencoder---to reconstruct the original image from the encrypted one. This scenario, in fact, is exactly the setup described in the second experiments of Section \ref{subsec:scramblingReconstruct}, \textit{where we showed that 13,500 original/scrambled image pairs are insufficient for any meaningful reconstruction of scrambled images}. It is also very important to note that---as shown in use-case 5 in Section \ref{subsec:evaluationResults}--- the maximal number of scrambled images needed to train the IIN is 4,500 (for confidential data with 100 labels). The aforementioned statistics provide us with a bound on the number of images that can be safely scrambled by OWSD\xspace. Given that 13,500 image pairs are not enough to mount a successful attack, and that 4,500 images \textit{at most} are needed to train our IIN, then we are able to safely use any given key for 9,000 submissions to the cloud. When this number is reached, all we have to do is re-initialize our key. Finally, we wish to emphasize the following: \begin{itemize} \item We stress again that the figure of 13,500 is a very loose bound, created using an unrealistic scenario that greatly favors the adversary. Moreover, the autoencoders were trained on images whose size was only a quarter of the original, thus making the reconstruction process easier. \item The process of generating a new key is instantaneous, and the training of the IIN required approximately five minutes on a laptop (see INN description in Section \ref{sec:proposedMethod}). Therefore, replacing the scrambling key has a negligible computational cost. \item This process can easily be made more secure with the deployment of multiple keys and IINs. Doing so will not only improve performance (see use-case 4 in Section \ref{subsec:evaluationResults}), but their gradual replacement will make an adversarial attack even more difficult. \end{itemize} \begin{comment} \subsection{Empirical Transformation Strength Analysis} \subsubsection{Training Data Requirements} The goal of the following evaluations is to substantiate the amount of data that is needed to sufficiently train the organizational inference model. The evaluation includes training the organizational model using varying amounts of samples per class, as well as different amount of classes, and calculating the achieved performances. ILSVRC2012 validation set was used as the dataset (organizational data) for the evaluation \yiftach{maybe not necessary to reference}, along with two subsets of it with 100 classes each (50 samples per class). Pre-trained ResNet50 was used as encoder and pre-trained InceptionV3 as an external model. The organizational model was trained to predict the ground-truth labels as in use-case 1. The results reported are the average performance on the two 100-labels subsets. \ref{fig:accScore1000} \ref{fig:accDiff1000} \yiftach{add table? add 100 data} \end{comment} \begin{comment} \subsubsection{Data Reconstruction Evaluation} The goal of this section is to empirically evaluate whether the original data can be recreated from the transformed data, and if so what is the size of the data that is required. To perform this analysis we assume that an hostile entity has access to N number of pairs of original and transformed images and tries to learn a mapping between the transformed images and their original form. \yiftach{relaxed assumption ??? Classified data does not leave the organization unencrypted in all the variations of our proposed approach. However, the variation that utilizes an unclassified set does send both plain and encrypted data that might be exposed.} A Deep Convolutional Autoencoder is used to attempt to learn the mapping by attempting to learn how to recreate the original image from the generated one. As a comparison target for the recreation performance, the same autoencoder architecture is also trained to reconstruct the original image \yiftach{(from the original image)}. The same hyper-parameters were used for the training of both autoencoders. The encoder part of the autoencoder architecture used is based on the DCGAN discriminator model adapted to the task and supplemented with residual blocks. The decoder part is based on the generator of DCGAN. The aim of the experiment is to determine how many samples are required for a sufficient recreation. Therefor, four different subsets of ILSVRC2010 were used as datasets with different amounts of classes and training images pairs. To assist the implementation and execution of these experiments the images were loaded to a quarter of their original size ($(128,128)$ RGB instead of $(256,256)$ RGB) \yiftach{Add experiments with less samples} The results show that it is harder to learn a mapping from the transformed images to their original form than it is to learn to an identity mapping \yiftach{Gilad please assert this phrasing}. Figure \ref{fig:avgTestRecon} shows the average test losses of the different encoders in dependence of the dataset size. There is a significant difference between the losses achieved by the models that received the original images than the ones that received the transformed images. Additionally, a major increase in loss is observed for datasets with less than [fill number] samples \yiftach{fill number. add reference to the number of classes. determine a threshold per class}. \end{comment} \begin{comment} \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/Average Evaluated Test Loss (MSE) reconstruction.png} \caption{Average MSE Test Loss in dependence of Train Set Size. we defined two labels amounts-10, 100. for each label amount we used two different subsets of ImageNet ILSVRC2010 test set with randomly selected labels and 150 samples per label (each 10-label set contains 1,500 images and each 100-label set contains 15,000). In addition we used varying number of samples per class. we used random train/test split of 90\%/10\%. These definitions resulted in varying overall sizes of the autoencoder train set. The results of each pair of subsets with the same labels count are averaged and presented.} \label{fig:avgTestRecon} \end{figure} \end{comment} \section{Conclusion} We present OWSD\xspace, a scrambling-based approach that offers many of the advantages of Homomorphic encryption at a fraction of the computational cost. We showed that when the number of labels in the confidential data is smaller than in the CMLS, our approach can achieve the same performance as the CMLS. For future work, we intend to conduct experiments on additional types of data, and explore the use of our approach in a multi-agent collaborative setting. \section{Introduction} Recent advances in Cloud-based Machine Learning Services (CMLS) capabilities have made it possible for individuals to access state-of-the-art algorithms that until recently were only accessible to few. These capabilities, however, come with two major risks: \textit{a)} the leakage of sensitive data as it's being sent to and/or processed by the cloud, and; \textit{b)} the ability of third parties to gain insight into the organization's data by analyzing the output of the ML model in the cloud. Given that organizations must transmit their data to the cloud to use cloud services, the former are faced with three options: \textit{a)} Send the data in encrypted form to the cloud, where it will be decrypted, analyzed and then sent back in encrypted form (e.g., using asymmetric encryption); \textit{b)} Employ Homomorphic Encryption (HE) techniques that enable the cloud to process the data in its encrypted form; and, \textit{c)} apply differential privacy techniques which introduce varying degrees of noise to the data. Each of these approaches, however, has shortcomings. The first option -- decryption in the cloud -- enables the cloud provider unfettered access to the organization's private data, and is unacceptable in many cases. HE keeps the data private, even when it is being processed in the cloud, but it is slow and puts various limitations on the operations that can be performed so as not to prevent the decryption at the end of the process. Other encryption solutions that offer some or all of the capabilities of HE also exist, but they too require cooperation from the service provider (i.e., the cloud-based service) and often have other prerequisites such as non-collusion among participating servers or dedicated hardware. Finally, differential privacy techniques do prevent attackers from inferring specific details from the data, but they do not prevent obtaining a general sense of the processed data and they come with the price of reduced performance. In this study we propose One Way Scrambling by Deconvolution (OWSD\xspace), an approach that provides the main advantage of Homomorphic encryption---not sharing the unencrypted data with any party, including the CMLS---but with a computational overhead that is smaller by orders of magnitude. Our approach uses a randomly-initialized deconvolutional architecture to scramble the input, which is then sent to the CMLS. The CMLS processes the input in the same manner as it would any unencrypted data, and produces a classification vector. Finally, a small ``translator'' neural architecture within the organization receives the classification vector produced by the cloud and combines it with an embedding of the original image to predict the classification the cloud service would have given to the original image. OWSD\xspace has several important advantages compared to existing methods. First, the use of randomly-initialized deconvolutional networks creates scrambled images that are both incomprehensible to human observers and whose classification in the cloud does not disclose their original label. Secondly, as the deconvolutional network is randomly initialized and not trained, replacing the ``key'' (i.e., network weights values) of our scrambling mechanism is computationally inexpensive, as we only need to retrain our translator architecture. Moreover, multiple scrambling keys can be used simultaneously, thus both improving OWSD\xspace's performance and making decryption efforts more challenging. Thirdly, our approach does not require any coordination with the CMLS. Our contributions in this study are as follows: \begin{itemize} \item We present OWSD\xspace, a scrambling-based approach that has many of the advantages of HE at a fraction of the computational cost. \item We perform extensive evaluation and show that our approach can reach up to 99.9\% of the performance of the CMLS when the number of labels in the confidential data is smaller than that of the cloud. This is also the case when the labels of the confidential data are not in the cloud's training data (i.e., transfer learning). \item We perform an extensive empirical analysis of our approach and provide an upper bound on the number of images that can be securely scrambled by any one key of our approach. \end{itemize} \section{Related Work} Existing solutions can be roughly divided into two groups: encryption-based and differential privacy-based. \subsection{Encryption-based solutions} In this study we focus on approaches that enable the application of privacy-preserving Machine Learning (ML) in the cloud. These solutions can also be divided into two groups: one in which the cloud-based service provider has access to the plaintext, and one in which it does not. The former group of solutions utilizes common public/private key settings (e.g., RSA \cite{milanov2009rsa}) and is in widespread use. In Li, Ping, et al. \cite{li2018privacy}, the authors present a multi-step framework for the exchange of public keys. A semi-honest model -- a scenario where the cloud provider is not compromised -- is also assumed. Similar approaches have also been proposed by \cite{li2018privacy,li2018privacymulti}. The latter group of solutions, where the cloud provider does not have access to the plaintext, can be divided into hardware and software-based solutions. In hardware-based solutions, multiple studies \cite{hunt2018chiron,tramer2018slalom,hynes2018efficient} utilize the SGX architecture which possess a secure enclave for the processing of sensitive information. In Chiron \cite{hunt2018chiron}, for example, the authors demonstrate how SGX could be effectively used to run deep neural architectures. This approach, while effective, requires the installation of a dedicated client both by the client and the service provider, as well as adaptation of the ML model, and are costly and difficult to implement. Software-based encryption solutions that without the plaintext from the CMLS, though diverse, mostly revolve around the use of HE. In \cite{li2017multi} the authors propose two Fully Homomorphic Encryption (FHE) schemes for privacy-preserving deep learning. In \cite{hesamifard2018privacy} and \cite{hesamifard2017privacy}, the authors demonstrated that it is feasible to train neural networks using encrypted data, while in \cite{gilad2016cryptonets} the authors detailed a method to convert learned neural networks to neural networks that can be applied to encrypted data (using leveled HE). While they enable full protection of one's data, Homomorphic solutions are slow, require large amount of memory and require prior knowledge of the type of queries, so that the appropriate HE scheme can be selected to encrypt the raw data \cite{li2017multi}. \subsection{Differential privacy-based solutions} Differential privacy is a general term for techniques that obfuscate the data (i.e., inject noise) in order to ensure that the details of individual records cannot be inferred \cite{dwork2008differential}. Generally, these techniques sacrifice some accuracy in the interest of privacy. The main drawback of this approach is that there is still a way of inferring the general type and characteristics of the data. In \cite{bonawitz2017practical} the authors use aggregations of data collected from mobile devices, which are then sent to a CMLS. A similar approach is presented in \cite{yang2018machine,osia2020hybrid}, who also incorporate the injection of noise into the data. A different approach is presented in \cite{wang2018not}, where a deep architecture is divided into two parts: the smaller (initial part) is installed locally on the client, and the bulk of the architecture is in the cloud. The data passes through the client (compressed and encrypted) and then sent to the cloud. Noise is also added to ensure differential privacy. While the latter solution bears some similarity to our proposed approach, the two networks have to be trained jointly and cooperation between the cloud and the client is necessary. Moreover, the cloud-based provider has access to the final classifications and has some ability to reconstruct the data---a shortcoming not shared by OWSD\xspace. \section{The Proposed Method} \label{sec:proposedMethod} Our proposed approach is presented in Figure \ref{fig:encrypArchitecture}. OWSD\xspace consists of three components: \textit{a)} an \textit{encoder}, that creates an embedding of the original image; \textit{b)} a \textit{generative model}, that receives the embedding as input and creates the encrypted image, and; \textit{c)} an \textit{internal inference network}, which receives the classification vector for the encrypted image from the cloud and infers the labels of the original (unencrypted image). We now review these components.\\ \noindent \textbf{The Encoder.} The goal of this component is to create a meaningful condensed representation of the original (unencrypted) image. Multiple convolutional architectures would be suitable for this task. In our experiments we used several pre-trained and well-known image classification architectures (e.g., ResNet50, ResNet50V2, ResNet101) whose softmax layers were removed to create our embeddings.\\ \noindent \textbf{The Generative Model.} The goal of this component is to create a scrambled version of the original image. We use a deconvolutional architecture that receives the embedding generated by the encoder and outputs a new image. The new image is scrambled because it is generated by a \textit{network whose weights are randomly initialized}. This set of randomly-initialized weights serves as OWSD\xspace's encryption key. Next, the newly-generated (i.e., scrambled) image is sent to the CMLS. The service processes the image as it would any unencrypted input, producing a classification vector. This vector is then sent back to the secure organizational network. It is important to note that \textit{only scrambled images ever leave the organizational network}, both during the training of model (on which we elaborate later in this section) and when it is applied on new data. \\ \noindent \textbf{The Internal Inference Network (IIN).} The goal of this component is to infer the label of the original (unscrambled) image. This dense neural network receives as input the embedding of the original image (produced by the Encoder) and the classification vector produced by the CMLS for the encrypted image. The network then \textit{infers the true label of the original image}. This network can be easily trained using a small number training inputs---training required on average 4-5 minutes on a standard laptop. \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/Project_layout_no_dimensions_Page_2.png} \caption{OWSD\xspace's inference process.} \label{fig:encrypArchitecture} \end{figure} \subsection{The Training Phase} The only component of OWSD\xspace that requires training is the IIN. To train this component in a fully secure manner, the organization requires a small dataset of images $D$ whose real labels are known. These images can then be scrambled, sent to the cloud, and have their classification vectors retrieved. We then use the embedding of each image (the output of the Encoder) and the CMLS's classification vector to train the IIN to predict the true label of the original image. We consider the requirement that organizations have a small labeled dataset to be reasonable, since most organizations have proprietary knowledge they wish to protect and therefore able to leverage for OWSD\xspace's training. If such a dataset is not available, however, it is also possible to use publicly-available images to train the inference network. We explore such a scenario in use-case 3 of Section \ref{subsec:evaluationResults}. \subsection{Why Does Our Approach Work?} The main insight behind OWSD\xspace's encryption process is that convolutional (and deconvolutional) architectures identify and transform latent patterns in the data. These patterns are very difficult to reverse-engineer because of the non-linear nature of the neural net's activation function and the large number of operations, but they are maintained nonetheless. These transformations are performed in a consistent (yet complex) manner, and will therefore elicit consistent behavior from the CMLS (i.e., a classification vector). Our ability to translate the classification vector of the encrypted image into a label for the original image is not without foundations in existing literature. Our work builds upon two areas of research: membership inference attacks \cite{shokri2017membership} and distillation \cite{hinton2015distilling}. In membership inference attacks, an attacker can learn which samples were used to train a black-box model by analyzing its output vector. This field of research shows that one can derive meaningful insights regarding the neural network's inner workings from its output vector. In distillation, a single neural network is used to learn the decision process of an entire ensemble, and is thus able to achieve similar performance at a fraction of the computational resources. The ideas behind these two approaches are combined in OWSD\xspace: we analyze the output vectors for encrypted images, and train a small neural network to distill the performance of the cloud-based model, although for predicting possibly different labels than the cloud's. \subsection{Why is our approach secure?} One-time pad encryption (OPE) is known to be unbreakable, as long as \textit{a)} it is of the same length as the encrypted text, and; \textit{b)} it is used only once \cite{matt2013one}. Our approach builds upon OPE, but with several modifications: first, we use an `encryption pad' (i.e., the deconvolutional network) that is larger by orders of magnitude than the encrypted text. This makes decryption difficult even when the pad is used for scrambling multiple samples. Secondly, the deconvolutional network's use of the ReLU activation function means that negative values generated throughout the network will be transformed to zero. This trait of our network adds another layer of complexity for an attacker, because multiple parameter configurations could be used to generate an input/output pair. Our analysis shows that on average 59\% of the neurons of our deconvolutional network output zeros for any input they receive. Finally, we present a comprehensive empirical analysis of the strength of our approach in Section \ref{subsec:AnalyzingRobustness}, and provide a bound on the number of images that can be safely scrambled by any given key. \section{Experiments} \subsection{Experimental setup} \label{subsec:ExperimentalSetup} \begin{itemize} \item We used four datasets in our experiments: \textit{a)} two variants of ImageNet \cite{deng2009imagenet}: ILSVRC2010 and ILSVRC2012; \textit{b)} CIFAR-100, and; \textit{c)} CIFAR-10 \cite{krizhevsky2009learning}. \item We used the following pre-trained architectures as our CMLS: InceptionV3 \cite{szegedy2016rethinking}, Xception \cite{chollet2017xception}, and VGG16 \cite{simonyan2014very}. The two former architecture were trained on the training set of ILSVRC2012 (i.e., ImageNet), and the latter both on CIFAR10 and CIFAR100. \item For the Encoder component, we used pre-trained architectures of ResNet50 and ResNet101 \cite{he2016deep}, and ResNet50V2 \cite{rahimzadeh2020modified}, that were trained on the training set of ILSVRC2012. The output of this component is an embedding vector with 2,048 entries. Please note that the same pre-trained architecture is \textit{never used simultaneously in the Encoder and as the CMLS in our experiments}. \item For our Generative model, we used the DCGAN's \cite{radford2015unsupervised} generator. The dimensions of the output image were $256x256x3$. \item Our IIN was a dense neural network with a single hidden layer, followed by a softmax layer. The input vector size was $2048 + |V|$, where $V$ is the classification vector of the cloud. We applied batch normalization and dropout, and used ADAM optimization. We used a learning rate of 0.0001 with exponential decay, and trained the network up to 40 epochs, with early stopping. \item We evaluate our approach using two metrics---top-1 and top-5 accuracy---which are the standard in image classification tasks. We calculate these metrics with respect both to the ground truth (i.e., true labels) and to the cloud's classification of the unencrypted image (i.e., we measure our ability to infer the cloud's classifications). \item All experiments in this section (i.e., training the INN) were conducted on a laptop with 16GB RAM and an Intel CPU (Intel(R) Core(TM) i7-8565U). \end{itemize} \subsection{Evaluation Results} \label{subsec:evaluationResults} We evaluate five use-cases: \textit{a)} \textit{same labels in confidential data and cloud} -- in this use-case, the cloud was trained on images with the same labels as confidential data (no overlap between the two sets of images); \textit{b)} \textit{subset of cloud labels} -- the confidential data consists of a subset of the labels on which the cloud was trained -- the goal of these experiments is to assess the impact of the relative number of labels on performance; \textit{c)} \textit{different labels in confidential data and cloud} -- these experiments evaluate our ability to perform transfer learning to new labels; \textit{d)} \textit{ensemble} -- we explore the effects of using several Encoders; \textit{e)} \textit{Varying IIN training set sizes} -- we analyze OWSD\xspace's performance as a function of the IIN's training set size.\\ \noindent \textbf{Use-Case 1: Same Labels in Confidential Data and Cloud.} We conducted three sets of experiment, for ImageNet, CIFAR100, and CIFAR10. Table \ref{tab:Use Case 1 Results} presents the pre-trained models used as the CMLS and the Encoder component in each experiment (see Section \ref{subsec:ExperimentalSetup} for specifics on the training of each architecture). For the ImageNet experiments, we used 90\% of the validation set---45,000 images---to train the INN, and used the remaining 10\% (5,000 images) as our test set. For CIFAR10/100, we used 90\% (9,000 images) of the test set to train the INN, and the remaining 10\% for our evaluation (class ratios were maintained). We performed five experiments for each dataset, with random 90\%/10\% splits, and report the averages of all runs. The results of our evaluation are presented in Table \ref{tab:Use Case 1 Results}. We present the INN's performance with respect to the ground truth and to the CMLS's classifications of the unencrypted images. To place our results in context, we also present the performance of the cloud model on the unencrypted images. these results are, in effect, the upper bound for the performance of our approach. The results clearly show that OWSD\xspace is capable of inferring both the ground truth labels and the cloud's classifications. There is, however, a decrease in performance. For the prediction of true labels, for example, our accuracy was reduced by 6.2\%-9.8\% for ImageNet, by 1.6\%-5.2\% for CIFAR100, and by 0.6\%-6.8\% for CIFAR10. An important observation is that while there is a decrease in performance, it is smaller when the \textit{number of labels in the confidential data is small}. The reason for this phenomenon is simple: as the ratio of labels in the confidential data and that of the cloud $\frac{|L_{conf}|}{|L_{cloud}|}$ becomes smaller, each confidential data label can be expressed in a more nuanced way. This additional ``bandwidth'' is helpful because, as we show in Section \ref{subsec:analyzingCloudOutput}, the use of our scrambling approach results in much higher entropy in the CMLS's classification vector. Our next use-case therefore focuses on further analysis of the effects of $\frac{|L_{conf}|}{|L_{cloud}|}$.\\ \begin{table*}[t] \centering \begin{tabular}{|c|c|c|c|c|c|c|c|c|} \hline \multirow{3}{*}{Dataset} & \multirow{3}{*}{\makecell{Cloud\\ Architecture}} & \multirow{3}{*}{\makecell{Encoder\\ Architecture}} & \multicolumn{4}{c|}{Internal Inference}& \multicolumn{2}{c|}{Cloud Performance} \\ & & & \multicolumn{2}{c|}{Real Labels} & \multicolumn{2}{c|}{Cloud Class.} & \multicolumn{2}{c|}{Un-encrypted images} \\ & & & Top-1 & Top-5 & Top-1 & Top-5 & Top-1 & Top-5 \\ \hline ImageNet&Xception&ResNet101& \makecell{67.9\% \\(0.007)} & \makecell{87.6\% \\(0.006)}& \makecell{69.3\% \\(0.008)}& \makecell{88.8\% \\(0.004)}& \makecell{77.7\% \\(0.005)}& \makecell{93.8\% \\(0.004)}\\ \hline CIFAR100&VGG16&ResNet50V2& \makecell{64.3\% \\(0.013)}& \makecell{88.5\% \\(0.015)}& \makecell{58.1\% \\(0.004)}& \makecell{81.6\% \\(0.015)}& \makecell{69.5\% \\(0.011)}& \makecell{90.1\% \\(0.004)}\\ \hline CIFAR10&VGG16&ResNet50V2& \makecell{86.5\% \\(0.017)}& \makecell{99.2\% \\(0.004)}& \makecell{84.8\% \\(0.014)}& \makecell{98.8\% \\(0.004)}& \makecell{93.3\% \\(0.009)}& \makecell{99.8\% \\(0.002)}\\ \hline \end{tabular} \caption{Use Case 1 Results } \label{tab:Use Case 1 Results} \end{table*} \noindent \textbf{Use-Case 2: Using a subset of confidential data labels.} Based on use-case 1, we now revisit our ImageNet experiments (in which OWSD\xspace had the largest gap with the original cloud performance). We used the same settings as in use-case 1, but the confidential data contained only a subset of 10/100 labels instead of the original 1,000. For each of these two settings---10 and 100---we performed five experiments, with the labels of each randomly selected. We used a 70\%/30\% train/test split with 50 images per label, resulting in 350/3,500 images for the training of the IIN and 150/1,500 images for evaluation. The results of our evaluation are presented in Table \ref{tab:Use Case 2 Results}. It is clear that our performance on ImageNet improves as the number of labels decreases, with OWSD\xspace's top-1 accuracy rising from 67.9\% to 95.5\%, and its top-5 accuracy rising from 87.6\% to 99.9\%. The improvement in performance shows that we were correct in our hypothesis that $\frac{|L_{conf}|}{|L_{cloud}|}$ is the main factor in determining our method's performance.\\ \begin{table} \begin{tabular}{|c|c|c|} \hline Number of labels & Top-1 & Top-5 \\ \hline 1000 & 67.9\% (0.007)& 87.6\% (0.006)\\ \hline 100 & 87.2\% (0.009)& 96.7\% (0.006)\\ \hline 10 & 95.5\% (0.019)& 99.9\% (0.003)\\ \hline \end{tabular} \caption{Use Case 2: IIN's accuracy compared to ``ground truth''} \label{tab:Use Case 2 Results} \end{table} \noindent \textbf{Use-Case 3: Different labels for confidential data and cloud.} We now evaluate OWSD\xspace's ability to infer labels that did not appear in the CMLS's training set. This use-case is important because it assesses whether our proposed approach is generic and transferable. For these experiments we used VGG16, which was trained on CIFAR 100 as our CMLS, and ResNet101, which was trained on ImageNet, as our Encoder. To generate our confidential dataset, we first identified all ImageNet labels that \textit{did not} appear in CIFAR100. Next we randomly sampled 10 labels from these labels---150 images per class, 1,500 overall. We use 70\% of these images (1,050) to train our Internal Inference agent and use the remaining 30\% for evaluation. This process is repeated five times, and the averaged results are presented in Table \ref{tab:Use Case 3 Results}. For this setting we can only present the results with respect to the original image labels, which clearly show that we are able to reach the same level of performance for images with previously-unseen labels as we do for those on which the CMLS was trained. Additionally, we once again show that our approach is most effective when $\frac{|L_{conf}|}{|L_{cloud}|}$ is small.\\ \begin{table} \begin{tabular}{|c|c|} \hline Metric & Internal Inference to Real Labels \\ \hline Top-1 & 96\% (0.015)\\ \hline Top-5 & 99.9\% (0.002)\\ \hline \end{tabular} \caption{Use Case 3: results on ``ground truth''} \label{tab:Use Case 3 Results} \end{table} \noindent \textbf{Use-Case 4: Using an ensemble of Encoders.} The goal of this use-case is to examine whether an ensemble of Encoders can improve the performance of our proposed approach. To this end, we use multiple pre-trained networks as our Encoders. The resulting encodings are scrambled using the same Generative Model and sent to the CMLS. The classification vectors produced for each individual encoding are then concatenated and fed as a single input the to IIN. The results of our analysis are presented in Table \ref{tab:Use Case 4 Results}. We build upon the experiments presented in Table \ref{tab:Use Case 1 Results}, and therefore the results for a single encoder are identical. When using two encoders, the network we added was ResNet50. For our third encoder we used ResNet50v2 for the ImageNet dataset and ResNet101 for CIFAR100/10. The results show that adding encoders indeed improves OWSD\xspace's performance, although the improvement appears to be greater for the CIFAR10/CIFAR100 datasets (which concurs with our conclusion in use case 2). Using the paired-t test, we were able to determine that the two-Encoders setting significantly outperforms the single-Encoder setting with $p<0.001$, and that three-Encoders outperform the two-Encoders with a smaller but still highly significant value of $p<0.01$. \\ \begin{table*}[t] \centering \scriptsize \begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c||c|c|} \hline \multirow{3}{*}{} & \multicolumn{12}{c|}{Internal Inference}& \multicolumn{2}{c|}{Cloud Performance} \\ & \multicolumn{6}{c|}{Real Labels} & \multicolumn{6}{c|}{Cloud Class.} & \multicolumn{2}{c|}{Un-encrypted images} \\ & \multicolumn{3}{c|}{Top-1} & \multicolumn{3}{c|}{Top-5} & \multicolumn{3}{c|}{Top-1} & \multicolumn{3}{c|}{Top-5} & Top-1 & Top-5 \\ \makecell{datasets/ \\ \#encoders}& 1 & 2 & 3 & 1 & 2 & 3 & 1 & 2 & 3 & 1 & 2 & 3 & & \\ \hline ImageNet& \makecell{67.9\% \\ (0.007)} & \makecell{68.6\% \\ (0.002)} & \makecell{69.5\% \\ (0.006)} & \makecell{87.6\% \\ (0.006)} & \makecell{88.9\% \\ (0.004)} & \makecell{89.1\% \\ (0.006)} & \makecell{69.3\% \\ (0.008)} & \makecell{69.9\% \\ (0.004)} & \makecell{71.4\% \\ (0.009)} & \makecell{88.8\% \\ (0.004)} & \makecell{90.1\% \\ (0.003)} & \makecell{90.7\% \\ (0.005)} & \makecell{77.7\% \\ (0.005)} & \makecell{93.8\% \\ (0.004)}\\ \hline CIFAR100& \makecell{64.3\% \\ (0.013)} & \makecell{67.2\% \\ (0.01)} & \makecell{68.4\% \\ (0.007)} & \makecell{88.5\% \\ (0.015)} & \makecell{89.8\% \\ (0.004)} & \makecell{90.4\% \\ (0.009)} & \makecell{58.1\% \\ (0.004)} & \makecell{61\% \\ (0.01)} & \makecell{62.4\% \\ (0.009)} & \makecell{81.6\% \\ (0.015)} & \makecell{84.5\% \\ (0.011)} & \makecell{85.7\% \\ (0.015)} & \makecell{69.5\% \\ (0.011)} & \makecell{90.1\% \\ (0.004)}\\ \hline CIFAR10& \makecell{86.5\% \\(0.017)} & \makecell{88.1\% \\ (0.014)} & \makecell{88.9\% \\ (0.009)} & \makecell{99.2\% \\(0.004)} & \makecell{99.3\% \\ (0.004)} & \makecell{99.4\% \\ (0.001)} & \makecell{84.8\% \\ (0.0014)} & \makecell{86.2\% \\(0.015)} & \makecell{87.4\% \\ (0.008)} & \makecell{98.8\% \\(0.004)} & \makecell{99.2\% \\(0.001)} & \makecell{99.1\% \\(0.002)} & \makecell{93.3\% \\(0.009)} & \makecell{99.8\% \\(0.002)}\\ \hline \end{tabular} \caption{Use Case 4 Results -- the effect of using multiple Encoders on performance.} \label{tab:Use Case 4 Results} \end{table*} \noindent \textbf{Use-Case 5: The Effect of the IIN's training size on performance.} We now analyze the effect of the training set size on the performance of the IIN. While it likely that larger training sets will lead to higher accuracy, our goal is to quantify this impact. We conducted our analysis as follows: We used ILSVRC2012's validation set, from which we randomly sampled 100 labels, to train our IIN and evaluate its performance. We used InceptionV3 as our CMLS (this model was trained on ILSVRC2012's \textit{training set}), and ResNet50 as our Encoder. We sampled different numbers of images from each of our selected 100 labels, and used them to train the IIN. We repeat this experiment five times and report the average results, which are presented in Figure \ref{fig:accScore100}. It is clear that an increase in the training set significantly improves the performance of our approach, with top-1 accuracy improving by 8.7\% and top-5 accuracy improving by 5.2\%. It is also clear that the improvement in OWSD\xspace's performance begins to plateau at around 35 images per label, which achieved an accuracy of 90.6\% compared to the 91.2\% for 45 images, indicating that a relatively small number of training samples is needed for maximal performance. The small number of samples that is needed to train our INN is a crucial aspect of our proposed approach. Given that each key (i.e., the randomly-initialized Generator weights) can only be used a limited number of times before an adversary can reconstruct the original images (see Section \ref{subsec:AnalyzingRobustness} for analysis), requiring a limited number of images to train the INN means that each key can be used for a longer period of time. \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/IMMeanAccuracy100classesTrainonreallabels.png} \caption{The top-1 and top-5 accuracy of OWSD on a randomly-sampled subset of ImageNet, consisting of 100 labels. The results are presented as a function of the number of images per label that were used in OWSD’s training set.} \label{fig:accScore100} \end{figure} \section{Confidentiality Analysis} In this section we analyze four aspects of our proposed approach and demonstrate the difficulties an attacker would face when attempting to recover the original images. First, in Section \ref{subsec:originalImage} we show that our scrambled images do not contain any information that can be understood by humans. Secondly, in Section \ref{subsec:analyzingCloudOutput} we analyze the outputs (i.e., classification vectors) produced by the CMLS for our images, and show that the former's entropy is much higher than that of unscrambled images and that the ``true'' label of the image (i.e., the ground truth) is almost never in the top-5 chosen labels. In Section \ref{subsec:scramblingReconstruct} we analyze our scrambled images and show that they are more difficult to reconstruct than their plaintext counterparts. Finally, in Section \ref{subsec:AnalyzingRobustness} we provide an empirical loose upper bound on the number of images that can be scrambled by OWSD\xspace using a single key. \subsection{Comparing Original and Scrambled Images} \label{subsec:originalImage} We begin by addressing a simple question: can humans identify objects in our scrambled images. Figure \ref{fig:encrypted-pair-example} presents an original image and its scrambled counterpart. It is clear that no information in the scrambled image is discernible to humans using the naked eye. Similar grayscale images were produced for all the images we manually examined. \begin{figure}[h!] \centering \includegraphics[width=\columnwidth]{Figures/originalandtransformedimage.png} \caption{left) The original image. right) The same image, scrambled by OWSD\xspace using embeddings by ResNet50.} \label{fig:encrypted-pair-example} \end{figure} \subsection{Analyzing the Cloud Output} \label{subsec:analyzingCloudOutput} Our goal is to determine whether our approach effectively obfuscates the labels of scrambled images. We used the InceptionV3 and ResNet50 architectures as our CMLS and Encoder models, respectively. The training and evaluation image sets were those of use-case 1 in Section \ref{subsec:evaluationResults}. We begin by comparing the classification vectors produced by the CMLS for each image and its scrambled counterpart. Our results, presented in Table \ref{tab:predictions-vectors-results}, show that the probabilities of any intersection of labels in the top-1 and top-5 labels is 0.07\% and 0.52\%, respectively. Moreover, the confidence scores assigned for each of the original top-1/5 labels have been reduced by an average of 76\%-87\% respectively. Finally, an analysis of the entropy of the classification vectors of plaintext and confidential images shows that the entropy of the latter is more than twice that of the former: 4.3 to 1.97. These results indicate that not only are our scrambled images not discernible to humans, but the CMLS's classification vector does not enable an easy inference of the original label(s) assigned to them. Next, we use PCA to reduce the dimensionality of the classification vectors of original and scrambled images. We randomly chose two labels from ImageNet, each consisting of 50 samples. We present our generated 2D representations in Figure \ref{fig:2Ddist}. It is clear that while the classification vectors for the two original groups of images are clearly separated, all the scrambled images are grouped together. Additionally, the scrambled images' representation is clearly separated from both groups of original images. These results further show that our scrambling process is effective in obfuscating the original label of the image. \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/predictions2Ddistribution.png} \caption{The classification vectors of plaintext and scrambled images of two labels, presented in a 2D space. It is clear that plaintext images are clearly separated, while the scrambled ones are mixed together.} \label{fig:2Ddist} \end{figure} \begin{table} \begin{center} \begin{tabular}{|c|c|} \hline Top-1 Mean Intersection Rate & 0.07\% \\ \hline Top-5 Mean Intersection Rate & 0.52\%\\ \hline Top-1 Mean Reduction & 76\%\\ \hline Top-5 Mean Reduction & 87\%\\ \hline \end{tabular} \caption{Comparison of the label intersection and relative confidence scores for plaintext and scrambled images.} \label{tab:predictions-vectors-results} \end{center} \end{table} \begin{comment} \begin{table} \footnotesize \begin{center} \begin{tabular}{|c|c|} \hline Mean Entropy for original images & 1.97\\ \hline Mean Entropy for scrambled images & 4.3\\ \hline \textbf{Mean Entropy Gain} & \textbf{2.33}\\ \hline Maximal possible Entropy & 9.97 \\ \hline \end{tabular} \caption{Analysis of the mean entropy of the cloud-based model’s prediction vectors} \label{tab:mean-etropy-results} \end{center} \end{table} \end{comment} \subsection{Reconstruction of Scrambled Images} \label{subsec:scramblingReconstruct} In previous sections we showed that our scrambled images are not discernible by human users, and that they induce a higher degree of entropy in their classification. Our goal now is to determine whether our scrambled images are more difficult to reconstruct. We used an autoencoder in two experimental settings: \textit{a)} receive the original image as input, and reconstruct it; \textit{b)} receive the scrambled image as input, and reconstruct the original image. As our autoencoder we used the well-known DCGAN architecture \cite{radford2015unsupervised}. We used DCGAN's discriminator, which we augmented with additional residual blocks, as our encoder. DCGAN's generator was used as our decoder. For OWSD\xspace's setup we used the InceptionV3 architecture as our cloud-based model, and ResNet50 as our Encoder. For this experiment we randomly selected 100 labels from ImageNet, and then retrieved all 150 images associated with each label. We therefore created a set of 15,000 images. We than randomly split these 15,000 images into train and test sets, using a 90\%/10\% split. This process was repeated twice, and we present their averaged results in Table \ref{tab:AETrainMse2}. To enable faster convergence (i.e., using less training samples), all images were reduced to a quarter of their original size (128x128 instead of 256x256). We define difficulty to reconstruct as the \textit{number of samples needed for the training of autoencoder}. This definition is crucial for Section \ref{subsec:AnalyzingRobustness}, where we analyze our model's robustness. The results of our evaluation are presented in Table \ref{tab:AETrainMse2} and Figure \ref{fig:70gtest}. While this training set size is sufficient for a decent reconstruction of images when applied on the original images, reconstruction quality for scrambled images is so low that the images are incomprehensible. \begin{figure} \begin{subfigure}{.23\textwidth} \centering \includegraphics[width=\textwidth]{Figures/70otest.png} \caption{} \label{fig:70otest} \end{subfigure} \begin{subfigure}{.23\textwidth} \centering \includegraphics[width=\textwidth]{Figures/70gtest.png} \caption{} \label{fig:70gtest} \end{subfigure} \caption{The inputs ($x$), targets ($y$) and reconstructions ($\hat{y}$) of images. Figure \ref{fig:70otest} presents the use-case where we receive the plaintext image as input, and \ref{fig:70gtest} presents the use-case where we receive the scrambled image.} \label{fig:autoencoder training} \end{figure} \begin{comment} \begin{table} \footnotesize \centering \begin{tabular}{|c|c|c|c|c|} \hline \multirow{3}{*}{Train Set Size} & \multicolumn{2}{c|}{Original Images} & \multicolumn{2}{c|}{Scrambled Images} \\ & Test Loss (MSE) & $\sigma$ & Test Loss (MSE) & $\sigma$\\ \hline 13,500 & 0.021 & 0.004 & 0.061 & 0.001\\ \hline 9,000 &...&...&...&...\\ \hline \end{tabular} \caption{\yiftach{Additional train set sizes performances are interesting (there are more)? if not use the other table or just incorporate in text.} Average of two different subsets of ImageNet ILSVRC2010 test set \yiftach{explained above}} \label{tab:AETrainMse1} \end{table} \end{comment} \begin{table} \footnotesize \centering \begin{tabular}{|c|c|c|} \hline Images Type & Test Loss (MSE) & $\sigma$ \\ \hline Original & 0.021 & 0.004\\ \hline Scrambled & 0.061 & 0.001\\ \hline \end{tabular} \caption{The autoencoder's reconstruction loss when applied on original and scrambled images} \label{tab:AETrainMse2} \end{table} \subsection{Analyzing the Robustness of Our Approach} \label{subsec:AnalyzingRobustness} As explained in Section \ref{sec:proposedMethod}, only the encrypted images ever leave the organizational network. As a result, attackers are likely to have to resort to a practically infeasible brute-force search to discover our randomly-set Generator weights. However, we are unable at this time to provide a theoretical proof to this claim, and therefore provide an \textit{empirical proof}. We do so by creating a scenario in which the adversary has access to \textit{additional information that enables a more effective attack against our approach}. We then use the amount of information required to carry out this attack as a bound on the number of images that can be securely scrambled by any one given key.\\ \noindent \textbf{The proposed attack scenario.} Assume that an adversary has gained access to pairs of original-scrambled images (i.e., not only does the adversary have access to such sets, but she can also pair them accordingly). The adversary can now train a neural architecture---more specifically, an autoencoder---to reconstruct the original image from the encrypted one. This scenario, in fact, is exactly the setup described in the second experiments of Section \ref{subsec:scramblingReconstruct}, \textit{where we showed that 13,500 original/scrambled image pairs are insufficient for any meaningful reconstruction of scrambled images}. It is also very important to note that---as shown in use-case 5 in Section \ref{subsec:evaluationResults}--- the maximal number of scrambled images needed to train the IIN is 4,500 (for confidential data with 100 labels). The aforementioned statistics provide us with a bound on the number of images that can be safely scrambled by OWSD\xspace. Given that 13,500 image pairs are not enough to mount a successful attack, and that 4,500 images \textit{at most} are needed to train our IIN, then we are able to safely use any given key for 9,000 submissions to the cloud. When this number is reached, all we have to do is re-initialize our key. Finally, we wish to emphasize the following: \begin{itemize} \item We stress again that the figure of 13,500 is a very loose bound, created using an unrealistic scenario that greatly favors the adversary. Moreover, the autoencoders were trained on images whose size was only a quarter of the original, thus making the reconstruction process easier. \item The process of generating a new key is instantaneous, and the training of the IIN required approximately five minutes on a laptop (see INN description in Section \ref{sec:proposedMethod}). Therefore, replacing the scrambling key has a negligible computational cost. \item This process can easily be made more secure with the deployment of multiple keys and IINs. Doing so will not only improve performance (see use-case 4 in Section \ref{subsec:evaluationResults}), but their gradual replacement will make an adversarial attack even more difficult. \end{itemize} \begin{comment} \subsection{Empirical Transformation Strength Analysis} \subsubsection{Training Data Requirements} The goal of the following evaluations is to substantiate the amount of data that is needed to sufficiently train the organizational inference model. The evaluation includes training the organizational model using varying amounts of samples per class, as well as different amount of classes, and calculating the achieved performances. ILSVRC2012 validation set was used as the dataset (organizational data) for the evaluation \yiftach{maybe not necessary to reference}, along with two subsets of it with 100 classes each (50 samples per class). Pre-trained ResNet50 was used as encoder and pre-trained InceptionV3 as an external model. The organizational model was trained to predict the ground-truth labels as in use-case 1. The results reported are the average performance on the two 100-labels subsets. \ref{fig:accScore1000} \ref{fig:accDiff1000} \yiftach{add table? add 100 data} \end{comment} \begin{comment} \subsubsection{Data Reconstruction Evaluation} The goal of this section is to empirically evaluate whether the original data can be recreated from the transformed data, and if so what is the size of the data that is required. To perform this analysis we assume that an hostile entity has access to N number of pairs of original and transformed images and tries to learn a mapping between the transformed images and their original form. \yiftach{relaxed assumption ??? Classified data does not leave the organization unencrypted in all the variations of our proposed approach. However, the variation that utilizes an unclassified set does send both plain and encrypted data that might be exposed.} A Deep Convolutional Autoencoder is used to attempt to learn the mapping by attempting to learn how to recreate the original image from the generated one. As a comparison target for the recreation performance, the same autoencoder architecture is also trained to reconstruct the original image \yiftach{(from the original image)}. The same hyper-parameters were used for the training of both autoencoders. The encoder part of the autoencoder architecture used is based on the DCGAN discriminator model adapted to the task and supplemented with residual blocks. The decoder part is based on the generator of DCGAN. The aim of the experiment is to determine how many samples are required for a sufficient recreation. Therefor, four different subsets of ILSVRC2010 were used as datasets with different amounts of classes and training images pairs. To assist the implementation and execution of these experiments the images were loaded to a quarter of their original size ($(128,128)$ RGB instead of $(256,256)$ RGB) \yiftach{Add experiments with less samples} The results show that it is harder to learn a mapping from the transformed images to their original form than it is to learn to an identity mapping \yiftach{Gilad please assert this phrasing}. Figure \ref{fig:avgTestRecon} shows the average test losses of the different encoders in dependence of the dataset size. There is a significant difference between the losses achieved by the models that received the original images than the ones that received the transformed images. Additionally, a major increase in loss is observed for datasets with less than [fill number] samples \yiftach{fill number. add reference to the number of classes. determine a threshold per class}. \end{comment} \begin{comment} \begin{figure}[h!] \centering \includegraphics[width=0.9\columnwidth]{Figures/Average Evaluated Test Loss (MSE) reconstruction.png} \caption{Average MSE Test Loss in dependence of Train Set Size. we defined two labels amounts-10, 100. for each label amount we used two different subsets of ImageNet ILSVRC2010 test set with randomly selected labels and 150 samples per label (each 10-label set contains 1,500 images and each 100-label set contains 15,000). In addition we used varying number of samples per class. we used random train/test split of 90\%/10\%. These definitions resulted in varying overall sizes of the autoencoder train set. The results of each pair of subsets with the same labels count are averaged and presented.} \label{fig:avgTestRecon} \end{figure} \end{comment} \section{Conclusion} We present OWSD\xspace, a scrambling-based approach that offers many of the advantages of Homomorphic encryption at a fraction of the computational cost. We showed that when the number of labels in the confidential data is smaller than in the CMLS, our approach can achieve the same performance as the CMLS. For future work, we intend to conduct experiments on additional types of data, and explore the use of our approach in a multi-agent collaborative setting.
{'timestamp': '2021-11-08T02:03:28', 'yymm': '2111', 'arxiv_id': '2111.03125', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03125'}
arxiv
\section{Introduction}\label{introduction} We consider nonparametric prediction with multiple categorical or functional predictors, or a mixture of both. Especially in the case of a categorical, multi-class response, the number of corresponding methods found in the literature is very limited. For instance, \cite{FuchsGertheissTutz2015} use an ensemble approach for classification of multiple functional covariates. They estimate the posterior probability separately for every covariate and weight the results to get an estimate of the overall posterior probability. Further they use several semi-metrics and combine the results in an analogous way. Thus their method can be used for feature as well as variable selection. \cite{GulEtal2018} follow a similar approach for continuous or categorical covariates. They use an ensemble of kNN classifiers based on random subsets of the covariates with the aim to select the most relevant covariates. \cite{MbinaNkietObiang2019} propose a procedure for classification in more than two groups with continuous and categorical (binary) predictors. Their aim is to select among the continuous variables those that are relevant for the classification. They use a criterion to quantify the loss of information resulting from selecting not all continuous variables and compare different procedures to estimate the criterion's value. \cite{RacineHartLi2006} test for significance of categorical predictors in regression models with continuous and categorical predictors. They use a product kernel to estimate the regression function and approximate the distribution of their test statistic under the null using a bootstrap procedure. \cite{Shang2014} considers a nonparametric regression model with a mixture of continuous, categorical and functional covariates. He uses a Bayesian approach to determine simultaneously the different bandwidths. His method can also be used for variable selection since the irrelevant variables are smoothed out by the appropriate bandwidth. \begin{figure} \includegraphics[width=0.33\textwidth]{MFCC1.pdf} \hspace{-2mm}\includegraphics[width=0.33\textwidth]{MFCC3.pdf} \hspace{-2mm}\includegraphics[width=0.33\textwidth]{MFCC10.pdf} \caption{Illustration of the ArabicDigits in terms of a subset of the available signals for three Mel Frequency Cepstrum Coefficients, and digits `2', `3', `5', and `7'; solid lines correspond to the respective mean curves.}\label{fig:mfcc} \end{figure} For illustration, consider the following classification problem: the well-known {\it ArabicDigits} data set from the R-package {\it mfds} by \cite{Rmfds}, which contains time series of 13 Mel Frequency Cepstrum Coefficients (MFCCs) corresponding to spoken Arabic digits. MFCCs are very common for speech recognition, see \cite{KoolagudiRastogiRao2012} for a detailed explanation. Figure\ref{fig:mfcc} shows a subset of the available signals for MFCC1, MFCC3 and MFCC10, and digits `2', `3', `5', and `7'. In total, and more generally speaking, we are faced with a 10-class problem (digits $0,1,\ldots,9$) and 13 functional predictors. \begin{figure}[h!] \begin{centering} \subfigure{\includegraphics[width=0.49\textwidth]{TraRHgli9.pdf}} \subfigure{\includegraphics[width=0.49\textwidth]{TraHori9.pdf}} \end{centering} \caption{Examples for trajectories from one female individual. The orientational movement of the head (right chart) can be interpreted as follows: An increase in the x-component refers to looking to the right; a decrease to looking to the left. An increase in the y-component refers to looking up; a decrease to looking down. An increase in the z-component refers to tilting the head to the right; a decrease to tilting it to the left.}\label{fig:trajec} \end{figure} Besides `classical', one-dimensional functional data, also other types of functional data such as 3-dimensional trajectories are getting more and more attention; see, e.g., \cite{Fernandez-FonteloEtal2021}. The data set considered in the paper at hand contains 3-dimensional movement data of the hands and head of participants in a psychological experiment, compare \cite{VogelEtal2021}. The participants were asked to perform guided upper body exercises like stretching their arms or embracing themselves. Furthermore, the participants were given a virtual reality headset and two joysticks, one for each hand. With these devices the movements of the hands and the head were recorded. The movements are recorded as `global', `local' and `orientational', where `global' describes the position in the lab, `local' the position relative to the position of the feet and `orientational' records rotational motions; see \cite{VogelEtal2021} for a more detailed description of the experimental setting, and \cite{VahleTomasik2021} for a similar experiment, with the focus being on memory performance, physical strength and endurance. Figure \ref{fig:trajec} shows some example trajectories. It is easy to identify from the chart the time point when the participant is asked to raise her hands and to build the letter `T' directly afterwards. The virtual reality that was created for the participants, was an avatar to mimic the movements. The participants were all young, while the avatars were either young or elderly people. One of the questions of this psychological experiment was whether the experimental condition, that is, the class of the avatar (young vs.~elderly person) could be reconstructed from the movement data. Thus we have a binary classification problem with multiple 3-dimensional functional predictors (trajectories). The rest of the paper is organized as follows. In Section~\ref{Methods}, we begin with the regression case to explain the idea of our approach, and then put our focus on classification problems. Both cases are investigated through simulation studies in Section~\ref{NumExp}. The real data mentioned above is revisited in Section~\ref{RealData}, and Section~\ref{Conclude} concludes with a short discussion and outlook. \section{Methodology}\label{Methods} Suppose there are training data ${\mathbf X}_i=(X_{i1},\ldots,X_{ip})$, $i=1,\ldots,n$, with variables contained in ${\mathbf X}_i$ being continuous, categorical, functional, or a mixture of those. In addition, there is information $Y_i$ on a scalar, dependent variable which may be continuous or categorical. \subsection{Regression}\label{Remod} Let us first consider the regression problem with continuous $Y_i$ and a single covariate $X_i$, where \[Y_i = f(X_i) + \epsilon_i,\] $f$ being an unknown regression function, and $\epsilon_i$ some mean zero noise variable, potentially with some further assumptions such as independent identically distributed (iid) across subjects $i = 1,\ldots,n$.\\ For a new observation with known covariate value $x$, but unknown $Y$, a kernel-based, nonparametric prediction $\hat{Y} = \hat{f}(x)$ is, e.g., given by \[\hat{f}(x) = \frac{\sum_{i=1}^{n} Y_i K(d(X_i,x)/h_n)}{\sum_{i=1}^{n} K(d(X_i,x)/h_n)},\] with some kernel $K(\cdot)$, bandwidth $h_n\searrow 0$ (for $n \rightarrow \infty$) and distance measure $d(\cdot,\cdot)$ that is appropriate for the type of predictor considered. In particular with functional data, $d(\cdot,\cdot)$ may also be calculated through so-called \emph{semi}-metrics, compare \cite{FerratyVieu} and Section~\ref{Metric} below. Now suppose for multiple (and potentially very different) predictors as given above, there are $d_1(\cdot,\cdot),\ldots,d_p(\cdot,\cdot)$ available. With categorical predictors $X_{il},x_l \in \{1,\ldots,G_l\}$ we may use \[d_l(X_{il},x_l) = \left\{ \begin{array}{ll} 0 & \mbox{ if } X_{il} = x_l,\\ 1 & \mbox{ if } X_{il} \neq x_l, \end{array} \right.\] or for functional $X_{ij},x_j \in L^2$, for instance, \begin{equation}\label{metric} d_j(X_{ij},x_j) = \sqrt{\int_{\mathcal{D}_j} (X_{ij}(t) - x_j(t))^2 dt}, \end{equation} where $\mathcal{D}_j$ is the domain of the functions $X_{ij},x_j$. In what follows, we will omit the $\mathcal{D}_j$ for the sake of readability. \bigskip When predicting $Y$, predictor information ${\mathbf x}=(x_1,\ldots,x_p)$ should be considered jointly. A somewhat natural way to do so, appears to be \begin{equation}\label{fhat}\hat{Y}=\hat{f}({\mathbf x}) = \frac{\sum_{i=1}^{n} Y_i K(\omega_1d_1(X_{i1},x_1) + \ldots + \omega_pd_p(X_{ip},x_p))}{\sum_{i=1}^{n} K(\omega_1d_1(X_{i1},x_1) + \ldots + \omega_pd_p(X_{ip},x_p))},\end{equation} with positive weights $\omega_1,\ldots,\omega_p$ that should be estimated from the data. With $\hat{Y}_{(-i)}$ being the leaving-one-out estimate \[\hat{Y}_{(-i)} = \frac{\sum_{s\neq i} Y_s K(\omega_1d_1(X_{s1},X_{i1}) + \ldots + \omega_pd_p(X_{sp},X_{ip}))}{\sum_{s\neq i} K(\omega_1d_1(X_{s1},X_{i1}) + \ldots + \omega_pd_p(X_{sp},X_{ip}))},\] we may estimate $\omega_1,\ldots,\omega_p$ by minimizing \begin{equation}\label{Qre} Q(\omega_1,\ldots,\omega_p) = \sum_{i=1}^n (Y_i - \hat{Y}_{(-i)})^2. \end{equation} By $\hat\omega_1,\ldots,\hat\omega_p$ we denote these minimizing weights. The nonparametric estimator $\hat f$ defined in \eqref{fhat} is an extension of the well known Nadaraya-Watson estimator. Similar extensions of this kind of kernel estimator to the multivariate case are also well established; see, e.g., \cite{HaerdleMueller1997} for some deeper insight. The typical form of a multivariate Nadaraya-Watson estimator for continuous covariates is \[\hat f_{\text{NW}1}({\mathbf x})=\frac{\sum_{i=1}^nY_iK(|X_{i1}-x_1|/h_1)\cdot\ldots\cdot K(|X_{ip}-x_p|/h_p)}{\sum_{i=1}^nK(|X_{i1}-x_1|/h_1)\cdot\ldots\cdot K(|X_{ip}-x_p|/h_p)}\] with bandwidths $(h_1,\ldots,h_p)$, or \[\hat f_{\text{NW}2}({\mathbf x})=\frac{\sum_{i=1}^nY_iK(\|{\mathbf H}^{-1}({\mathbf X}_i-{\mathbf x})\|)}{\sum_{i=1}^nK(\|{\mathbf H}^{-1}({\mathbf X}_i-{\mathbf x})\|)}\] where $\|\cdot\|$ is, e.g., the euclidean norm and ${\mathbf H}$ is a symmetric bandwidth matrix. If we set $K$ in our $\hat f$ defined in \eqref{fhat} as an exponential function, e.g., the Picard kernel $K(u)=e^{-u}I\{u\geq 0\}$, we have a very similar setting to $\hat f_{\text{NW}1}$ with $|X-x|$ replaced by the more general $d(X,x)$. Also, our $\hat f$ can be interpreted as a form of $\hat f_{\text{NW}2}$ with $\|\cdot\|$ being some kind of $L_1$-norm (Manhattan-norm). Estimation of the weights (\ref{Qre}) is similar to determining an optimal bandwidth for the Nadaraya-Watson estimator with cross-validation. There are different possibilities to choose the starting values for the numerical minimization of $Q(\omega_1,\ldots,\omega_p)$. In the simulation studies to follow in Section~\ref{NumExp}, for instance, we will use a rule of thumb for the bandwidth size for the regression case, whereas for the classification case (see Section~\ref{ClMod}) we determine a pre-estimator for each weight by considering $p$ models each with only one predictor. \subsection{Classification}\label{ClMod} In the classification case we consider models that contain functional and/or categorical predictors $X_{ij}$ ($i=1,\ldots,n$, $j=1,\ldots,p$) and categorical responses $Y_i \in\{1,\ldots,G\}$ for $i=1,\ldots,n$. Especially the case $p>1$, $G>2$ is of interest since in this `multi$^2$fun' case (multiple, possibly functional predictors and a multi-class response) there are to the best of our knowledge no other genuinely nonparametric methods available (compare Section \ref{introduction}). Following the idea for the regression case, we estimate the posterior probability $P_g({\mathbf x}):=P(Y=g|{\mathbf x})$ for a new set of predictors ${\mathbf x}=(x_1,\ldots,x_p)$ with unknown class label $Y$ by \[\hat P_g({\mathbf x})=\frac{\sum_{i=1}^nI\{Y_i=g\}K\left(\omega_1d_1(X_{i1},x_1)+\ldots+\omega_pd_p(X_{ip},x_p)\right)}{\sum_{i=1}^nK\left(\omega_1d_1(X_{i1},x_1)+\ldots+\omega_pd_p(X_{ip},x_p)\right)}\] with data-driven weights $\omega_1,\ldots,\omega_p$. As before we determine the weights by minimizing \begin{equation}\label{Qcla} Q(\omega_1,\ldots,\omega_p)= \sum_{i=1}^n\sum_{g=1}^G (I\{Y_i=g\} - \hat{P}_{g(-i)})^2 \end{equation} where $\hat P_{g(-i)}$ is the leave-one-out estimator \[\hat P_{g(-i)}=\frac{\sum_{s\neq i}I\{Y_s=g\}K\left(\omega_1d_1(X_{s1},X_{i1})+\ldots+\omega_pd_p(X_{sp},X_{ip})\right)}{\sum_{s\neq i}K\left(\omega_1d_1(X_{s1},X_{i1})+\ldots+\omega_pd_p(X_{sp},X_{ip})\right)}.\] Quantity \eqref{Qcla} is also know as the Brier score or quadratic scoring rule, compare \cite{GneRaf2007}, \cite{Brier1950} and \cite{Selten1998}. \subsection{Distances and (Semi-)Metrics}\label{Metric} A crucial question when dealing with functional predictors is the choice of the (semi-)metric $d$, contrary to models with predictors that take values in $\mathbb{R}^p$, since in a finite dimensional euclidean space all norms are equivalent. This concept fails for functional predictors since they take values in an infinite dimensional space. Even more, restricting $d$ to be a metric is sometimes too restrictive in the functional case. That is why semi-metrics are considered such as \begin{equation}\label{semi} d(u,v) = \sqrt{\int (u'(t) - v'(t))^2 dt},\end{equation} where $u,v$ are functional predictors and $u',v'$ their derivatives, see \cite{FerratyVieu} Chapter 3 for a deeper insight on this topic. An important difference between semi-metric \eqref{semi}, for instance, and a metric is that in the former case $d(u,v) = 0$ will also be obtained if $v(t) = u(t) + c$, for some constant $c \neq 0$, i.\,e., if $v$ is just a vertically shifted version of $u$. In general, the choice which (semi-)metric to take depends on the shape of the data and the goal of the statistical analysis. If, for example, the functional observations shall be displayed in a low-dimensional space, one possibility to do this is to use (functional) principal component analysis; compare, e.g., \cite{RamsaySilverman} and \cite{YaoMueWan2005}. In general, results can look very different, depending on the chosen measure of proximity. In Chapter~3 of \cite{FerratyVieu} examples to illustrate this effect are given. Also, further suggestions for semi-metrics and a survey which semi-metric may be appropriate for which situation can be found there. For example, semi-metric~\eqref{semi}, which is based on the derivatives, is often well suited for smooth data whereas for rough data a different approach should be considered. The (semi-)metric also plays an important role for the asymptotic properties of nonparametric functional estimators. Chapter 13 in \cite{FerratyVieu} is dedicated to this issue. The small ball probability that is defined as $P(d(u,v)<\epsilon)$ appears in the rate of convergence of many nonparametric estimators such as the functional Nadaraya-Watson estimator. If the small ball probability decays very fast when $\epsilon$ tends to zero (in other words, if the functional data are very dispersed) the rate of convergence will be poor, whereas a small ball probability decaying adequately slowly will lead to a rate of convergence similar to those found in finite dimensional settings. In our simulation studies and for the real data examples we will use a form of the $L^2$-metric as already given in~\eqref{metric}. This is a standard choice which works quite well for our examples. Note that, although our focus in this paper is not on the choice of the distance measure, our procedure could also be used to give a data driven answer on the question which (semi-)metric to choose. For this sake let us suppose there is only one functional predictor with observations $X_1,\ldots,X_n$ and a set of $p$ potential (semi-)metrics $d_1,\ldots,d_p$. With this we set $$\hat f(x)=\frac{\sum_{i=1}^nY_iK(\omega_1d_1(X_i,x)+\ldots+\omega_pd_p(X_i,x))}{\sum_{i=1}^nK(\omega_1d_1(X_i,x)+\ldots+\omega_pd_p(X_i,x))}$$ and $$\hat P_g(x)=\frac{\sum_{i=1}^nI\{Y_i=g\}K(\omega_1d_1(X_i,x)+\ldots+\omega_pd_p(X_i,x))}{\sum_{i=1}^nK(\omega_1d_1(X_i,x)+\ldots+\omega_pd_p(X_i,x))},$$ respectively. Then, the estimated weights $\hat\omega_1,\ldots,\hat\omega_p$ tell us which distance measures are appropriate to explain the influence of the covariate on the response: those that are weighted highest. This approach is especially useful for feature selection since the (semi-)metrics can be chosen such that each $d_j$ focuses on a certain feature of the curve, compare to \cite{FuchsGertheissTutz2015}. \section{Numerical Experiments}\label{NumExp} \subsection{Regression Problems}\label{ReSim} \subsubsection{Set-up} To investigate the finite sample performance of our procedure we generate data according to three different models, namely \begin{itemize} \item[(CatR)] For $i=1,\ldots,n$, the observations are generated as \\ $Y_i=2(X_{i1}+\ldots+X_{iq})+\varepsilon_i$, with iid $X_{i1},\ldots,X_{ip}\sim${\it B}$(0.5)$, $q\leq p$. \item[(FunR)] For $i=1,\ldots,n$ and $j=1,\ldots,p$, the functional observations $X_{ij}(t)$, $t \in [0,T]$, are generated according to $$\tilde X_{ij}(t)=\frac 1{100}\left(15+\sum_{l=1}^5B_{ij,l}\sin\left(\frac tT(5-B_{ij,l})2\pi\right)-M_{ij,l}\right),$$ where $B_{ij,l}\sim\mathcal{U}[0,5]$ and $M_{ij,l}\sim\mathcal{U}[0,2\pi]$ for $l=1,\ldots,5$, $j=1,\ldots,p$, $i=1,\ldots,n$, and $T=300$. $\mathcal{U}$ stands for the (continuous) uniform distribution. Then, $X_{ij}(t)$ is calculated from $\tilde X_{ij}(t)$ by scaling it in direction $i$ and then dividing each value by 10. The regression is built by the functional linear model $$Y_i=5\sum_{j=1}^{q}\int X_{ij}(t)\gamma_{3,\frac 13}(t/10)dt+\varepsilon_i,\quad q\leq p,$$ where the coefficient function $\gamma_{a,b}(t)=b^a/\Gamma(a)t^{a-1}e^{-bt}I\{t>0\}$ is the density of the Gamma distribution. See \cite{RamsaySilverman} Chapter 15 or \cite{KokoszkaReimherr} Chapter 4 for an introduction to functional linear models. Furthermore, we assume that each $X_{ij}$ is observed on a dense, equidistant grid of 300 evaluation points. \item[(MixR)] In this scenario we combine functional and categorical predictors. For $i=1,\ldots,n$, we generate functional covariates $X_{i1},\ldots,X_{ip_{\text{fun}}}$ in the same manner as above (FunR) and categorical covariates $X_{i(p_{\text{fun}}+1)},\ldots,X_{i(p_{\text{fun}}+p_{\text{cat}})}$ $\sim${\it B}$(0.5)$, such that $p_{\text{fun}}+p_{\text{cat}}=p$. With this, $$Y_i=5\sum_{j=1}^{q_{\text{fun}}}\int X_{ij}(t)\gamma_{3,\frac 13}(t/10)dt+2(X_{i(p_{\text{fun}}+1)}+\ldots+X_{i(p_{\text{fun}}+q_{\text{cat}})})+\varepsilon_i$$ for some $q_{\text{fun}}\leq p_{\text{fun}}$ and $q_{\text{cat}}\leq p_{\text{cat}}$. \end{itemize} The errors $\varepsilon_i$ are iid standard normal in all models.\\ In all three scenarios we investigate `minimal' and `sparse' cases. Specifically, for (CatR) and (FunR), we compare the cases $q=1$, $p=2$ (minimal: (CatR.m) and (FunR.m), respectively) and $q=3$, $p=18$ (sparse: (*.s)), and for (MixR) the cases $q_{\text{fun}}=q_{\text{cat}}=1$, $p_{\text{fun}}=p_{\text{cat}}=2$ (minimal: (*.m)) and $q_{\text{fun}}=q_{\text{cat}}=2$, $p_{\text{fun}}=p_{\text{cat}}=8$ (sparse: (*.s)). For all generated data sets we use a one-sided Picard kernel $K(u)=e^{-u}I\{u\geq 0\}$ and the results shown are based on 500 replications each. To uncouple the estimation of the weights from the bandwidth that goes to zero as $n$ grows, we set \begin{eqnarray*} d_{\text{fun}}(X_{ij},x_j)&:=&\frac 1{h_n^\text{fun}c_j^\text{fun}}\sqrt{\int(X_{ij}(t)-x_j(t))^2dt},\\ d_{\text{cat}}(X_{ij},x_j)&:=&\frac 1{h_n^\text{cat}c_j^\text{cat}}\sqrt{(X_{ij}-x_j)^2}\\ &=&\frac 1{h_n^\text{cat}c_j^\text{cat}}I\{X_{ij}\neq x_j\}, \end{eqnarray*} with norming constants $$c_j^\text{fun}=\sqrt{\int \frac1{n-1}\sum_{l=1}^n\left(X_{lj}(t)-\frac 1n\sum_{k=1}^nX_{kj}(t)\right)^2dt},$$ $$c_j^\text{cat}=\sqrt{\frac1{n-1}\sum_{l=1}^n\left(X_{lj}-\frac 1n\sum_{k=1}^nX_{kj}\right)^2},$$ and bandwidths $h_n^\text{fun}=n^{-\frac1{p+4}}$ and $h_n^\text{cat}=\frac{p+4}{\ln(n)}$, respectively. This choice of bandwidths coincides with the order of the optimal bandwidths in \cite{RacineLi2004} when $K$ is the one sided Picard kernel and the categorical covariates are {\it B}$(0.5)$-distributed. The prediction is then calculated as given in~\eqref{fhat}. For (MixR), this means \[\hat Y=\hat f({\mathbf x})=\frac{\sum_{i=1}^nY_iK\left(\sum_{j=1}^{p_\text{fun}}\omega_jd_\text{fun}(X_{ij},x_j)+\sum_{j=p_\text{fun}+1}^{p_\text{fun}+p_\text{cat}}\omega_jd_\text{cat}(X_{ij},x_j)\right)}{\sum_{i=1}^nK\left(\sum_{j=1}^{p_\text{fun}}\omega_jd_\text{fun}(X_{ij},x_j)+\sum_{j=p_\text{fun}+1}^{p_\text{fun}+p_\text{cat}}\omega_jd_\text{cat}(X_{ij},x_j)\right)},\] where $p_\text{fun}$ is the total number of functional covariates, $p_\text{cat}$ the total number of categorical covariates and $p=p_\text{fun}+p_\text{cat}$. The weights are estimated by minimizing $Q(\omega_1,\ldots,\omega_p) = \sum_{i=1}^n (Y_i - \hat{Y}_{(-i)})^2$, with $\hat Y_{(-i)}$ being the leave-one-out estimate as described above, e.g., \[\hat Y_{(-i)}=\frac{\sum_{s\neq i}Y_sK\left(\sum_{j=1}^{p_\text{fun}}\omega_jd_\text{fun}(X_{sj},X_{ij})+\sum_{j=p_\text{fun}+1}^{p_\text{fun}+p_\text{cat}}\omega_jd_\text{cat}(X_{sj},X_{ij})\right)}{\sum_{s\neq i}K\left(\sum_{j=1}^{p_\text{fun}}\omega_jd_\text{fun}(X_{sj},X_{ij})+\sum_{j=p_\text{fun}+1}^{p_\text{fun}+p_\text{cat}}\omega_jd_\text{cat}(X_{sj},X_{ij})\right)}\] in case of (MixR). For the minimization we make use of the R function {\it optim} (\cite{R}) with starting value $(\omega_1,\ldots,\omega_p)=(1,\ldots,1)$. \subsubsection{Results}\label{ReRe} The minimizing weights for our six different scenarios and sample size $n=100, 500, 1000$ are shown in Figure \ref{fig:Reweights}. To increase comparability between the different models we display normed weights $\frac {\hat\omega_j}{\sum_{k=1}^p\hat\omega_k}$. This can also be interpreted as separating the estimation of the weights (normed weights) and optimization of the bandwidth ($h_{\text{opt}}=\frac{h_n^{\text{fun/cat}}}{\sum_{k=1}^p\hat\omega_k}$). It can be seen that the selection of relevant predictors works well, as the covariates with influence on the response get distinctly higher weights than those without in all scenarios. The sum over the weights for relevant covariates should be approximately one whereas the weights for irrelevant covariates should be close to zero. Both is visible for the simulated data. To compare our prediction results to, we also compute the minimizer of $Q$ under the restrictions \begin{itemize} \item[(i)] $\omega_1=\omega_2=\ldots=\omega_p$, \item[(ii)] $\omega_j=0$ for all covariates with no influence on the response. \end{itemize} Thus under restriction (ii), which we also call `oracle', we determine the minimizing weights only for the relevant covariates, whereas restriction (i) leads to a single minimizing weight and can be interpreted as determination of a suitable overall/global bandwidth. Note, however, (ii) is only doable in simulations where the truth is known, and no option in practice. In Figure \ref{fig:Remse} the squared estimation error of $\hat f$ is shown, where we display the average over 100 (minimal case) and 10000 (sparse case) ${\mathbf x}$-values, respectively. In scenario (CatR) with $p=2$, we only use the 4 possible ${\mathbf x}$-values. In all other scenarios, the ${\mathbf x}$-values are generated randomly in the same way as the covariates in the respective scenario. In each of the $500$ replications, new ${\mathbf x}$-values are generated. The explicit formula to calculate the squared estimation error for each replication is $$\frac 1{N}\sum_{l=1}^{N} \left(\frac{\hat f({\mathbf x}_l)-f({\mathbf x}_l)}{\text{range}(f)}\right)^2,$$ where $N$ is the number of ${\mathbf x}$-values, $f$ is the true regression function used to generate the data, ${\mathbf x}_1,\ldots,{\mathbf x}_{N}$ are the $x$-values (generated at random) and $\text{range}(f)=\max_{l}f({\mathbf x}_l)-\min_lf({\mathbf x}_l)$. In all cases the results for our procedure are comparable to those under restriction (ii) and better than those under restriction (i), as expected. To get an insight in the influence of the ${\mathbf x}$-values on the estimation error we ran the simulations also with ${\mathbf x}$-values that are the same for each replication. The results are almost identical to those with varying ${\mathbf x}$-values shown in Figure \ref{fig:Remse}. Only the variance of the estimation errors is slightly larger with varying ${\mathbf x}$-values (as could be expected). Another possible way to asses the performance of our procedure would be to look at the (test set) prediction error $Y-\hat f({\mathbf x})=\varepsilon+f({\mathbf x})-\hat f({\mathbf x})$ instead of the estimation error as described above. The results would be similar since the errors $\varepsilon$ are independent of the predictors and thus the mean squared prediction error and the mean squared estimation error only differ in the variance of $\varepsilon$. \begin{figure} \begin{centering} \subfigure{\includegraphics[width=0.28\textwidth]{WcatMin.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.52\textwidth]{WcatSp.pdf}} \\ \subfigure{\includegraphics[width=0.28\textwidth]{WfunMin.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.52\textwidth]{WfunSp.pdf}} \\ \hspace{1.8cm}\subfigure{\includegraphics[width=0.32\textwidth]{WmixMin.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.48\textwidth]{WmixSp.pdf}} \end{centering} \caption{Normed minimizing weights $\frac{\hat\omega_j}{\sum_{k=1}^p\hat\omega_k}$ for models (CatR, top), (FunR, middle) and (MixR, bottom) in the minimal and sparse case, respectively. }\label{fig:Reweights} \end{figure} \begin{figure} \begin{centering} \subfigure{\includegraphics[width=0.4\textwidth]{MSEcatMin.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.4\textwidth]{MSEcatSp.pdf}} \\ \subfigure{\includegraphics[width=0.4\textwidth]{MSEfunMin.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.4\textwidth]{MSEfunSp.pdf}} \\ \hspace{1.8cm}\subfigure{\includegraphics[width=0.4\textwidth]{MSEmixMin.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.4\textwidth]{MSEmixSp.pdf}} \end{centering} \caption{Prediction results for models (CatR, top), (FunR, middle) and (MixR, bottom) in the minimal (left) and sparse (right) case with no restriction (`data driven weights'), restriction (i, `equal weights') and (ii, `oracle'), respectively. }\label{fig:Remse} \end{figure} \subsection{Classification Problems}\label{ClSim} \subsubsection{Set-up} Similar to the regression case, we generate data according to the models \begin{itemize} \item[(CatC)] For $i=1,\ldots,n$, the observations are generated with iid errors $\varepsilon_i\sim\mathcal{U}[0,1]$ as \[Y_i\begin{cases} = X_{i1}+\ldots,X_{iq}+1 & \text{if } \varepsilon_i \leq 0.7\\ \sim\mathcal{U}\{1,\ldots,G\} & \text{else}, \end{cases}\] with $X_{i1},\ldots,X_{ip}\sim${\it B}$(0.5)$, $q\leq p$; $\mathcal{U}$ stands for the (discrete) uniform distribution. We run the simulations with $G=5$. \item[(FunC)] The functional observations are based on those built in model (FunR), see Section \ref{ReSim}. Let's call them $X_{ij}^{\text{(Fun)}}$. Then the functional observations for this classification model are $X_{ij}(t)=X_{ij}^{\text{(Fun)}}(t)+c\cdot C_{ij}$ for some constant $c>0$ with $C_{ij}\sim\mathcal{U}\{0,1,2\}$, and the outcome is $Y_i=C_{i1}+\ldots+C_{iq}+1$, $q\leq p$. Thus we have $G=2q+1$ response classes in this scenario. We simulate this setup for different values of $c \in \{0.1,0.3,0.7\}$. In Figure \ref{fig:FunC} examples for the functional observations with different $c$ are shown to highlight the effect of the size of $c$. It can be seen that for $c=0.7$ and $q=1$ classes are distinctly separated, and the classification task could even be done manually/visually. In what follows, we will hence focus on $c=0.3$. \item[(MixC)] In this scenario we combine again functional and categorical predictors. For $i=1,\ldots,n$ we generate functional covariates $X_{i1},\ldots,X_{ip_{\text{fun}}}$ in the same manner as in scenario (FunR)/(FunC) and categorical covariates $X_{i(p_{\text{fun}}+1)},$ $\ldots,X_{i(p_{\text{fun}}+p_{\text{cat}})}\sim${\it B}$(0.5)$, such that $p_{\text{fun}}+p_{\text{cat}}=p$. As in scenario (FunC) we set $X_{ij}(t)=X_{ij}^{\text{(Fun)}}(t)+0.3\cdot C_{ij}$ for $j=1,\ldots,p_{\text{fun}}$, but here $C_{ij}\sim\mathcal{U}\{0,1\}$ . Then $$Y_i=(q_{\text{cat}}+1)\cdot(C_{i1}+\ldots+C_{iq_{\text{fun}}})+X_{i(p_{\text{fun}}+1)}+\ldots+X_{i(p_{\text{fun}}+q_{\text{cat}})}+1,$$ $q_{\text{fun}}\leq p_{\text{fun}}$, $q_{\text{cat}}\leq p_{\text{cat}}$, and thus $G=(q_{\text{fun}}+1)\cdot(q_{\text{cat}}+1)$ for this scenario. \end{itemize} As before we compare minimal (*.m) and sparse (*.s) cases in all scenarios, i.e., $q=1$, $p=2$ (*.m) and $q=3$, $p=18$ (*.s) for (CatC) and (FunC), and $q_{\text{fun}}=q_{\text{cat}}=1$, $p_{\text{fun}}=p_{\text{cat}}=2$ (*.m) and $q_{\text{fun}}=q_{\text{cat}}=2$, $p_{\text{fun}}=p_{\text{cat}}=8$ (*.s) for (MixC). The results are based on 500 replications. We use again the one-sided Picard kernel as described in Section \ref{ReSim}. \begin{figure} \begin{centering} \subfigure{\includegraphics[width=0.33\textwidth]{FunC01.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.33\textwidth]{FunC03.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.33\textwidth]{FunC07.pdf}} \end{centering} \caption{Examples for functional observations from model (FunC) for $c=0.1,0.3,0.7$ (from left to right). The green dashed lines represent $X_{ij}$ with $C_{ij}=2$, the blue solid lines those with $C_{ij}=1$ and the red dotted lines are realizations of $X_{ij}$ with $C_{ij}=0$. }\label{fig:FunC} \end{figure} In contrast to the regression case, however, we use a pre-estimator for the weights instead of a starting value for the bandwidth. Thus, we set \begin{eqnarray*} d_{\text{fun}}(X_{ij},x_j)&:=&\frac 1{c_j^\text{fun}}\sqrt{\int(X_{ij}(t)-x_j(t))^2dt},\\ d_{\text{cat}}(X_{ij},x_j)&:=&\frac 1{c_j^\text{cat}}I\{X_{ij}\neq x_j\}, \end{eqnarray*} with norming constants $c_j^\text{fun}=\sqrt{\int \frac1{n-1}\sum_{l=1}^n(X_{lj}(t)-\frac 1n\sum_{k=1}^nX_{kj}(t))^2dt}$, \\$c_j^\text{cat}=\sqrt{\frac1{n-1}\sum_{l=1}^n(X_{lj}-\frac 1n\sum_{k=1}^nX_{kj})^2}$, respectively, and determine the starting values $(\hat\omega_1^{\text{pre}},\ldots,\hat\omega_p^{\text{pre}})$ for minimizing $Q(\omega_1,\ldots,\omega_p) = \sum_{i=1}^n\sum_{g=1}^G (I\{Y_i=g\} - \hat{P}_{g(-i)})^2$ by \[\hat\omega_j^{\text{pre}}:=\arg\min_{\omega}\sum_{i=1}^n\sum_{g=1}^G (I\{Y_i=g\} - \hat P_{g(-i)}^{\text{pre}}(j,\omega))^2\] with \[\hat P_{g(-i)}^{\text{pre}}(j,\omega)=\frac{\sum_{s\neq i}I\{Y_s=g\}K\left(\omega d_\text{fun/cat}(X_{sj},X_{ij})\right)}{\sum_{s\neq i}K\left(\omega d_\text{fun/cat}(X_{sj},X_{ij})\right)}\] where $d_\text{fun/cat}$ means that $d_\text{fun}$ or $d_\text{cat}$ is used according to the type of the $j$th predictor. \subsubsection{Results}\label{ClRe} In Figure \ref{fig:Clweights} the minimizing normed weights for model (CatC), (FunC) (with $c=0.3$) and (MixC) for $n=100,500,1000$ are displayed. The performance regarding the variable selection is very encouraging. \begin{figure} \begin{centering} \subfigure{\includegraphics[width=0.28\textwidth]{WcatMinCl.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.52\textwidth]{WcatSpCl.pdf}} \\ \subfigure{\includegraphics[width=0.28\textwidth]{WfunMinCl.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.52\textwidth]{WfunSpCl.pdf}} \\ \hspace{1.8cm}\subfigure{\includegraphics[width=0.32\textwidth]{WmixMinCl.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.48\textwidth]{WmixSpCl.pdf}} \end{centering} \caption{Normed minimizing weights $\frac{\hat\omega_j}{\sum_{k=1}^p\hat\omega_k}$ for models (CatC, top), (FunC, middle) with $c=0.3$ and (MixC, bottom) in the minimal (left) and sparse (right) case, respectively. }\label{fig:Clweights} \end{figure} The prediction performance of our procedure is shown in Figure \ref{fig:Clmse}, where we display the squared error of $\hat P_g$ and compare it to the results under restriction (i) and (ii) as described in Section \ref{ReRe}. Additionally we compare the results to those of a random forest, as a benchmark apart from kernel-based, nonparametric prediction. After applying a functional principal component analysis (R package {\it refund} by \cite{Rrefund}) on the functional observations we build a random forest using the R function {\it randomForest} (\cite{RrandomForest}). For new ${\mathbf x}$-values that are generated in the same way as the observations from the training set, we predict the posterior probability with the random forest and with our $\hat P_g$ with the estimated weights, respectively. The data for the boxplots is calculated on test sets with $N=100$ (minimal case) and $N=1000$ (sparse case) as the Brier Score \[\frac 1N\sum_{l=1}^N\frac 1G\sum_{g=1}^G(\hat P_g({\mathbf x}_l)-I\{y({\mathbf x}_l)=g\})^2,\] where $y({\mathbf x})$ is the response (class) resulting from the predictor ${\mathbf x}$. In scenario (CatC) this is $y({\mathbf x})=x_1+\ldots+x_{q}+1$ and in (FunC) and (MixC) $y({\mathbf x})$ are built in the same way as for the training observations. Similar to the regression case, the results achieved with new ${\mathbf x}$-values for each replication and those with the same ${\mathbf x}$-values in all replications are comparable. We display the results with varying ${\mathbf x}$-values. It can be seen that the prediction works well and in almost all cases clearly better than the random forest. Further in the sparse cases, the results with data driven weights are much better than those with equal weights, which confirms the good variable selection/weighting performance. \begin{figure} \begin{centering} \subfigure{\includegraphics[width=0.4\textwidth]{MSEcatMinCl.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.4\textwidth]{MSEcatSpCl.pdf}} \\ \subfigure{\includegraphics[width=0.4\textwidth]{MSEfunMinCl.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.4\textwidth]{MSEfunSpCl.pdf}} \\ \hspace{1.8cm}\subfigure{\includegraphics[width=0.4\textwidth]{MSEmixMinCl.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.4\textwidth]{MSEmixSpCl.pdf}} \end{centering} \caption{Prediction results for models (CatC, top), (FunC, middle) with $c=0.3$, and (MixC, bottom) in the minimal (left) and sparse (right) case with no restriction (`data driven weights'), restriction (i, `equal weights') and (ii, `oracle'), and with a random forest, respectively. }\label{fig:Clmse} \end{figure} As additional information we display the missclassification rate as an arithmetic mean over \[\frac 1N\sum_{l=1}^NI\left\{\arg\max_{g\in\{1,\ldots,G\}}\hat P_g({\mathbf x}_l)\neq y({\mathbf x}_l)\right\}.\] The results are summed up in Table~\ref{tab:missCl}. They confirm and extend the good performance shown in Figure \ref{fig:Clmse}, especially that our procedure works much better than the random forest in most of the settings considered. For model (FunC) with different values of $c$, we see that classification becomes much easier with growing $c$ as expected. \begin{table} \begin{centering} \begin{tabular}{c|c||c|c|c|c} Model & $n$ & Data driven w. & Equal weights & Oracle & Random forest \\ \hline \hline \multirow{3}{*}{(CatC.m)} & 100 &{\color{blue} 0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} \\ & 500 &{\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} \\ &1000 &{\color{blue}0.00 (0.00)} &{\color{blue} 0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} \\ \hline \multirow{3}{*}{(CatC.s)} & 100 & {\color{red}0.09 (0.07)} & 0.50 (0.03) & {\color{blue}0.00 (0.02)} & 0.34 (0.06) \\ & 500 & {\color{blue}0.00 (0.00)} & 0.36 (0.02) & {\color{blue}0.00 (0.00)} & 0.05 (0.02)\\ &1000 & {\color{blue}0.00 (0.00)} & 0.30 (0.02) & {\color{blue}0.00 (0.00)} & 0.02 (0.01)\\ \hline \multirow{2}{*}{(FunC.m)} & 100 & {\color{blue}0.38 (0.05)} & 0.40 (0.05) & {\color{blue}0.38 (0.05)} & 0.50 (0.18) \\ & 500 & {\color{red}0.36 (0.04}) & 0.37 (0.04) & {\color{blue}0.35 (0.04)} & 0.44 (0.17) \\ $c=0.1$&1000 & {\color{blue}0.35 (0.04)} & 0.36 (0.05) & {\color{blue}0.35 (0.05)} & 0.42 (0.16)\\ \hline \multirow{2}{*}{(FunC.s)} & 100 & {\color{red}0.73 (0.02)} & 0.74 (0.02) & {\color{blue}0.69 (0.02)} & 0.75 (0.02) \\ & 500 & 0.73 (0.02) & 0.74 (0.02) & {\color{blue}0.69 (0.02)} & {\color{red}0.71 (0.02)} \\ $c=0.1$&1000 & {\color{red}0.65 (0.02)} & 0.70 (0.02) & {\color{blue}0.63 (0.02)} & 0.69 (0.02)\\ \hline \multirow{2}{*}{(FunC.m)} & 100 & {\color{blue}0.04 (0.02)} & 0.05 (0.02) & {\color{blue}0.04 (0.02)} & 0.28 (0.31) \\ & 500 & {\color{blue}0.03 (0.02)} & 0.04 (0.02) & {\color{blue}0.03 (0.02)} & 0.23 (0.30) \\ $c=0.3$&1000 & {\color{blue}0.03 (0.02)} & 0.04 (0.02) & {\color{blue}0.03 (0.02)} & 0.21 (0.28) \\ \hline \multirow{2}{*}{(FunC.s)} & 100 & {\color{red}0.31 (0.05)} & 0.69 (0.02) & {\color{blue}0.27 (0.03)} & 0.74 (0.03) \\ & 500 & {\color{red}0.31 (0.05)} & 0.69 (0.02) &{\color{blue} 0.27 (0.03)} & 0.65 (0.09) \\ $c=0.3$&1000 & {\color{red}0.14 (0.01)} & 0.60 (0.02) & {\color{blue}0.13 (0.01)} &0.58 (0.12) \\ \hline \multirow{2}{*}{(FunC.m)} & 100 & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & 0.29 (0.33)\\ & 500 & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & 0.26 (0.33) \\ $c=0.7$&1000 & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & {\color{blue}0.00 (0.00)} & 0.25 (0.32)\\ \hline \multirow{2}{*}{(FunC.s)} & 100 & {\color{red}0.08 (0.14)} & 0.68 (0.04) & {\color{blue}0.03 (0.03)} & 0.75 (0.05) \\ & 500 & {\color{blue}0.00 (0.00)} & 0.78 (0.18) & {\color{blue}0.00 (0.00)} & 0.67 (0.17) \\ $c=0.7$&1000 & {\color{blue}0.00 (0.00)} & 0.81 (0.19) & {\color{blue}0.00 (0.00)} & 0.55 (0.24) \\ \hline \multirow{3}{*}{(FunC.2.m)} & 100 & {\color{blue}0.46 (0.05)} & 0.57 (0.06) & {\color{blue}0.46 (0.05)} & 0.78 (0.12) \\ & 500 & {\color{blue}0.34 (0.05)} & 0.47 (0.05) & {\color{blue}0.34 (0.05)} & 0.77 (0.14)\\ &1000 & {\color{blue}0.30 (0.04)} & 0.43 (0.05) & {\color{blue}0.30 (0.04)} & 0.76 (0.15)\\ \hline \multirow{3}{*}{(FunC.2.s)} & 100 & {\color{red}0.74 (0.03)} & 0.77 (0.02) & {\color{blue}0.70 (0.02)} & 0.78 (0.03) \\ & 500 & {\color{red}0.62 (0.02)} & 0.72 (0.02) & {\color{blue}0.60 (0.02)} & 0.75 (0.03) \\ &1000 & {\color{red}0.58 (0.02)} & 0.71 (0.02) & {\color{blue}0.56 (0.02)} & 0.74 (0.05) \\ \hline \multirow{3}{*}{(MixC.m)} & 100 & {\color{red}0.04 (0.02)} & 0.06 (0.07) & {\color{blue}0.03 (0.02)} & 0.32 (0.43) \\ & 500 & {\color{blue}0.03 (0.02)} & {\color{blue}0.03 (0.03)} & {\color{blue}0.03 (0.02)} & 0.20 (0.37) \\ &1000 & {\color{blue}0.03 (0.01)} & {\color{blue}0.03 (0.02)} & {\color{blue}0.03 (0.01)} &0.18 (0.35) \\ \hline \multirow{3}{*}{(MixC.s)} & 100 & {\color{red}0.13 (0.03)} & 0.59 (0.02) & {\color{blue}0.10 (0.02)} & 0.63 (0.11) \\ & 500 & {\color{red}0.07 (0.01)} & 0.44 (0.02) & {\color{blue}0.06 (0.01)} & 0.21 (0.25) \\ &1000 & {\color{blue}0.06 (0.01)} & 0.39 (0.02) & {\color{blue}0.06 (0.01)} & 0.13 (0.24) \end{tabular} \caption{Missclassification rates as arithmetic mean (and standard deviation) with no restriction (``Data driven weights''), restriction (i) (``Equal weights''), restriction (ii) (``Oracle'') and with a random forest respectively. The values in blue are the lowest and the values in red the second to lowest in each row. }\label{tab:missCl} \end{centering} \end{table} To gain some further insight into the performance of our procedure in the classification of functional data, we simulate another model with a purely nonparametric concept of classification, that is \begin{itemize} \item[(FunC.2)] The functional observations are generated in exactly the same way as in model (FunR). The classification is then based on the maximizing argument of each functional observation following the set-up in \cite{FuchsGertheissTutz2015}. Let $j_{i,\text{max}}$ be the index such that \\$\max_tX_{ij_{i,\text{max}}}(t)=\max(\max_tX_{i1}(t),\ldots,\max_tX_{iq}(t))$, $q\leq p$. \\Then $Y_i=g\in\{1,\ldots,G\}$ if and only if $\arg\max_t X_{ij_{i,\text{max}}}(t)\in (\frac{gT-T}G,\frac{gT}G]$. \end{itemize} The results for this model are displayed in Figure~\ref{fig:ClfunMax} with $G=5$ and in Table~\ref{tab:missCl}. It can be seen that the prediction for this model is more difficult than for model (FunC) while the variable selection still works quite well. In comparison to the random forest, however, our procedure is still highly competitive. \begin{figure} \begin{centering} \subfigure{\includegraphics[width=0.28\textwidth]{WFunMinClmax.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.52\textwidth]{WFunSpClmax.pdf}}\\ \hspace{1.8cm}\subfigure{\includegraphics[width=0.4\textwidth]{MSEFunMinClmax.pdf}}\hspace{-0.02\textwidth} \subfigure{\includegraphics[width=0.4\textwidth]{MSEFunSpClmax.pdf}} \end{centering} \caption{Normed minimizing weights (top) and prediction resulte (bottom) for model (FunC.2) in the minimal (left) and sparse (right) case, respectively.}\label{fig:ClfunMax} \end{figure} \section{Application to real world data}\label{RealData} Finally, we apply our procedure to some real world data. The first one is the trajectory data from the virtual reality experiment already described in the Introduction. Further we consider the \emph{ArabicDigits} data as also mentioned in Section~\ref{introduction}. \subsection{Virtual reality movement data} The task is to predict/identify the class of the avatar (young vs.~elderly person) using the movement data. To allow for the multi-dimensional functional predictors (the trajectories), we set \[d(X_{ij},x_j)=\frac{1}{c_j}\sqrt{\sum_{r=1}^3\int(X_{ij}^{(r)}(t)-x_j^{(r)}(t))^2dt}\] where $X^{(r)}(t)$ describes the $r$-th component of $X(t)$ and \[c_j=\sqrt{\sum_{r=1}^3\int \frac1{n-1}\sum_{l=1}^n(X_{lj}^{(r)}(t)-\frac 1n\sum_{k=1}^nX_{kj}^{(r)}(t))^2dt}.\] \begin{figure} \begin{centering} \subfigure{\includegraphics[width=0.59\textwidth, height=0.3\textwidth]{WVR.pdf}} \subfigure{\includegraphics[width=0.39\textwidth,height=0.3\textwidth]{WVR6.pdf}} \end{centering} \caption{Estimated weights (normed) for the 9 (6) predictors (3 (2) body parts x 3 coordinate systems) in the VR data set with the original (left-hand side) and the trimmed (right-hand side) data. On the left-hand side, the first 3 weights belong to the head movements (global, local, orientational), the middle 3 weights to the left hand movements, and the last 3 weights to the right hand movements. On the right-hand side, the first/last 3 weights belong to the left and right hand movements (global, local, orientational), respectively.}\label{fig:VRweights} \end{figure} In total there is data from $n=72$ participants available and the movements are tracked with a frequency of 10 Hz, resulting in patterns consisting of $T=4970$ time points per coordinate. The data is available at \texttt{\small https://osf.io/h53rk/}. We estimate the weights with all available observations. The results are shown in Figure \ref{fig:VRweights}, left-hand side. It can be seen that the first two predictors (global and local position of the head) are weighted distinctly higher than the following 7 predictors. The reason for this effect, however, became clear after some closer inspection of the data as there is an artificial additive shift between groups for the local head data. Due to a coding error, the reference point for the local head data is different between groups. This shift is not apparent in the global head data and thus, since both components describe the same movements, their combination is a good predictor. Although this effect is only an artifact, we nevertheless present the results for the entire data set since they confirm the good performance of our procedure in terms of variable selection. The results when removing head positions, are displayed in Figure \ref{fig:VRweights}, right-hand side. Now, the weight for the global movement of the right hand is very high in comparison to the other weights. A potential interpretation/explanation is that due to the relatively small sample size further covariates, in addition to global right hand position, do not contribute substantial discriminatory information. In other words, the additional information that might be provided by further covariates is foiled by the so-called `curse of dimensionality' (compare, e.\,g., \cite{HasTibFri2009}). \subsection{Speech recognition} As an example for a multi-class classification with multiple functional predictors we consider the data set {\it ArabicDigits} from the R-package {\it mfds} by \cite{Rmfds}. This dataset contains time series of 13 Mel Frequency Cepstrum Coefficients (MFCCs) corresponding to spoken Arabic digits. MFCCs are very common for speech recognition, see \cite{KoolagudiRastogiRao2012} for a detailed explanation. Each time series in the 13 speech features contains 93 data points and the number of time series is 8800 (10 digits x 10 repetitions x 88 speakers) in total. We split the data in each group randomly in a training and a test set in the relation 70/30. Thus we estimate our weights based on $n=6160$ observations with $p=13$, $G=10$ and $T=93$. The results show that all 13 MFCCs are relevant as expected. The 13 normed weights are all of the same size around $1/13$, see Figure \ref{fig:ADweights}. Further the prediction results for the test data set (2640 observations) are almost perfect as can be seen in Table \ref{tab:ADres}. This very good prediction performance is comparable to results of other procedures applied on this data set. For instance, \cite{GoreckiLuczak2015} model the data as multivariate time series and use a 1NN classification where the distance measure is based on dynamic time warping. A (parametric) functional multivariate regression approach for multi-label classification is used by \cite{KrzyskoSmaga2017}. In \cite{MoellerGertheiss2018} a classification tree is applied. The authors choose arbitrarily two out of the 10 digits to make the problem a binary classification task. They all get very good prediction results for this data set as well. \begin{figure} \begin{centering} \includegraphics[width=\textwidth]{WAD.pdf} \caption{Estimated weights (normed) for the 13 MFCCs in the {\it ArabicDigits} data set.}\label{fig:ADweights} \end{centering} \end{figure} \begin{table} \begin{centering} \begin{tabular}{c|cccccccccc} & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 \\ \hline 0 & 261 &0 &0 &0 &0 &2 &1 &0 &0 &0\\ 1& 0& 264& 0& 0& 0& 0& 0& 0& 0& 0\\ 2 & 0& 0 &263& 0& 0& 0& 0& 0& 1& 0\\ 3 &0 & 0 & 0 &264 & 0 & 0 & 0& 0& 0& 0\\ 4 &0 & 0 &0 & 0 &264& 0& 0 &0 &0 &0\\ 5 &0 &0 &0 &1 & 0 &263 & 0 & 0& 0& 0\\ 6 &2 &0 &0 &0 &0 &0 &262& 0 &0 &0\\ 7 &0 &0 &0 &0 &0 &0 & 0 &261 &0& 3\\ 8 &0 &0 &0 &0 &0 &0 &0 &0 &264 &0\\ 9 &0 &0 &0 &0 &0 &0 &0 & 2 &0& 262 \end{tabular} \caption{Classification results for the {\it ArabicDigits} data set as a contingency table of the true (rows) and the estimated (columns) classes. }\label{tab:ADres} \end{centering} \end{table} \section{Concluding Remarks}\label{Conclude} We proposed a nonparametric method for classification and regression estimation where the covariates may be functional, categorical, or a mixture of both. We allowed for multiple predictors as well as multi-class classification. A key property of our method is its ability of variable/feature weighting, which can also be used for selection purposes. Although we focussed on functional and categorical predictors, our approach is also suitable for continuous, or continuous mixed with functional and/or categorical, covariates. Due to its universal structure our method works for all types of data that a distance measure can be applied on. In our extensive simulation study and the application to real world data we showed the good performance of our procedure both in terms of variable weighting/selection as well as estimation and prediction. \bibliographystyle{apa}
{'timestamp': '2021-11-08T02:02:46', 'yymm': '2111', 'arxiv_id': '2111.03115', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03115'}
arxiv
\section{Proof of Theorem \ref{thm:2vs3}} \begin{theorem}[Restatement of Theorem \ref{thm:2vs3}] There exists a distribution ${\cal D}_x$ for the $d$-dimensional input $x$, and a probability function $$p^*(x)= \sum_{i=1}^l u^*_i\sigma \left(\sum_{i=1}^l v^*_{i,j}\sigma(w_{i,j}^{*\top} x +b^*_{i,j})+c^*_i\right) $$ such that the following properties hold. \begin{itemize} \item There exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$ and $N\ge C\alpha^{1.5}d^2$ and let $l$ be an integer satisfying $l\le ce^{cd}$ for a universal constant $c$. There exists a choice of $\epsilon_i \in \{-1,1\}$ such that $p^*(x)$ has the folloiwng property. Let $f$ be any two-layer neural network, \text{i.e.} $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$$ then, $$\mathbb{E}_{x\sim {\cal D}_x}|f(x)-p^*(x)|^2\ge \tilde{c}^2/\alpha^2$$ for a universal constant $\tilde{c}$. \item However, if we use our method to build sets upon $\hat{h}$ satisfying learnablility assumption 4 for $$h^*=\sum_{j=1}^l v^*_{i,j}\sigma(w_{i,j}^{*\top} x +b^*_{i,j})$$ with $l \le 8c_\sigma/\delta \alpha^{1.5}Nd^3+2$, we can have for any $\hat{p}$ that is $\alpha_n$-multi-calibrated on $\{S^{(\hat{h})}_k\}$,such that $\forall \delta>0$, if sample size $n=\Omega(poly( d,l, N ,1/\delta))$, we have $$E_{x}|p^*(x)- \hat{p}(x)|^2\le \delta^2+\alpha_n^2.$$ \end{itemize} \end{theorem} \begin{proof} We argue by contradiction. Consider $\tilde{g}(x)$ defined in \cite{xx}. For the function $\tilde{g}$, it has the following properties: there exists a distribution ${\cal D}_x$, such that \begin{itemize} \item $\tilde{g}(x)\in [-1,1]$. \item There exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$ and let $l$ be an integer satisfying $l\le ce^{cd}$ for a universal constant $c$. Let $f$ be any two-layer neural network, \text{i.e.} $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$$ then, $$\mathbb{E}_{x\sim {\cal D}_x}|f(x)-\tilde{g}(x)|^2\ge \tilde{c}^2/\alpha^2$$ for a universal constant $\tilde{c}$. \item There exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$, there exists a three-layer neural network $g$, \textit{i.e.} $$g(x)= \sum_{i=1}^l u_i\sigma \left(\sum_{j=1}^l v_{i,j}\sigma(w_{i,j}^\top x +b_{i,j})+c_i\right )$$ with width at most $8c_\sigma C/\delta \alpha^{3}d^5+1$ for a universal constant $c_\sigma$ such that $$\mathbb{E}_{x\sim {\cal D}_x}|\tilde{g}(x)-g(x)|^2\le (\frac{\sqrt{3}}{\alpha d^{0.25}}+\delta)^2.$$ \end{itemize} Note that $\tilde{g}$ already is bounded in $[-1,1]$, thus we only need to prove that $\frac{1}{2}\tilde{g}+\frac{1}{2}$ shares the same properties as $\tilde{g}$, then we can take $$p^*=\frac{1}{2}\tilde{g}+\frac{1}{2}$$ since $\frac{1}{2}\tilde{g}+\frac{1}{2}\in [0,1]$. We first claim that for $p^*=\frac{1}{2}\tilde{g}+\frac{1}{2}$, there exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$ and let $l$ be an integer satisfying $l\le ce^{cd}$ for a universal constant $c$. Let $f$ be any two-layer neural network, \text{i.e.} $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$$ then, $$\mathbb{E}_{x\sim {\cal D}_x}|f(x)-p^*(x)|^2\ge \tilde{c}^2/\alpha^2$$ for a universal constant $\tilde{c}$. If not, for any $\varepsilon>0$, there exists a two-layer neural network $f_{\varepsilon}$ with $l\le ce^{cd}$, such that $$\mathbb{E}_{x\sim {\cal D}_x}|f_\varepsilon(x)-p^*(x)|^2\le \varepsilon^2.$$ Then, there must exist $f'_{\varepsilon}(x)$ with width at most $ce^{cd}+1$ such that $$\mathbb{E}_{x\sim {\cal D}_x}|f'_\varepsilon(x)-\tilde{g}(x)|^2\le 4\varepsilon^2,$$ since we can rescale the weights and bias and add at most one node to obtain $f'_\varepsilon(x)=2f_{\varepsilon}(x)-1$. Thus, for any $\varepsilon>0$, there exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$ and let $l$ be an integer satisfying $l\le 2ce^{2cd}$ for a universal constant $c$. there exists $f'_\varepsilon$, \text{i.e.} $$\mathbb{E}_{x\sim {\cal D}_x}|f'_\varepsilon(x)-\tilde{g}(x)|^2\le 4\varepsilon^2,$$ which contradicts. Secondly, notice we only need to add one extra node for the three-layer neural network and rescale the weights and bias so that there exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$, there exists a three-layer neural network $g'$, with width at most $8c_\sigma C/\delta \alpha^{3}d^5+2$ for a universal constant $c_\sigma$ such that $$\mathbb{E}_{x\sim {\cal D}_x}|\tilde{g}(x)-g'(x)|^2\le (\frac{\sqrt{3}}{\alpha d^{0.25}}+\delta)^2.$$ The proof is complete. \end{proof} \newpage \textbf{Old Proof} Let us briefly introduce the structure of neural networks we consider in this paper. We consider the input with dimension $d$. \begin{itemize} \item Two-layer neural network: $$x\mapsto \sum_{i=1}^l v_i\sigma(w_i^\top x +b_i)$$ where $v_i\in {\mathbb R}$ and $w_i \in {\mathbb R}^d$. \item Three-layer neural network: $$x\mapsto \sum_{i=1}^l u_i\sigma \left(\sum_{j=1}^l v_{i,j}\sigma(w_{i,j}^\top x +b_{i,j})+c_i\right )$$ \end{itemize} In this section, we only consider $\sigma$ is the ReLU function. \subsection{Notations} Let $B_d$ to be the $d-dimensional$ ball with radius $1$ and center $0$. Let $R_d$ to be $\sqrt{1/\pi}(\Gamma(d/2+1))^{1/d}$. Thus, $R_dB_d$ will have volume $1$. For function $f$, $g$, $\langle f,g\rangle_{L_2}=\int f(x)g(x)dx$ and $\langle f,g\rangle_{L_2(\mu)}=\int f(x)g(x)d\mu(x)$. The corresponding norm induced by the inner product are $\|\cdot\|_{L_2}$ and $\|\cdot\|_{L_2(\mu)}$ respectively. \paragraph{Fourier Transformation} For a function $f:{\mathbb R}^d\mapsto{\mathbb R}$, let us denote the fourier transformation to be $$\hat{f}(w)=\int _{{\mathbb R}^d}\exp(-2\pi i \langle w,x\rangle)f(x)dx.$$ \paragraph{Construction of Hard to Get Functions} To define the hard to approximate functions, we introduce some notations, Let $\alpha\ge 1$ and $\gamma$ be some large numerical constant to be determined later. Then, let $N=\gamma d^2$ and assumed to be an integer. Consider the intervals: $$\Delta_i=[(1+\frac{i-1}{N})\alpha\sqrt{d}, 1+\frac{i}{N})\alpha\sqrt{d}],~i=1,2,\cdots,N.$$ We say that interval $\Delta_i$ is good (or simply say $i$ is good) if for any $x\in \Delta_i$ $$J^2_{d/2}(2\pi R_dx)\ge \frac{1}{80\pi R_d x},$$ where $J$ is the Bessel function. Otherwise, we say $\Delta_i$ is bad. Then, we define $g_i$ such that $g_i(\|x\|)=1\{\|x\|\in\Delta_i\}$ if $i$ is good, and $g_i(x)=0$ if $i$ is bad. We further define $$\psi(x) = (R_d/\|x\|)^{d/2}J_{d/2}(2\pi R_d\|x\|).$$ In this section, we consider $x$ follows the probability measure $\mu$ with density function $\psi^2(x)$. \begin{lemma}\label{lm:1} Let $$\rho_i (x)=\frac{1+3\epsilon_i}{4}g_i(\|x\|) $$ where $\epsilon_i \in \{-1,1\}$. There is a choice of $\epsilon_i \in \{-1,1\}$, $i=1,\cdots,N$ such that $$\int_{{\mathbb R}^d\backslash(2R_dB_d)}[\widehat{(\sum_{i=1}^N \epsilon_i\rho_i\psi)}(w)]^2dw \ge c$$ where $c$ is a universal constant. \end{lemma} \begin{proof} Let us randomly choose $\epsilon_i$ from $\{-1,1\}$ indepedently. It suffices to show that $$\mathbb{E} \int_{{\mathbb R}^d\backslash(2R_dB_d)}[\widehat{(\sum_{i=1}^N \epsilon_i\rho_i\psi)}(w)]^2dw \ge c$$ where $c$ is a universal constant. \begin{align*} \mathbb{E} \int_{{\mathbb R}^d\backslash(2R_dB_d)}[\widehat{(\sum_{i=1}^N \epsilon_i\rho_i\psi)}(w)]^2dw &=\frac{1}{16}\mathbb{E} \int_{{\mathbb R}^d\backslash(2R_dB_d)}[\widehat{(\sum_{i=1}^N \epsilon_ig_i\psi)}(w)]^2dw\\ &+\frac{3}{8}\mathbb{E} \int_{{\mathbb R}^d\backslash(2R_dB_d)}[\widehat{(\sum_{i=1}^N \epsilon_ig_i\psi)}(w)](\sum_{i=1}^N\widehat{g_i\psi}(w))dw\\ &+\frac{9}{16}\mathbb{E} \int_{{\mathbb R}^d\backslash(2R_dB_d)}[\sum_{i=1}^N\widehat{g_i\psi}(w)]^2dw \end{align*} The second term is $0$ and the last term is positive, the first term is lower bounded by some universal $c$ by Lemma 8 in \cite{xx}. The proof is complete. \end{proof} Next, we provide a lemma to show that the linear combination $\epsilon_i\rho_i$ has a non-negligible mass under $L_2$ distance and density function $\psi^2(x)$. \begin{lemma}\label{lm:2} Suppose $\alpha\ge c$, $N\ge c(\alpha d)^{3/2}$ for some sufficiently large universal constant $c$, then for every choice of $\epsilon_i\in\{-1,1\}$, $i=1,2,\cdots, N$, one has $$\int\Big(\sum_{i=1}^N\epsilon_i\rho_i(x)\Big)^2\psi^2(x)dx\ge \frac{0.00075}{\alpha}.$$ \end{lemma} \begin{proof} Since $g_i$ has disjoint support for different $i$, we have \begin{align*} \int\Big(\sum_{i=1}^N\epsilon_i\rho_i(x)\Big)^2\psi^2(x)dx&=\int\Big(\sum_{i=1}^N\frac{\epsilon_i+3}{4} g_i(\|x\|)\Big)^2\psi^2(x)dx\\ &=\sum_{i=1}^N\int\Big(\frac{\epsilon_i+3}{4} g_i(\|x\|)\Big)^2\psi^2(x)dx\\ &\ge \sum_{i=1}^N\frac{1}{4}\int\Big( g_i(\|x\|)\Big)^2\psi^2(x)dx. \end{align*} Then, by Lemma 6 in \cite{xx}, we have $$\sum_{i=1}^N\frac{1}{4}\int\Big( g_i(\|x\|)\Big)^2\psi^2(x)dx\ge \frac{1}{4}\frac{0.003}{\alpha}=\frac{0.00075}{\alpha}.$$ \end{proof} \paragraph{Inapproximability of the two-layer neural networks.} We consider the probability function: $$p^*(x)=\sum_i \epsilon_ig_i(\|x\|)$$ where $\{\epsilon_i\}_i$ are the signs provided by Lemma \ref{lm:1}. \begin{theorem} There exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$ and $N\ge C\alpha^{1.5}d^2$ and let $l$ be an integer satisfying $l\le ce^{cd}$ for a universal constant $c$. There exists a choice of $\epsilon_i \in \{-1,1\}$ such that $p^*(x)$ has the folloiwng property. Let $f$ be any two-layer neural network, \text{i.e.} $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$$ then, $$\|f-p^*\|_{L_2(\mu)}\ge \tilde{c}/\alpha$$ for a universal constant $\tilde{c}$. \end{theorem} \begin{proof} According to Lemma \ref{lm:2}, we know that $$\|p^*\|_{L_2(\mu)}\ge \frac{c_1}{\alpha},$$ where $\|\cdot\|_{L_2(\mu)}$ is the $L_2$ norm under probability measure $\mu$ and $c_1$ is a universal constant $c_1>0$. Note that the function $|p^*(x)|\le 1 $ for any $x$, and define $w=\widehat{p^*\psi}/\|p^*\psi\|_{L_2}$. \begin{align*} \int_{2R_dB_d}w(x)^2dx&=1-\frac{\int_{2R_dB_d}\widehat{p^*\psi}(x)^2dx}{\|p^*\psi\|^2_{L_2}}\\ &\le 1-\frac{\int_{2R_dB_d}\widehat{p^*\psi}(x)^2dx}{\|\psi\|^2_{L_2}}\\ &\le 1-c_2 \end{align*} for a universal constant $c_2>0$ and the first inequality is due to $|p^*(x)|\le 1$ for all $x$ and the second one is due to Lemma \ref{lm:1}. Next, for any two-layer neural network $f$, \textit{i.e.} $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$$ we define $q=\widehat{f\psi}/\|f\psi\|_{L_2}$. By Claim $2$ and Lemma $9$ in \cite{xx}, we have $$\langle q,w\rangle_{L_2}\le 1-c_2/2+l\exp(-c_3d)$$ for a universal constant $c_3>0$. Besides, given $\|q\|_{L_2}=\|w\|_{L_2}=1$, by Proposition $1$ in \cite{xx}, we have for every scalars $\beta_1,\beta_2>0$ that $$\|\beta_1 q - \beta_2 w\|_{L_2}\ge \frac{\beta_2}{2}\|q-w\|_{L_2}.$$ As a result, \begin{align*} \|f-p^*\|_{L_2(\mu)}&=\|f\psi-p^*\psi\|_{L_2}=\|\|f\psi\|_{L_2}q(\cdot)-\|p^*\psi\|_{L_2}w(\cdot)\|_{L_2}\\ &\ge \frac{1}{2}\|q-w\|_{L_2}\|p^*\|_{L_2(\mu)}\\ &\ge \frac{1}{2}\sqrt{2(1-\langle q,w \rangle_{L_2} )} \frac{c_1}{\alpha}\\ &\ge \frac{c_1}{2\alpha} \sqrt{2\max (c_2/2-l\exp(-c_3d),0)}\ge \frac{c_1\sqrt{c_2}}{4\alpha}. \end{align*} The last inequality follows if we take $c=\min\{c_2/4,c_3\}$. \end{proof} \paragraph{Approximability of the three-layer neural networks.} \begin{theorem} There exists a universal constant $C>0$ such that the following holds. Let $\delta\in(0,1)$. Suppose that $d\ge C$ and for any choice of $\epsilon\in\{-1,1\}$, $i=1,\cdots, N$ there exists a three-layer neural network $$g= \sum_{i=1}^l u_i\sigma \left(\sum_{i=1}^l v_{i,j}\sigma(w_{i,j}^\top x +b_{i,j})+c_i\right )$$ with $l \le 8c_\sigma/\delta \alpha^{1.5}Nd^3+2$ for some universal constant $c_\sigma$, such that $$\|g(x)-\sum_{i=1}^N \epsilon_i\rho_i(\|x\|)\|_{L_2(\mu)}\le \frac{\sqrt{3}}{\alpha d^{0.25}}+\delta.$$ Moreover, $g$ is $L$-Lipchisz constant, where $L=O(poly(d,N,1/\delta))$. \end{theorem} \begin{proof} Note that $\sum_{i=1}^N \epsilon_i\rho_i(\|x\|)$ is just a linear transformation of $ \sum_{i=1}^N \epsilon_ig_i(\|x\|)$, we at most need add one more note to approximate $\sum_{i=1}^N \epsilon_i\rho_i(\|x\|)$. Other part follows exactly the same as Proposition $2$ in \cite{xx}. \end{proof} \section{Conclusions and Future Directions} This work presents a proof of concept that multi-calibration can be carried out efficiently {\em and} simultaneously approximate $p^*$, through the lens of representation learning, and suggests several directions for future research. We briefly discuss two. In our work, we theoretically analyze the feasibility of using the first layer of a neural network as the representation. We expect that more intermediate layers can provide even better representations. Analyzing intermediate layers of neural networks is a general challenge in neural network theory; our results provide added motivation for this field of study. We have also provided two representation learning methods that fit a smaller (low-complexity) model to obtain a low-dimensional representation function. An interesting direction would be to consider other explicit dimensional reduction methods, for example, PCA and autoencoders. \section{Experimental Support} To provide further support for the methods presented in Sections~\ref{sec:main_results} and~\ref{sec: learning h}, we present two numerical experiments. We define a mapping $p^*(x)$ from instances in the data universe to probabilities, and for each sample $x \in D$ in the dataset, we generate the outcome $y$ such that $y \sim \mathrm{Bern}(p^*(x))$. Dividing the resulting dataset into a training and test set, we train a fully connected neural network on the training pairs $\{(x, y)\}$. Given access to both the $p^*$ and labels $y$ for each $x$, we can check for proximity to truth by computing the mean squared error (MSE) between the predictions of the fully connected network and the underlying $p^*$ used to generate the Boolean labels. This is unlike the traditional setting, in which one only has the Boolean outcomes $y$ without access to the underlying probability distributions from which the outcomes are drawn. In more detail, we consider the MNIST dataset of 50,000 training images and 10,000 test images of handwritten digits labeled 0 through 9. We define $p^*(x) = \frac{\#}{10}$; for example, an image $x$ of the digit 1 will have $p^*(x)=10\%$ and an image $x$ of the digit 9 will have $p^*(x)=90\%$. Motivated by Theorems \ref{thm:ReLU:rep} and \ref{thm:sigmoid:rep} in Section~\ref{sec: learning h}, we define $\hat h(x)$ to be the first $k-2$ layers of a $k$-layer a fully connected neural network. The network is trained on the Boolean outcomes defined by draws from $p^*(x)$ as described above. We expect that such an $\hat h(x)$ will learn a useful representation of the underlying data and that generating scaffolding{} sets with this $\hat h(x)$ via Algorithm~\ref{alg:set} and multi-calibrating with respect to them as in Algorithm~\ref{alg:full} offers a performance benefit over the network itself. In this setting, the goals of our two experiments are as follows: \textit{Demonstrating Learnability:} We validate the Learnabilty Assumption (Remark~\ref{rem:learnability}) for the $\hat h$ described above. By training a neural network on the Boolean outcomes first, freezing the first $k - 2$ layers of the network, and then further training the remaining $2$ layers using the true $p^*$ values, we obtain a small suffix network $g$ such that $p^*(\cdot) \approx g({\hat h}(\cdot))$. This demonstrates that the learned $\hat h(x)$ representation is sufficiently informative to be used as an input into a small neural network that can closely approximate the true $p^*(x)$ values. This justifies using $\hat h(x)$ as the input to the scaffolding{} set algorithm in the next experiment. \textit{Demonstrating the Benefit of our Approach:} We demonstrate a case in which the multi-calibrating with respect to the scaffolding{} sets found by Algorithm~\ref{alg:set} offers a benefit over a (traditionally) trained neural network. Training the network on the Boolean outcomes alone, removing the last two layers of the network, and then setting $\hat h(x) = h(x)$ and applying Algorithm~\ref{alg:full}, we show that multi-calibrating with respect to the resulting collection of scaffolding{} sets offers a material benefit over using the original neural network itself in terms of closeness to the true underlying $p^*(x)$. \subsection{Demonstrating Learnability} In addition to the motivation provided by Theorems~\ref{thm:sigmoid:rep} and \ref{thm:ReLU:rep} in Section~\ref{sec: learning h}, we provide experimental justification for Assumption~\ref{assumption on h}. Recall that Assumption~\ref{assumption on h} requires that there exist some $w_{new}$ which, when composed with $h$, gives an estimator $p$ that is close to $p^*$. Then, so long as we can find a $\hat h$ that is close to $h$, we can use Algorithm~\ref{alg:set} to construct the scaffolding{} sets. In this experiment, we show that we can find a $p = w_{new}\circ h$ that is close to $p^*$ and motivate taking $\hat h = h$. Recall that in our experimental setup, for an image $x$ of the digit $i$ we define $p^*(x)$ to be $i/10$, and for an image $x$ of digit $i$ in the training data the label $y$ is drawn from $Bern(p^*(x)) = Bern(i/10)$. First, we train a fully connected network with the Boolean labels. We partition this network into $w$ and $h$, where $w$ is the last two layers, including the output layer, and $h$ is the remainder. We then show that, by freezing the layers in $h$ and training a new $w_{new}$ on the $p^*$ values directly, the model achieves a low mean squared error with respect to the underlying $p^*$ values. That is, we find that $w_{new} \circ h(x)$ is close to $p^*$. Since $w_{new}$ is narrow and shallow and therefore cannot alone perform the task of getting $w_{new} \circ h(x)$ close to $p^*(x)$, we find that $h(x)$ describes a reasonable representation of the input. Since $h$ was only trained on Boolean data, we can simply take $\hat h = h$ and run the scaffolding{} algorithm with confidence in Assumption~\ref{assumption on h}. Specifically, we train a 6 layer fully connected neural network with widths 784, 512, 512, 256, 256, and 2 in the layers. The first two layers use a ReLU activation function while the remainder use the Sigmoid function. The network is trained for 75 epochs using stochastic gradient descent with an initial learning rate of 0.01, which decays by a factor of 10 at epochs 40 and 70. After the network is trained, $w$ is frozen and $w_{new}$ is trained for 50 epochs with a learning rate of 0.09 using $p^*$ values, as described above. Each point in Figure~\ref{fig:expt1} is the result of averaging over 10 model instances. The plot demonstrates the convergence of $p_{new} = w_{new} \circ h$ to $p^*$ and, therefore, the validity of choosing $\hat h = h$ in Algorithm~\ref{alg:set}. \begin{figure}[H] \includegraphics[width=0.35\textwidth]{Expt2.png} \centering \caption{\fontsize{10pt}{12}\selectfont (Blue) Model performance on the test set as measured by the prediction MSE with $p^*(x)$. The model is trained on Boolean data only during this phase. (Orange) Model performance on the test set as measured by the prediction MSE with $p^*(x)$. The model is trained on the true probability labels in this phase, but only the final two layers of the network may be updated. The substantial drop in MSE during the second phase of training demonstrates the shortcomings of neural networks alone in estimating $p^*$, as well as the utility of the $h(x)$ representation trained in the previous phase for extracting features relevant for modeling $p^*(x)$. Each point shown is averaged over 10 trials.} \label{fig:expt1} \end{figure} \subsection{Demonstrating the Benefit of Our Approach} After training the neural network (denoted by $\hat p_{NN}$), we extract the output of the second to last layer, with 4 neurons, providing us with a four-dimensional representation $\hat h(x)$ for each training sample. For a given $B$, we then apply Algorithm~\ref{alg:set} to $\hat h(x)$ to partition the training data into $B^4$ sectors and compute $\hat p(x) = \frac{1}{|S_{G(x)}|} \sum_{X_i \in S_{G(x)}} Y_i$ with partitioning scheme $G(x)$. Using this $\hat p(x)$ on the test data, we can compute the MSE with respect to the true $p^*$ values and compare it to the MSE of the direct output of the fully connected network ($\hat p_{NN}$) with respect to $p^*$ to determine whether Algorithm~\ref{alg:full} gets closer to the truth than using the neural network directly. The results for $B \in \{1, ..., 9\}$ are shown in Figure \ref{fig:expt2}, demonstrating that for $B$ between 2 and 6, Algorithm~\ref{alg:full} outperforms the fully connected network in mean squared error with $p^*$. For larger values of $B$, the algorithm begins to overfit (note that $B = 9$ corresponds to $6561$ partitions, or an expected $7.6$ training samples per partition). Figure~\ref{fig:expt2}, combined with the results of Experiment 2, demonstrates that the fully connected network has indeed learned a useful representation of the underlying data, however, guaranteeing that the algorithm is multi-calibrated with respect to the scaffolding{} sets obtained by Algorithm~\ref{alg:set} can offer an improvement over an standard neural network. \begin{figure}[H] \includegraphics[width=0.35\textwidth]{expt1a.png} \includegraphics[width=0.31\textwidth]{expt1b.png} \centering \caption{\fontsize{10pt}{12}\selectfont (Left) Training history of the model in Experiment 2. The training cross entropy loss, between the Boolean outcomes and the model predictions, is shown in red while the test MSE, between the true $p^*(x)$ values and the model predictions, is shown in blue. (Right) Accuracy benefit of Algorithm~\ref{alg:full} over a standard neural network. For $B \in \{2, \dots, 7\}$, Algorithm~\ref{alg:full} outperforms the fully connected network. In both plots, each point shown is averaged over 10 trials.} \label{fig:expt2} \end{figure} We further show that our results are robust to perturbations in the network architecture. Starting from a 5 layer ``base'' architecture with layers containing 784, 512, 512, 256, and 4 neurons respectively, we show that adding 1, 2, 3, or 20 extra layers with 256 neurons each to the network (in the final case doubling the network size), Algorithm~\ref{alg:full} offers similar test mean squared error. Each network is trained for 100 epochs using SGD with an initial learning rate of 0.1, decaying by a factor of $\frac{1}{\sqrt{10}}$ every 10 epochs between epochs 20 and 70 inclusive. The network with 20 additional layers is trained with Adam and an initial learning of $1\times10^{-4}$. The results are shown in Figure~\ref{fig:expt3} and demonstrates that Algorithm~\ref{alg:full} performs similarly for each of these choices of $\hat h$. \begin{figure}[H] \includegraphics[width=0.35\textwidth]{expt3.png} \centering \caption{\fontsize{10pt}{12}\selectfont The impact of changes to neural network architecture on the performance of Algorithm~\ref{alg:full}. Five fully connected networks (FCNs) of each architecture are trained to generate five $\hat h(x)$ functions, each of which is used as an input to Algorithm~\ref{alg:full}. The average test set performance of each is shown for varying choices of $B$ is shown in the figure above while the solid horizontal line denotes the average performance of the original neural networks themselves on the test set data. Here, we define the test set as the ground truth $p^*(x)$ values. The labels ``FCN+x'' refer to the architecture of the first FCN with the addition of $x$ additional dense layers.} \label{fig:expt3} \end{figure} \section{Introduction} \label{sec:intro} Prediction algorithms ``score" individual instances, mapping them to numbers in $[0,1]$ that are popularly understood as ``probabilities'' or ``likelihoods'': the probability of success in the job, the likelihood that the loan will be repaid on schedule, the chance of recidivism within 2 years. Setting aside for a moment the pressing question of the {\em meaning} of a probability for a non-repeatable event, these scores have life-altering consequences, and there is great concern that they be {\em fair}. One approach to defining fairness is through {\em calibration}: a predictor $p$ is calibrated on a set $S$ for a distribution ${\cal D}$ on (instance, Boolean label) pairs $(x,y)$, if ${\mathbb{E}}_{(x,y) \sim {\cal D}} [y~|~p(x)=v, x\in S] = v$. Calibration as an accuracy condition (in the online setting) has a long intellectual history~\cite{Dawid1982,FosterVohra,G3}; calibration as a fairness criterion was introduced by Kleinberg, Mullinathan, and Raghavan~\cite{KPR}, who required calibration simultaneously on disjoint demographic groups. The intuition expressed in that work is compelling: a score of $v$ ``means the same thing'' independent of the demographic group of the individual being scored. It is well known that calibration is a poor measure of accuracy; for example, as Fienberg and DeGroot (and, as they note, others before them) point out~\cite{degroot1983comparison}, in the online setting calibration can be a {\em disincentive} for accurate forecasting, and Sandroni showed more generally that, if a quality test is known in advance, a charlatan who is unable to predict can nevertheless pass the quality test (calibration is a special case of a quality test)~\cite{Sandroni}. Nonetheless, in a seminal work, H\'ebert-Johnson, Kim, Reingold, and Rothblum take an exceptional step in the direction of accuracy through {\em multi-calibration} with respect to a (possibly large) collection $\mathcal S$ of arbitrarily intersecting large sets~\cite{HKRR}. Here the requirement is that the predictor be (approximately) calibrated simultaneously on all sets $S \in \mathcal S$. The authors demonstrate a batch method for creating a ``small'' multi-calibrated predictor from relatively few training observations. At a very high level, the algorithm begins with an arbitrary candidate predictor $p$ and makes a series of ``adjustments'' when a pair $(S,v)$ is found, for $S \in \mathcal S$ and $v \in [0,1]$, such that $p$ is not calibrated (as estimated on the training data) on $S_v =\{x | x \in S,~p(x)=v\}$ and $S_v$ is of sufficiently large weight according to the underlying distribution ${\cal D}$. By means of a potential function argument, the authors show that every adjustment brings the modified predictor substantially closer (in $\ell_2$ norm) to the ``truth,'' with the size of advance tied to the quality of the approximation to calibration. Since the value of the potential function is bounded {\it a priori}, it follows that not too many adjustments are required before ``truth'' is well-approximated. Multi-calibrated algorithms have performed well in medical settings~\cite{barda2020developing, barda2021addressing}. Nevertheless, reaching ``truth'' is not the expected outcome; for example, the representation of individuals to the algorithm might be missing key features necessary for computing the probability of a positive outcome, or the collection of sets~$\mathcal S$ only contains sets that are orthogonal to the probability of positive outcome, in which case the predictor that reports the population average is multi-calibrated with respect to~$\mathcal S$. \cite{dwork2021outcome} views the design goal of a predictor through the lens of indistinguishability: multi-calibrated predictors provide a generative model of the real world whose outcomes are ``indistinguishable,'' to a collection of distinguishers intimately tied to the sets in~$\mathcal S$, from those seen in the real world. This is not the same as producing ``true'' probabilities of positive outcomes, even if we had a solution to the philosophical problem of how to define such probabilities for non-repeatable events. The power, and the computational complexity, of multi-calibration comes from choosing a rich collection $\mathcal S$. Suppose, for example, that $\mathcal S$ contains all sets recognizable by circuits of size, say, $n^2$. Consider a demographic group that is so compromised by a history of subordination that individuals in this group accept their mistreatment as ``justified''~\cite{Banaji}. If membership in this group can be recognized by a circuit of size $n^2$ then multi-calibration with respect to $\mathcal S$ immediately ensures calibration on this demographic group, without requiring members of the group to (know to) advocate for the group. At the same time, however, the set of all circuits of size $n^2$ is very large, and the step, in the algorithm of~\cite{HKRR}, of finding a (slice of a) set to trigger an adjustment could potentially require exhaustive search of $\mathcal S$; (\cite{HKRR} shows that learning a predictor that is multi-calibrated with respect to $\mathcal S$ is as hard as weak agnostic learning for $\mathcal S$; see~\cite{gerrymandering} for a related result). These dueling considerations -- power and complexity -- together with the fact that a perfectly accurate predictor is calibrated on all sets, motivate us to consider the following question: {\em Can we find a small collection of sets $\mathcal S$, such that multi-calibrating on $\mathcal S$ guarantees accuracy?} We call this the {\em Scaffolding{} Set Construction} problem, and our principal contribution is {a proof of concept: a scaffolding{} set construction algorithm that works under a variety of assumptions common in the machine learning literature.} Suppose there exists a ground truth $p^*$ mapping instances $x$ (say, students) to true probabilities $p^*(x)$ (say, of graduating within 4 years). Fix an arbitrary grid on the interval $[0,1]$, specifically, multiples of some small $\gamma$, {\it e.g.}, $\gamma = 0.01$, and assume for simplicity that for all $x$, $p^*(x)$ is a multiple of $\gamma$. Our starting point is the observation that {\em if the collection $\mathcal S$ contains the level sets of $p^*$ (possibly among other sets), then multi-calibration with respect to $\mathcal S$ ensures closeness to~$p^*$}. \paragraph{Our Contributions.} Speaking informally, our goal is to find a small collection of sets with the property that multi-calibration with respect to this small collection ensures accuracy (closeness to $p^*$). By virtue of this smallness, multi-calibration with respect to this collection can be carried out in polynomial time using the algorithm in~\cite{HKRR} or any other multi-calibration algorithm that is efficient in the number of sets, giving rise to a natural 2-step ``Meta-Algorithm" (Algorithm~\ref{alg:full}). Throughout this work We assume individuals are presented to the algorithm(s) as elements of $\mathbb{R}^d$ for some $d>0$\footnote{There is a difference between the instance (say, student) and the representation of the instance to the algorithm (say, transcript, test scores, and list of extra-curricular activities). We have in mind the situation in which the representation is rich, so distinct instances result in distinct representations to the algorithm, but our results hold in the general case.}. \begin{enumerate} \item We formalize the problem of learning {\em scaffolding{} sets} as, roughly speaking, the generation of a polynomial-sized collection ${\cal S}$ of sets that contains the (approximate) level sets of $p^*$ (the truth is more nuanced, but this description suffices for building intuition). A {\em scaffolding{} set} algorithm, when run on a data representation mapping $\hat h: \mathbb{R}^d \rightarrow \mathbb{R}^r$, $r < d$ (more on this below) and $d$-dimensional training data labeled with Boolean outcomes, is said to {\em succeed} if it outputs a small collection of sets ${\cal S}$ that indeed contains the (approximate) level sets of $p^*$. \item We provide an algorithm for the Scaffolding{} Set problem and give sufficient conditions on the representation mapping for the algorithm's success. The Scaffolding{} Set Construction algorithm (Algorithm~\ref{alg:set}) takes a (typically low-dimensional) representation mapping as input, without regard to how this mapping was obtained. The algorithm does not require that $p^*$ be expressible by the class of architectures that can express the representation (Section~\ref{set construction}). Our approach is motivated by the folk wisdom that, in a classification task, the initial layers of a neural network extract a useful data representation for the task at hand, while the final layers of the network are responsible for assigning ``probabilities" to those representations. {Under the above-mentioned sufficient conditions, we prove asymptotic convergence of our method: as the number of samples approaches infinity the calibration error goes to~$0$; moreover, under the same conditions, we present a multi-calibration method that, when used in the multi-calibration step of the Meta-Algorithm, yields a nearly minimax rate-optimal predictor (Section~\ref{sec:accuracy}).} \item \label{contribution:find rep} We provide methods for finding a suitable representation that applies to a wide class of data generation models $\mathbb{E}[Y|X]=p^*(x)$ (Section~\ref{sec: learning h}), including a $k$-layer neural network model. We further obtain results for the transfer learning setting, where, in addition to the sample from the target task, we also have abundant samples from source tasks. \item If, using our techniques, we can learn a collection $\mathcal S$ of scaffolding{} sets such that multi-calibration with respect to $\mathcal S$ yields a good approximation to $p^*$, then perhaps we can directly learn $p^*$, and not bother with all this machinery. In other words, do the techniques developed in this work actually buy us anything? In short, the answer is yes. We give an example of a (non-contrived) data generation model for which, by using a neural net of a given architecture, together with training data, we can solve the scaffolding{} set problem for $p^*$ even though $p^*$ itself cannot be computed by a neural net of this architecture (Section~\ref{sec: benefit}). The representation mapping is found using the method of Contribution~\ref{contribution:find rep} above. \item {\bf Experiments.} Using synthetic data drawn from a known distribution on $p^*$, we show experimentally that multi-calibrating with respect to the collection of sets obtained by our Scaffolding{} Set Construction algorithm trained with Boolean labels drawn according to $p^*$ gets closer to the truth than training a neural network on the same data. \end{enumerate} Suppose we have a specific and moderately-sized collection $\mathcal C$ of sets for which we wish to ensure calibration; for example, these may be specific demographic groups. Recall that we can not know when the Scaffolding{} Set algorithm produces level sets. When it does, multi-calibration produces a predictor that is close to $p^*$ (Theorem~\ref{thm:mc wrt S}), which (most likely) gives calibration with respect to $\mathcal C$. Since we cannot be certain of success, we can still explicitly calibrate with respect to $\mathcal C$ using the algorithm of~\cite{HKRR} as a ``post-processing" step; \cite{HKRR} argues that such post-processing does not harm accuracy. {We remark that, while it is generally impossible to ensure or detect success of any scaffolding{} set algorithm, given any collection ${\cal G}$ of (arbitrarily intersecting) demographic groups we can ensure multi-calibration for $\mathcal G$ by, for example, setting ${\cal C} = {\cal G} \cup {\cal S}$ and using the algorithm in~\cite{HKRR} to multi-calibrate with respect to~${\cal C}$. If the scaffolding{} set construction was successful, then in addition to being multi-calibrated with respect to $\mathcal G$ the predictor will also be accurate. } \subsection{Additional Related Work} The formal study of algorithmic fairness was initiated by Dwork {\it et al.} in~\cite{FtA} in the context of classification. \cite{FtA} emphasized {\em individual}, rather than {\em group} fairness, requiring that individuals who are similar, under some task-specific notion of similarity, receive similar distributions on classifications, and pointed to flaws of group fairness guarantees as solution concepts. \cite{FtA} further provided an algorithm for ensuring fair classification, given a similarity metric; nearly a decade later, Ilvento took a major step toward learning a metric from an expert~\cite{Ilvento}; \cite{jung2019eliciting} elicits this kind of information from a group of stakeholders. In the intervening years most (but not all) theoretical research focused on group fairness criteria. Two independent works suggested multi-group criteria as an approach to bridging group vs individual fairness~\cite{gerrymandering,HKRR}. In particular, H\'ebert-Johnson {\it et al.}\,introduced the method for constructing efficient multi-calibrated predictors in the batch setting~\cite{HKRR}. Multi-calibration in the online setting is implicit in~\cite{G3}, \cite{momentmulticalibration} extends the notion of multi-calibration to higher moments and provides constructions, and~\cite{online} provides an efficient online solution. Multi-calibration has also been applied to solve several flavors of problems: fair ranking~\cite{ranking}; {\em ommiprediction}, which is roughly learning a predictor that, for a given class of loss functions, can be post-processed to minimize loss for any function in the class~\cite{omnipredictors}; and providing an alternative to propensity scoring for the purposes of generalization to future populations~\cite{propensity}. Calibration, as a measure of predictive uncertainty quantification, is a well-studied concept in statistics and econometrics, see \cite{dawid1982well, foster1997calibrated, sandroni2003calibration,foygel2021limits} and the reference therein. Recently, it was found that although modern machine learning methods, such as neural networks, made significant progress with respect to the predictive accuracy in a variety of learning tasks \cite{simonyan2014very,srivastava2015highway,he2016deep}, their predictive uncertainties are poorly calibrated \cite{guo2017calibration}. To mitigate this issue, several recalibration methods and their variants have been proposed, including scaling approaches \cite{platt1999probabilistic, zadrozny2002transforming,guo2017calibration}, binning approaches \cite{zadrozny2001obtaining,naeini2014binary,gupta2021top}, scaling-binning \cite{kumar2019verified}, and data augmentation \cite{thulasidasan2019mixup, zhang2021and}. Recent work has begun to develop the theoretical analysis of these methods. For example, \cite{gupta2021distribution} draws the connection between calibration and conformal prediction; \cite{gupta2021distributionfree} avoids sample splitting in the binning method; and \cite{zhao2021calibrating} analyzes multi-class calibration from the decision making perspective. The folklore that intermediate layers of neural net serve as a (low-dimensional) representation \cite{bengio2013representation} has been recently studied, eg., in the settings of transfer learning \cite{du2020few,tripuraneni2020theory, tripuraneni2021provable,deng2021adversarial} and self-supervised learning \cite{lee2020predicting,ji2021power,tian2021understanding}. Those works focus on analyzing prediction error. In this paper, we initiate the study of the role of representation learning in multi-calibration. \section{Acknowledgements} The authors thank Michael Kim, Omer Reingold, Guy Rothblum, and Gal Yona for conversations that inspired this work. \section{Preliminaries} \subsection{Notation} We say an $\mathbb{R}^d$-valued random vector $x$ follows a $d$-dimensional elementwise sub-Gaussian distribution if for $\mu = {\mathbb{E}}[x]$ and $v\in\mathbb{R}^d$, we have $${\mathbb{E}} \exp (\langle\lambda x-\mu, v\rangle) \le \exp(\lambda^2\sigma^2), \forall \lambda \in \mathbb{R}, v\in\mathbb{R}^d, \|v\|=1.$$ Let us denote $X\in \mathcal X$ as the feature vector (typically $\mathcal X=\mathbb{R}^d$), $Y\in\mathbb{R}$ as the response (what we are trying to predict). For two positive sequences $\{a_k\}$ and $\{b_k\}$, we write $a_k =O(b_k)$ (or $a_n\lesssim b_n$), and $a_k = o(b_k)$, if $\lim_{k\rightarrow\infty}(a_k/b_k) < \infty$ and $\lim_{k\rightarrow\infty}(a_k/b_k) =0$ respectively. $\tilde O(\cdot)$ denotes the term, neglecting the logarithmic factors. We also write $a_k=\Theta(b_k)$ (or $a_k\asymp b_k$) if $a_k\lesssim b_k$ and $b_k\lesssim a_k$. We use $O_p(\cdot)$ to denote stochastic boundedness: a random variable $Z_k=O_p(a_k)$ for some real sequence $a_k$ if $\forall \epsilon>0$, there exists $M,N>0$ such that if $k>N$, $\mathbb{P}(|Z_k/a_k|>M)\le \epsilon$. For a rank-$r$ matrix $M$, we use $\lambda_1(M)$ or $\lambda_{\max}(M)$ to denote its maximum singular value, and $\lambda_r(M)$ or $\lambda_{\min}(M)$ to denote its smallest singular value. We use $c, c_1,c_2,...$ and $C, C_1,C_2,...$ to denote generic positive constants that may vary from place to place. \paragraph{Data Generation Model.} Throughout this work we assume a data generation model of the form $(X,Y)$, where $X \in \mathbb{R}^d$, $Y \in \{0,1\}$, and for some function $p^*:\mathbb{R}^d \rightarrow [0,1]$, we have $E[Y|X]= p^*(X). $ Our results are easily extended from this {\em classification setting} to the {\em regression setting}. We are agnostic as to whether $p^*$ is integer-valued or can take values in $(0,1)$. \begin{Remark} There is a difference between the instance (say, student) and the representation of the instance to the algorithm (say, transcript test scores, and list of extra-curricular activities). We have in mind the situation in which the representation is rich, so distinct instances result in distinct representations (in $\mathbb{R}^d$) to the algorithm, although our results hold in the more general case as well. When there are no collisions in representation the philosophical meaning of an individual probability $p^*(x)$ is a topic of study -- what is the probability of a non-repeatable event? Do non-integer probabilities exist, or are there only outcomes? See~\cite{dawid2017individual,dwork2021outcome} and the references therein. Our results are agnostic on these points. \end{Remark} \iffalse In this work we will consider several different types of neural nets, some quite general and others more constrained. When the neural nets are constrained our results will have application to wider classes of data distributions and, conversely, when the neural nets are in more general form our results require more assumptions on the distributions. \fi \subsection{Calibration/Multi-calibration} We first introduce the notions of calibration and multi-calibration. We assume we have samples $D=\{(X_i,Y_i)\}_{i=1}^{m}$ drawn from the joint distribution $(X,Y)$ where $m$ is the sample size. \begin{Definition}[Calibration] We say a predictor $\hat p$ is $\alpha$-calibrated if for all $v\in\mathbb{R}$, $$ |\mathbb{E}_{X,Y}[Y-\hat p(X)\mid \hat p(X)=v]|\le\alpha. $$ \end{Definition} \begin{Definition}[Asymptotic calibration] Consider a family of predictors $\{{\hat p}_m\}_{m \in \mathbb N}$, where $\hat p_m$, $m \ge 1$, is constructed based on a sample of size $m$. We abuse notation slightly and say that $\hat p_m$ is {\em asymptotically calibrated} if $\hat p_m$ is $\alpha_m$-calibrated, and $\alpha_m\to 0$ when the sample size $m\to \infty$. We will usually omit the subscript $m$ and write the predictor as $\hat p$. \end{Definition} \begin{Definition}[Multi-calibration\cite{HKRR}\footnote{{Our definition is slightly stronger than that in~\cite{HKRR}.}}] For a collection of subsets $\mathcal S=\{S_1, ..., S_K\}\subset \mathcal X$. We say a predictor $\hat p$ is $\alpha$-multi-calibrated with respect to $\mathcal S$ if for all $v\in\mathbb{R}$, $$ |\mathbb{E}_{X,Y}[Y-\hat p(X)\mid \hat p(X)=v, X\in S_k]|\le\alpha, \text{ for all $k\in[K]$}. $$ \end{Definition} Similarly, we say a predictor $\hat p$ is \textit{asymptotically multi-calibrated} with respect to $\mathcal S$ if $\alpha\to 0$ when the sample size $m\to \infty$. A caveat of the calibration/multi-calibration definition is that small calibration error $\alpha$ does not necessarily imply high-accuracy. For example, letting $\hat p(x)=\sum_{i=1}^m Y_i/m$ will yield $O_P(1/\sqrt m)$-calibrated predictor, but in general this $\hat p$ is not accurate as it does not depend on $x$ at all. Our goal is to find a small collection of subsets $\mathcal S=\{S_1, ..., S_K\}\subset \mathcal X$ that produces a multi-calibrated predictor with some accuracy guarantee, through the framework of representation learning. We present an algorithm for finding such a collection $\mathcal S$ and describe conditions, summarized in Assumption~\ref{assumption on h} below, under which any predictor that is asymptotically multi-calibrated with respect to $\mathcal S$ has small error. Under an additional {\em Learnability} assumption (Remark~\ref{rem:learnability}) the predictor is consistent (has estimation error that goes to~0). Further, we propose a predictor that is both multi-calibrated and nearly optimal in terms of accuracy (in the minimax sense) under these conditions. We give concrete and rich examples under which these assumptions hold. \subsection{Problem setup} \begin{Definition}[Scaffolding{} Set Problem] For a mapping $p^*: \mathbb{R}^d \rightarrow [0,1]$ and a data distribution $\mathcal D$ on pairs $(X,Y) \in \mathbb{R}^d \times \{0,1\}$, where $\mathbb{E}[Y|X]=p^*(X)$, the {\em scaffolding{} set problem} is to find, for some fixed polynomial $q$, a method that, given a set of i.i.d.\,draws $\{(X_i,Y_i)\}_{i \in [m]}$ from $\mathcal D$, outputs a collection of sets $\mathcal S^{(m)} = \{S_1, \dots,S_K\}$, $K \le q(m)$, such that $\forall \hat p:\mathbb{R}^d\rightarrow[0,1]$ that is multi-calibrated with respect to $\mathcal S^{(m)}$, $\mathbb{E}_X[(\hat p (X) - p^*(X))^2] \rightarrow 0$ as $m \rightarrow \infty$. We call the sets $\mathcal S^{(m)}$ the {\em scaffolding{} sets}. We will usually omit the superscript $(m)$. \end{Definition} To obtain our solution, we break the problem into two parts. The first takes training data and a {\em representation mapping} $\hat h: \mathbb{R}^d \rightarrow \mathbb{R}^r$ as input and outputs a collection of scaffolding{} sets, where $r$ is the dimension of the representation mapping (we assume $r < d$). The algorithm succeeds under certain technical assumptions on $\hat h$ (see Section~\ref{sec: learning h}); here {\em success} admits error parameters specific to $\hat h$ and the calibration error. The second part is to find a method for generating $\hat h$ that satisfies these assumptions, with the $\hat h$-specific error parameter vanishing as the size of the training set used to find $\hat h$ grows to infinity. In practice, for unknown distributions $p^*$ we cannot verify that the above-mentioned technical assumptions hold. However, we show that for {\em any} predictor $\hat p_0$, {our proposed algorithm (of making $\hat p_0$ multi-calibrated with respect to the scaffolding{} sets $\mathcal S$)} will {\em never} harm the accuracy of estimating $p^*$, even if neither assumption holds. \section{Main Results} \label{sec:main_results} \subsection{The Scaffolding{} Set Algorithm and its Properties} Consider a predictor $\hat p_0$ of form \begin{equation} \label{eq:p0 hat} \hat p_{0}(x)=\hat w\circ \hat h(x), \end{equation} where $\hat h: \mathbb{R}^d\to \mathbb{R}^r$ and $\hat w: \mathbb{R}^r\to\mathbb{R}$ are two mappings, where $r$ is the dimension of $\hat{h}$ (we assume $r<d$). Such a form can be obtained, for example, through fitting single/multiple index models\cite{hardle2004nonparametric, eftekhari2021inference} or the learning of neural networks; in the latter case, $\hat h$ is the first to some intermediate layer and $\hat w$ is the remaining layers. One can interpret $\hat h$ as a (low-dimensional) representation function, in accord with recent papers in representation learning theory in neural nets \cite{du2020few,lee2020predicting, tripuraneni2021provable,ji2021power}. For example, in the numerical investigations by Tripuraneni, Jin, and Jordan \cite{tripuraneni2021provable}, $r=5$. In this section, we make no assumptions about the accuracy of the predictor $\hat p_0$, nor are we concerned with how it is obtained. In fact, our algorithm will only make use of $\hat h$; we ignore $\hat w$ entirely and everything we say applies to an arbitrary $\hat h: \mathbb{R}^d\to \mathbb{R}^r$. Nonetheless, it is useful to think of $\hat h$ as a learned representation mapping, and we make use of this thinking in Section~\ref{sec: learning h}. The Scaffolding{} Set Construction Algorithm takes $\hat h$ and the training data $D$ as input and returns a collection ${\cal S}$ of sets. We define a second predictor, $\hat p$, based on this set collection, and argue that $\hat p$ is multi-calibrated with respect to~${\cal S}$ (Section~\ref{set construction}). We then give conditions on $\hat h$ under which $\hat p$ is guaranteed to approximate~$p^*$, giving tight accuracy bounds (Section~\ref{sec:accuracy}). In Section~\ref{sec: learning h} we address the problem of finding a suitable~$\hat h$. \subsubsection{Algorithm Description} \label{set construction} We now describe a Meta-Algorithm (Algorithm 2) for computing our predictors. Let $\hat h$ be as in Equation~\ref{eq:p0 hat} above, and denote the observations by $D=\{( X_i, Y_i)\}_{i=1}^{m}$ with $X_i\in\mathbb{R}^d$ and $Y_i \in \{0,1\}$. The Meta-Algorithm begins by splitting the training samples into two disjoint sets $D=D_1\cup D_2$, that is, $D_1=\{(X_i^{(1)},Y_i^{(1)})\}_{i=1}^{m_1}$ and $D_2=\{(X_i^{(2)},Y_i^{(2)})\}_{i=1}^{m-m_1}$ for $m_1\le m$. We will use $D_1$ together with $\hat h$ to construct the scaffolding{} sets and $D_2$ for calibration. Such a sample splitting step is commonly used in machine learning and statistics, such as in the problems of the conformal prediction \cite{lei2018distribution, romano2019conformalized}, standard calibration \cite{kumar2019verified,zadrozny2001obtaining}, and random forest \cite{arlot2014analysis,mourtada2020minimax}. In addition to the (possibly learned) representation $\hat h$ and the training data $D$, the Scaffolding{} Set construction algorithm takes as input a number $B$, which denotes the number of partitions on each coordinate. For simplicity, let us assume that, for some $C>0$, ${{\hat h}}(X_i)\in[-C,C]^r$ for all $i \in [n]$. We also let $h_j(X_i)$ denote the $j$-th coordinate of $\hat h(X_i)$ for $j\in[r]$. \begin{figure}[ht] \centering \begin{minipage}{.9\linewidth} \begin{algorithm}[H] \caption{{Scaffolding Set Algorithm}} \label{alg:set} \textbf{Input:} The representation $\hat h$, the number of partitions on each coordinate $B$, any dataset $\{(X_i,Y_i)\}_{i=1}^{n}$ with sample size $n\in\mathbb{N}^+$ \textbf{Step 1:} Let $Output=\{[-C,C]^r\}$ \textbf{Step 2:} For $j=1:r$ \quad\quad\quad\quad\quad For $set^{o}\in Output$ \quad\quad\quad\quad\quad\quad Divide $set^{o}$ into $B$ sets $set^{o}=set^{o}_1\cup set^{o}_2\cup...\cup set^{o}_B$, where the $b$-th set $set^{o}_b$ corresponds to the $(b-1)/B$ to the $b/B$-th quantile of $\{\hat {h}_j(X_i)\}_{i=1}^{n}$ \quad\quad\quad\quad\quad\quad Replace the $set^{o}$ with $set^{o}_1, set^{o}_2,..., set^{o}_B$ in $Output$ \quad\quad\quad\quad\quad EndFor \quad\quad\quad\quad EndFor \textbf{Step 3:} For $Output=\{S^{({{\hat h}})}_1,...,S^{({{\hat h}})}_K\}$, define the corresponding partitions in $\mathcal X$: $S_k=\{x\in \mathcal X: \hat h(x)\in S^{(h)}_k\}$, $k \in [K]$, and let $\mathcal S=\{S_1,...,S_K\}$. \textbf{Step 4:} Output $\mathcal S$. \end{algorithm} \end{minipage} \end{figure} At a high level, this algorithm proceeds by dividing the space into cells, such that within each cell, the values of $\hat h$ are similar to each other. As a result, when $\hat h$ is close to some representation mapping $h$ of $p^*$ (that is, there exists a $w$, such that $w\circ h\approx p^*$ and $\hat h\approx h$), these sets can be assembled into the approximate level sets of $p^*$, on which, as we will show later, multi-calibration ensures accuracy. Moreover, the above algorithm returns $K=B^r$ sets in total, and guarantees that each set contains around $m_1/K$ samples. In Section~\ref{sec:accuracy} we will show that, under some mild model assumptions, $B\asymp m_1^{1/(r+\gamma)}$ (for some constant $\gamma>0$) will yield a minimax optimally accurate predictor. To show the validity of $\mathcal S$, we exhibit a simple post-processing step that yields a predictor that is asymptotically calibrated with respect to $\mathcal S$. This simplicity stems from the fact that the sets in $\mathcal S$ are pairwise disjoint. We denote the partition-identity function as $G:\mathcal X\to[K]$ where $G(x)=k$ if and only if $x\in\mathcal S_k$. Based on the the sets constructed in Algorithm \ref{alg:set}, we can further obtain $\hat{p}$ that is multi-calibrated on the sets ${\mathcal S}$. Thus, we have the following algorithm. \begin{figure}[ht] \centering \begin{minipage}{.9\linewidth} \begin{algorithm}[H] \caption{{Meta-Algorithm }} \label{alg:full} \textbf{Input:} The representation $\hat h$, the number of partitions on each coordinate $B$, the dataset $D=\{(X_i,Y_i)\}_{i=1}^{m}$ the splitting parameter $\pi$, and the calibration parameter $\alpha$ \textbf{Step 1: }Set $m_1=\lfloor \pi m \rfloor$, $m_2=m-m_1$. We split the dataset $D$ into $D_1=\{(X_i^{(1)},Y_i^{(1)})\}_{i=1}^{m_1}$ and $D_2=\{(X_i^{(2)},Y_i^{(2)})\}_{i=1}^{m-m_1}$ \textbf{Step 2:} Obtain ${\mathcal S}$ through $D_1$ by applying Algorithm \ref{alg:set}. \textbf{Step 3:} Use $D_2$ to obtain an $\alpha$-multi-calibrated predictor $\hat p$. \textbf{Step 4:} Output $\hat p$. \end{algorithm} \end{minipage} \end{figure} \begin{Remark} In Step 3 of the Meta-Algorithm, we can apply any algorithm that produces a multi-calibrated predictor, {\it e.g.}, the iterative procedure proposed in \cite{HKRR}. Here, we propose and analyze a simple alternative method to obtain a predictor $\hat p$ that is multi-calibrated with respect to $\mathcal S$ using the data $D_2$: \begin{equation}\label{eq:predictor} \hat p(x)=\frac{1}{|\{X^{(2)}_i\in S_{G(x)}\}|}\sum_{X^{(2)}_i\in S_{G(x)}} Y_i^{(2)}. \end{equation} Suppose we have a specific and moderately-sized collection $\mathcal C$ of sets for which we wish to ensure calibration; for example, these may be specific demographic groups. Recall that we can not know when the Scaffolding{} Set algorithm produces level sets. When it does, multi-calibration produces a predictor that is close to $p^*$ (Theorem~\ref{thm:mc wrt S}), which (most likely) gives calibration with respect to $\mathcal C$. Since we cannot be certain of success, we can still explicitly calibrate with respect to $\mathcal C$ using the algorithm of~\cite{HKRR} as a ``post-processing" step; \cite{HKRR} argues that such post-processing does not harm accuracy. \end{Remark} {{For the simplicity of presentation, throughout the paper, we set $m=2n$, $\pi=1/2$, and therefore $m_1=n$. Our results hold for any $\pi\in(c,1-c)$ with a universal constant $c>0$.}} The following theorem says that, assuming only that the training data are i.i.d., the resulting $\hat p$ is $\tilde O(\sqrt{K/n})$-multi-calibrated with respect to $\mathcal S$. \begin{Theorem}\label{thm:mc} Suppose we construct $\hat p$ as described in the Meta-Algorithm with Step 3 using Equation~\eqref{eq:predictor} (on the set $D$ of size $2n$) for any $B\in\mathbb N$. Let $K=B^r$. If $D=\{(X_i, Y_i)\}_{i=1}^{2n}$ is $i.i.d.$ and $n\ge cK\log(K/\delta)$ for a universal constant $c>0$, then there exists a universal constant $C>0$, such that with probability at least $1-\delta-2\exp\left(\log K-{n/200K}\right)$ over $D$, $$ |\mathbb{E}_{X,Y}[Y-\hat p(X)\mid \hat p(X), X\in S_k]|\le C \sqrt{K\log(K/\delta)/n}, \text{ for all } k\in[K]. $$ \end{Theorem} \iffalse {\color{cyan} [to be removed later] For the uncertainty quantification problem, given a predictor $\hat f$, we can consider two types of intervals \begin{enumerate} \item we would like to find a confidence interval (CI) $\hat C_\alpha(\hat f(x))$, such that $\mathbb{P}({\mathbb{E}}[Y\mid \hat f(x)]\in \hat C_\alpha(\hat f(x)) \mid x\in S_k)\ge 1-\alpha$ \item we would like to find a prediction interval (PI) $\hat P_\alpha(\hat f(x))$, such that $\mathbb{P}(Y\in \hat P_\alpha(\hat f(x)) \mid x\in S_k)\ge 1-\alpha$ \end{enumerate}. For the first type of interval, based on the construction in \eqref{eq:predictor}. Let $N_k=|\{i\in[n_2]:G(X_i^{(2)})=k \}|$. $\hat C_{\alpha}(\hat f(x))=\hat f(x)\pm \sqrt{\frac{2\log(3K/\alpha)}{N_k}}$ satisfies the criterion $\mathbb{P}({\mathbb{E}}[Y\mid \hat f(x)]\in \hat C_\alpha(\hat f(x)) \mid x\in S_k)\ge 1-\alpha$, where the probability is taken over the randomness of training data. Remarks: 1. this confidence interval is derived using concentration inequalities, not the standard normal approximations, therefore might lead to over-coverage. A smarter method might be more desired. 2. According to \cite{foygel2020distribution}, in the standard calibration setting (without considering groups), for classification problems, $(1-\alpha)$ CI would imply $(1-\alpha)$ PI. Need to check if this is still true for the current MC setting (i.e. with multiple groups) } \fi This result shows that, once we have our hands on $\hat{h}$, we can construct sets $\mathcal S$ and, with an extremely simple post-processing step, obtain a predictor (given by Equation~\eqref{eq:predictor}) that is asymptotically multi-calibrated with respect to $\mathcal S$ with high probability if $K\log K/n\to 0$. The condition $K\log K/n\to 0$ holds when we choose $B\asymp n^{1/(r+\gamma)}$ The proof of Theorem~\ref{thm:mc} relies on the fact that the $\hat p$ constructed by \eqref{eq:predictor} only takes finitely many values. Additionally, by our construction, the conditioned event $\{\hat p(x), X\in S_k\}$ has nontrivial mass and includes at least around $n/K$ samples. Therefore, even if we only assume $i.i.d.$ training data, with no assumption on the distribution, this property, combined with some concentration inequalities, implies the desired result on the calibration error. \begin{proof}[Proof of Theorem~\ref{thm:mc}] For a given $k\in[K]$, we define $N_k=|\{i\in[{ n}]:G(X_i^{(2)})=k \}|$, $\hat p_k=\sum_{X_i^{(2)}\in S_k} Y_i^{(2)}/N_k$ and $p_k^*={\mathbb{E}}[Y\mid X\in S_k]$. \begin{Lemma}[Bernstein's inequality] Let $X_1,...X_n$ be independent random variables such that ${\mathbb{E}}[X_i]=0$, $|X_i|\leq b$ and ${\rm Var}{(X_i)}\leq \sigma_i^2$ for all $i$. Let $\sigma^2=\sum_{i=1}^n\sigma_i^2/n$. Then for any $t>0$, \begin{align*} \mathbb{P}{\left(\frac{1}{n}|\sum_{i=1}^nX_i|\geq t\right)}\leq 2\exp\left(-\frac{nt^2/2}{\sigma^2+bt/3}\right). \end{align*} \end{Lemma} \begin{Lemma}[Adapted from Lemma 4.3 in \cite{kumar2019verified}]\label{lem:radius} Suppose we have i.i.d.\,samples from a distribution $\mathcal D$ over $\mathcal X$, $X_1,...,X_n\in\mathcal X$. Suppose further that, for some $K>0$, we obtain a partition of the universe $\mathcal X=S_1\cup...\cup S_K$ such that $|\{i: X_i\in S_k\}|=n/K$ for all $k\in[K]$. Then there exists a universal constant $c$, such that if $n\ge cK\log(K/\delta)$, then for any $X$ independently drawn from $\mathcal D$, with probability at least $1-\delta$ over the choice of $\{X_i\}_{i=1}^n$, $$ {\mathbb{P}}_{X \sim \mathcal D}(X\in S_k)\in (1/2K,2/K), \text{ for all } k\in[K]. $$ \end{Lemma} We first prove the following claim showing that the differences $\hat p_k-p_k^*$, $k \in [K]$, are upper bounded by some stochastic upper bound uniformly for all $k$. For any $\delta\in(0,1)$, with probability at least $1-\delta$,\begin{equation}\label{ineq:concentration1} |\hat p_k-p_k^*|\le \sqrt{\frac{2\log(2K/\delta)}{N_k}}, \text{ for all } k\in[K]. \end{equation} In fact, for any realization of samples $(X_1^{(2)},...,X_{n_2}^{(2)})=(x_1,...,x_{n_2}):=x$, we define the event $E_{G(x)}=\{(G(X_1^{(2)}),...,G(X_{n_2}^{(2)}))=(G(x_1),...,G(x_{n_2}))\}$. On event $E_{G(x)}$, we have $N_k$'s fixed and in each bin $\{i: X_i^{(2)}\in S_k\}$ $Y_i$'s are $i.i.d.\sim Ber(p_k^*)$. As a result, using Bernstein's inequality and the fact that $p_k^*\le 1$, we have$$ {\mathbb{P}}\left(|\hat p_k-p_k^*|\ge t\mid E_{G(x)}\right)\le 2\exp(-\frac{N_k t^2}{{2 p_k^*}+2t/3})\le 2\exp(-\frac{N_k t^2}{{2}+2t/3}). $$ Using the assumption $n\ge cK\log(K/\delta)$ for a universal constant $c>0$, then there exists a universal constant $C_1$ such that when we take $t=\sqrt {C_1\log(K/\delta)/N_k}$, we have $$ {\mathbb{P}}(|\hat p_k-p_k^*|\ge \sqrt\frac{C_1 \log(K/\delta)}{N_k}\mid E_{G(x)})\le 2\exp(-\log(2K/\delta))=\delta/K, $$ implying $$ {\mathbb{P}}(|\hat p_k-p_k^*|\ge \sqrt\frac{C_1\log(K/\delta)}{N_k})\le \delta/K. $$ By a union bound, we then obtain with probability at least $1-\delta$,\begin{equation*} |\hat p_k-p_k^*|\le \sqrt{\frac{C_1\log(K/\delta)}{N_k}}, \text{ for all } k\in[K]. \end{equation*} We now use \eqref{ineq:concentration1} to derive the concentration inequalities for $N_k$. Let $q_k=\mathbb{P}(X_i\in S_k)$. By Bernstein's Inequality we have $$ \mathbb{P}(|N_k/n_2-q_k|\ge t)\leq 2\exp\left(-\frac{n_2t^2/2}{q_k+2t/3}\right). $$ We take $t=1/4K$, then $$ \mathbb{P}(|N_k/n_2-q_k|\ge 1/4K)\leq 2\exp\left(-\frac{n_2/32K^2}{q_k+1/6K}\right). $$ If we have $q_k\in (1/2K,2/K)$, then $$ \mathbb{P}(N_k/n_2 \le 1/4K)\leq 2\exp\left(-{n_2/100K}\right), $$ implying $$ \mathbb{P}(\min_{k\in[K]}N_k/n_2 \ge 1/4K)\geq 1- 2\exp\left(\log K-{n_2/100K}\right)\geq 1- 2\exp\left(\log K-{n/200K}\right). $$ Combining with the inequality~\ref{ineq:concentration1}, we have with probability at least $1-\delta-2\exp\left(\log K-{n/200K}\right)$,$$ |\hat p_k-p_k^*|\le \sqrt{\frac{4C_1\log(K/\delta)}{n_2/K}}\le \sqrt{\frac{8C_1\log(K/\delta)}{n/K}}, \text{ for all } k\in[K]. $$ \end{proof} \subsubsection{Accuracy Analysis} \label{sec:accuracy} In this subsection, we obtain conditions on $\hat h$ under which multi-calibration with respect to the collection $\mathcal S$ of scaffolding{} sets produced by Algorithm~\ref{alg:set} yields accuracy guarantees, specifically, closeness to $p^*$. As usual, we assume that we have $i.i.d.$ observations $D=\{( X_i,Y_i)\}_{i=1}^{2n}$ drawn from a distribution ${\cal D}$ satisfying \begin{equation}\label{eq:model} {\mathbb{E}}[Y_i\mid X_i]=p^*(X_i), \text{ for } i=1,2,...,2n, \end{equation} where $p^*(X): \mathbb{R}^d\to \mathbb{R}$ denotes the true probability (in the classification setting)\footnote{Our analysis can be extended to the regression case with slight modifications.} \iffalse We impose the following assumptions on this model: \begin{enumerate} \item $\epsilon$ is independent with $X$, and ${\mathbb{E}}[\epsilon]=0$, $Var(\epsilon)=\sigma^2<C'$ for some constant $C'$. \item $h(x)\in[-C,C]^r$, and $h(X)$ has continuous and positive probability density over $[-C,C]^r$. \item $w(h)$ is $(\beta,L)$-H\"older smooth, that is, for $\beta\in(0,1]$ and $L>0$, $$ |w(h)-w(h')|\le L \|h-h'\|^\beta, $$ for every $h\in[-C,C]^r$. \item $h$ is learnable, that is, for any $x\in\mathcal X$, ${\mathbb{E}}[\|\hat h(x)-h(x)\|]=e_h\to0$ when $n\to \infty$. \end{enumerate} Under these four assumptions, we have the following theorem, showing that any predictor that is asymptotically multi-calibrated with respect to $\mathcal S$ is consistent. \fi For $\beta\in(0,1]$ and $L>0$, let $\mathcal F(\beta,L)=\{w: \mathbb{R}^r\to\mathbb{R}\mid |w(h)-w(h')|\le L \|h-h'\|^\beta \text{ for any } h,h'\in\mathbb{R}^r\}$ denote the class of all $(\beta,L)$-H\"older smooth function. Let $H(p^*,\beta,L)$ be defined as $$ H(p^*,\beta,L)=\{h: \exists w \in \mathcal F(\beta,L), \text{ s.t. }p^*(x)=w \circ {h}(x)\}. $$ \begin{Assumption} \label{assumption on h} There exists an $h\in H(p^*,\beta,L)$, such that $\mathbb{E}_X[\|\hat h(X)-h(X)\|^2]=e_h$ for some $e_h>0$, and for each $j$, $\hat h_j(x)$ has bounded and positive probability density on a compact set within $[-C,C]$. \end{Assumption} \begin{Theorem} \label{thm:mc wrt S} $\exists c \in \mathbb{R}$ such that, $\forall r, B \in \mathbb{N^+}$, if $\hat{h}$ satisfies Assumption~\ref{assumption on h}, then, letting $\mathcal S$ denote the output of the scaffolding{} set construction algorithm when running on $\hat h$ and a training dataset of size $n\ge cB\log(rB)$ then the following statement holds. If $\hat p$ is $\alpha_n$-multi-calibrated with respect to $\mathcal S$, then for $X\sim{\cal D}$ $$ \mathbb{E}_{X,D}[(\hat p(X)-p^*(X))^2]\lesssim L^2(\frac{r^\beta }{B^{2\beta}}+e_h^\beta)+\alpha_n^2. $$ Here we use the notation $\mathbb{E}_{X,D}$ to denote that we take expectation over the randomness of $X$ and $\hat p$, as $\hat p$ is constructed based on $D$. \end{Theorem} {The proof of Theorem~\ref{thm:mc wrt S} makes use of the observation that, if the collection $\mathcal S$ contains the (approximate) level sets of $p^*$, then multi-calibration with respect to $\mathcal S$ ensures closeness to~$p^*$. By the smoothness condition on $w$, two points that are close in $h$ will also be close in $p^*$, and therefore the approximate level sets of $h$ (found by using the quantiles in Step 2 of Algorithm~\ref{alg:set}) can be used to construct the approximate level sets of $p^*$. This eventually yields an accuracy guarantee. \begin{proof} Fix an arbitrary set $S_k^{(\hat h)} \in \mathcal S$. For all $x\in S_k^{(\hat h)}$, we first define $\lambda_k(X):=\mathbb{E}_{X'}[w\circ h(X')|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k]$, where $X'$ is independent of $X$ and has the same distribution as $X$. By telescoping, we can obtain \begin{align*} \mathbb{E}_{X,D}[(\hat{p}(X)-p^{*}(X))^2]=&\sum_k\mathbb{E}_{X,D}[(\hat{p}(X)-p^{*}(X))^2 I\{X\in S^{(\hat h)}_k\}] \\ \le& 2\sum_k\mathbb{E}_{X,D}[(\hat{p}(X)-\lambda_k(X))^2 I\{X\in S^{(\hat h)}_k\}] \\ &+2\sum_k\mathbb{E}_{X,D}[(p^{*}(X)-\lambda_k(X))^2 I\{X\in S^{(\hat h)}_k\}]. \end{align*} Now, let us look into the term $\hat{p}(X)-\lambda_k(X)$. Since we know that $\hat p(\cdot)$ is $\alpha_n$ multi-calibrated on $S^{(\hat h)}_k$, Thus, \begin{align*} |\hat p(X) - \lambda_k(X)|&=|\hat p(X)-\mathbb{E}_{X'}[w\circ h(X')|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k]| \le \alpha_n. \end{align*} As a result, we have $$ 2\sum_k\mathbb{E}_{X,D}[(\hat{p}(X)-\lambda_k(X))^2 I\{X\in S^{(\hat h)}_k\}]\le 2 \sum_k\alpha_n^2 \mathbb{P}(X\in S^{(\hat h)}_k) = 2\alpha^2_n.$$ On the other hand, \begin{align*} &\mathbb{E}_{X,D}[(p^{*}(X)-\lambda_k(X))^2 I\{X\in S^{(\hat h)}_k\}]\\ \lesssim& \mathbb{E}_{X,D} [(w\circ \hat h(X)-\mathbb{E}_{X'}[w\circ \hat h(X')|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k])^2I\{X\in S^{(\hat h)}_k\}]\\\ &+ \mathbb{E}_{X,D}[(w\circ (h(X)-\hat h(X)))^2I\{X\in S^{(\hat h)}_k\}]\\ &+\mathbb{E}_{X,D}\left((\mathbb{E}_{X'}[w\circ h(X') - w\circ \hat h(X')|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k])^2I\{X\in S^{(\hat h)}_k\}\right). \end{align*} Meanwhile, note that \begin{align*} &\mathbb{E}_{X,D}\left((\mathbb{E}_{X'}[w\circ h(X') - w\circ \hat h(X')|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k])^2I\{X\in S^{(\hat h)}_k\}\right)\\ \le& \mathbb{E}_{X,D}\left((\mathbb{E}_{X'}[(w\circ h(X') - w\circ \hat h(X'))^2|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k])I\{X\in S^{(\hat h)}_k\}\right)\\ \le& L^2 \mathbb{E}_{X,D}\left((\mathbb{E}_{X'}[(\| h(X') - \hat h(X')\|^{2\beta}I\{X\in S^{(\hat h)}_k\}|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k])\right)\\ =& L^2(\mathbb{E}_{X'}[(\| h(X') - \hat h(X')\|^{2\beta}|X'\in S^{(\hat{h})}_k]\mathbb{P}(X\in S^{(\hat{h})}_k))=L^2(\mathbb{E}_{X'}[(\| h(X') - \hat h(X')\|^{2\beta}|x'\in S^{(\hat{h})}_k]\mathbb{P}(X'\in S^{(\hat{h})}_k))\\ =&L^2(\mathbb{E}_{X'}[\| h(X') - \hat h(X')\|^{2\beta}\cdot I\{X'\in S^{(\hat{h})}_k\}]. \end{align*} For the second inequality, since the indicator $I\{X\in S^{(\hat h)}_k\}$ can be viewed as a real number (no randomness) before taking expectation over $X$, so we can move the indicator function. As a result, the last two terms, by Assumption 1, are both bounded by $L^2e_h^\beta$. For the remaining term $$\mathbb{E}_{X,D}[(w\circ \hat h(X)-\mathbb{E}_{X'}[w\circ \hat h(X')|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k])^2I\{X\in S^{(\hat h)}_k\}].$$ Since both $X$ and $X'$ are in $S^{(\hat h)}_k$, using Lemma~\ref{lem:radius} and combining with the assumption that for each $j$, $\hat h_j(X)$ has bounded and positive probability density on a compact set in $[-C,C]$, we have that the length of each coordinate of $S_k^{\hat h}$ is $\Theta(1/B)$ uniformly for all coordinates simultaneously with probability $1-B^{-2}$ when $n\ge cB\log(rB)$ for some universal constant $c$. As a result, the radius of each cell $S^{(\hat h)}_k$ is $\Theta( \sqrt{r}/B)$ with probability $1-B^{-2}$. Thus, we know that by Holder smoothness, that $$\mathbb{E}_{X,D}[(w\circ \hat h(X)-\mathbb{E}_{X'}[w\circ \hat h(X')|\hat{p}(X')=\hat{p}(X), X'\in S^{(\hat{h})}_k])^2I\{X\in S^{(\hat h)}_k\}]\lesssim L^2\frac{r^\beta}{B^{2\beta}}+\frac{2}{B^2}\lesssim L^2\frac{r^\beta}{B^{2\beta}}.$$ Combining all the terms together, the proof is complete. \end{proof} \begin{Remark} We note here that Assumption~\ref{assumption on h} can be relaxed to allow approximation error, that is, $h\in H(p^*,\beta,L,\epsilon)$, where $H(p^*,\beta,L,\epsilon)=\{h: \exists w \in \mathcal F(\beta,L), s.t. \sup_{x\in\mathcal X}|p^*(x)-w \circ {h}(x)|\le\epsilon\}. $ In this case a proof similar to that of Theorem~\ref{thm:mc wrt S} yields $ \mathbb{E}_{X,D}[(\hat p(X)-p^*(X))^2]\lesssim L^2(\frac{r^\beta }{B^{2\beta}}+e_h^\beta)+\alpha_n^2+\epsilon^2. $ \end{Remark} \iffalse {\red do we need this corollary?} \begin{Corollary}[Our algorithm will not hurt under well-specified case] If there exists a trained $k$-layer neural network $\hat{f}$, such that for the probability function $\mathbb{E}_x(p^*(x)-\hat{f}(x))^2\le \varepsilon$. Denote $\hat{f}=\hat{w}\circ\hat{h}$ (add some conditions on $\hat w$ and $\hat h$?), where $\hat h$ represents the function obtained by some intermediate layers with output dimension $r$, for any $\delta>0$, then as long as the sample size $n=\Omega\left({poly(\|\hat w\|, r,1/\delta)}\right)$, applying our algorithm on $\hat h$ and for any $\hat{p}$ that is $\alpha_n$-multi-calibrated on $\{S^{(\hat{h})}_k\}$, we have $$E_{x}\|p^*(x)- \hat{p}(x)\|\le \delta^2+\varepsilon^2+\alpha_n^2.$$ \end{Corollary} \begin{proof} It is a straightforward application of Theorem 1. \end{proof} \fi This theorem further implies that for the predictor $\hat p$ constructed as in~\eqref{eq:predictor}, we have the following more refined accuracy guarantee. \begin{Corollary}\label{col:1} Suppose we construct $\hat p$ as described in~\eqref{eq:predictor}. Then, under Assumption~\ref{assumption on h}, we have $$ \mathbb{E}_{X,D}[(\hat p(X)-p^*(X))^2]=\tilde O( L^2(\frac{r^\beta }{B^{2\beta}}+e_h^\beta)+\frac{B^r}{n}) $$ In particular, if we choose $B\asymp L^{2/(r+2\beta)}n^{1/(r+2\beta)}$, we will then have $$ \mathbb{E}_{X,D}[(\hat p(X)-p^*(X))^2]=\tilde O(L^2 e_h^\beta+L^{2r/(r+2\beta)}n^{-2\beta/(r+2\beta)}) $$ \end{Corollary} \begin{Remark} \label{rem:learnability} In practice, we can also further split $D_1$ equally and try to use the first half to {\em learn} an $\hat h$. The hope in this scenario is that more training data will lead to learned functions $\hat h$ that, in the context of Assumption~\ref{assumption on h}, will have error terms $e_h$ that vanish as the sample size $n\to \infty$. We will refer to this as the {\em Learnability Assumption.} Note that, as $n$ grows, yielding a sequence of functions, $\hat{h}_n$, the $h_n$'s that witness the fact that the $\hat h_n$'s satisfy Assumption~\ref{assumption on h} may change with~$n$. Under the Learnability Assumption, the corollary implies that, if $e_h=\tilde O( L^{-4/(r+2\beta)}n^{-2/(r+2\beta)})$, then $$\mathbb{E}_{X,D}[(\hat p(X)-p^*(X))^2]=\tilde O(L^{2r/(r+2\beta)}n^{-2\beta/(r+2\beta)}). $ In fact, this is the best rate one could achieve since we have the following minimax lower bound \cite{tsybakov2009introduction}: there exists a universal constant $C$, such that $$ \inf_{\hat p}\sup_{p^*=w\circ h: w\in\mathcal F(\beta,L)}\mathbb{E}_{X,D}[(\hat p(X)-p^*(X))^2]\geq C\cdot L^{2r/(r+2\beta)}n^{-2\beta/(r+2\beta)}. $$ \end{Remark} This minimax result demonstrates that for any proposed estimator $\hat p$ obtained by training, there exists $p^*$ belonging to the class of structures we considered, the discrepancy between $\hat p$ and $p^*$ has to be larger than the rate $L^{2r/(r+2\beta)}n^{-2\beta/(r+2\beta)}$; in other words, this rate is the best one can get. \begin{Remark} In Section~\ref{sec: learning h}, we will present several methods that produce $e_h$ satisfying the condition $$e_h=\tilde O( L^{-4/(r+2\beta)}n^{-2/(r+2\beta)}),$$ when $p^*$ is expressible by different types of neural networks. \end{Remark} \subsubsection{``No Harm"} In this section, we show that even if Assumption~\ref{assumption on h} fails to hold, running the Meta-Algorithm with Equation~\eqref{eq:predictor} for the multi-calibration step will not harm accuracy. Specifically, suppose that we already have a prediction function $\hat p_0=\hat w\circ\hat h$ (from any training algorithm). We show that if we post-process ${\hat p}_0$ by using $\hat h$ as an input of Algorithm~\ref{alg:full}, and compute the Step 3 there via Equation~\eqref{eq:predictor}, then the resulting predictor is no less accurate than $\hat p_0$. It is in this sense that Algorithm~\ref{alg:full} ``does no harm". This may be viewed as an analogue to the results of~\cite{HKRR} that multi-calibrating an existing predictor does not harm accuracy. Recall that in Equation~\eqref{eq:predictor}, on each set $S$ that is found by the Scaffolding{} Set algorithm (Algorithm \ref{alg:set}), we set $\hat p$ to $\hat p(x)=\sum_{X_i\in S}Y_i/|S|. $ We have the following proposition. \begin{Proposition}\label{prop:no harm} Suppose that we have $\hat w\in\mathcal F(\beta,L)$, $\hat h(x)\in[-C,C]^r$, and $\hat h(X)$ has continuous and positive probability density over $[-C,C]^r$. Then there exists a constant $C$ such that, for $\hat p$ obtained by running the Meta-Algorithm (Algorithm~\ref{alg:full}) with multi-calibration achieved via Equation \ref{eq:predictor} on input $\hat h$, training set $D$ of size $2n$, $B$ and $r$ $$\mathbb{E}_{X,D}[(p^*(X)-\hat p(X))^2]\le\mathbb{E}_X[(p^*(X)-\hat p_0(X))^2]+\tilde O(L^2\frac{r^\beta}{B^{2\beta}}+\frac{B^r}{n}).$$ \end{Proposition} \begin{Remark} Note that the conditions we impose are on $\hat w$ and $\hat h$, which can be enforced during the training process. For example, we can enforce the smoothness of $\hat w$ by imposing bounded norm constraints on the parameters in neural network training. \end{Remark} This ``no harm'' result is proved using a decomposition of the mean squared error (MSE) $\mathbb{E}_{X,D}[(p^*(X)-\hat p(X))^2]=\sum_{S\in\mathcal S}\mathbb{E}_{X\in S,D}[(p^*(X)-\hat p(X))^2]$. In each $S$, the values of $\hat p$ vary little, and are almost constant. Using the fact that the mean minimizes the MSE, replacing this constant with ${\mathbb{E}}_{X\in S}[p^*(X)]$ therefore yields a smaller MSE. \begin{proof} We first analyze this problem at the population level (when we have infinite number of samples). The Scaffolding{} Set construction algorithm yields a collection of sets. For any set $S$ in this collection, and for any $x\in S$, at the population level, we update $\hat p_0$ to obtain $$ \tilde p(x)=\frac{1}{\mu_X(S)}\int_{x\in S} p^*(x)\;d\mu(x), $$ where $\mu_X(S)=\int_S \;d\mu(x)$. We also define, for $x\in S$, $\bar p_0(x)=\frac{1}{\mu_X(S)}\int_{x\in S} \hat p_0(x)\;d\mu(x)$. We present the following lemma \begin{Lemma}\label{lm:pop} Using the update rule described above, we have $$\int_{x\in S}(p^*(x)-\tilde p(x))^2 \;d\mu(x)\le\int_{x\in S}(p^*(x)-\bar p_0(x))^2 \;d\mu(x).$$ \end{Lemma} \begin{proof} Let $f(c)=\int_{x\in S}(p^*(x)-c)^2 \;d\mu(x)$. Then we have $$ f'(c)=2\int_{x\in S}(c-p^*(x)) \;d\mu(x). $$ Setting $f'(c)=0$, we get $f$ obtains the minimum when $c=\frac{1}{\int_S \;d\mu(x)}\int_{x\in S} p^*(x)\;d\mu(x)$. \end{proof} \paragraph{[Proof of Proposition \ref{prop:no harm}].} Let $\tilde p$ be defined as $\frac{1}{\mu_X(S)}\int_{x\in S} p^*(x)\;d\mu(x)$ and $\bar p_0=\frac{1}{\mu_X(S)}\int_{x\in S} \hat p_0(x)\;d\mu(x)$. By Lemma~\ref{lm:pop}, we have $$ \int_{x\in S}(p^*(x)-\tilde p(x))^2 \;d\mu(x)\le\int_{x\in S}(p^*(x)-\bar p_0(x))^2 \;d\mu(x). $$ So all we need now is to upper bound $ \int_{x\in S}(\hat p(x)-\tilde p(x))^2 \;d\mu(x) $ and $ \int_{x\in S}(\hat p_0(x)-\bar p_0(x))^2 \;d\mu(x). $ The first term is due to the finite sample. By definition, recall that we have $\hat p(x)=\frac{1}{\#\{X_i\in S\}}\sum_{X_i\in S}Y_i$, and $\tilde p(x)=\frac{1}{\mu_X(S)}\int_{x\in S} p^*(x)\;d\mu(x)$. By Theorem~\ref{thm:mc}, with probability at least $1-2\delta$ over $D$, we have $$ \mathbb{E}_x \|\tilde p(x)-\hat p(x)\|^2\le \frac{B^r\log n}{n}. $$ For the second term, using the result in the proof of Theorem~\ref{thm:mc wrt S}, we have that with probability at least $1-B^{-2}$, the radius of each cell $S^{(\hat h)}_k$ is $\Theta( \sqrt{r}/B)$, so $|\hat h(x)-\hat h(x')|\lesssim\frac{\sqrt r}{B}$, we then have $|\hat p_0(x)-\hat p_0(x')|\lesssim L(\frac{\sqrt r}{B})^\beta$. As a result, we have $$ \int_{x\in S}(\hat p_0(x)-\bar p_0(x))^2 \;d\mu(x)\le L^2(\frac{\sqrt r}{B})^{2\beta}\cdot\mu_X(S). $$ Combining all the pieces and summing up on all $S$'s, we obtain the desired result. \end{proof} \section{Methods for Finding $\hat h$} \label{sec: learning h} In the previous section, the accuracy guarantees (Theorem 2) rely on the assumption that the input $\hat h$ is close to some function $h$ which can serve as a representation mapping for $p^*$ (Assumption 1). In this section, we present methods for finding such an~$\hat h$ in the neural network setting, as well as an extension to the transfer learning setting. \subsection{Obtaining $\hat h$ in a homogeneous neural network} Consider the binary classification problem where we have $n$ i.i.d.~observations $\{(X_i,Y_i)\}_{i \in [n]}$ such that ${\mathbb{E}}[Y_i\mid X_i]=p^*(X_i)$, and in which $p^*$ has the form \begin{equation}\label{eq:model fitting} p^*(x)=\Pr[Y=1\mid X=x]=W_k(\sigma(W_{k-1}\sigma(...\sigma(W_1 x))), \end{equation} where $x\in\mathbb{R}^{d_1}$, $W_1\in\mathbb{R}^{1\times d_1}$, $W_2\in\mathbb{R}^{d_2\times d_1}, W_j\in\mathbb{R}^{d_j\times d_{j-1}}$ for $j=3,...,k-1$, $W_k\in\mathbb{R}^{1\times d_{k-1}}$, and $\sigma(\cdot)$ is the ReLU activation function $\sigma(x)=\max\{0,x\}$. Suppose $\|W_j\|_2=O(1)$, for $j=1,2,...,k$. Such a neural network model is said to be {\em homogeneous} because multiplying $x$ by a positive number $a$ will result in multiplying the output by $a^m$, for some $m\in\mathbb{N}$. Such a model approximates the single index model, which is a commonly used data distribution assumption in economics \cite{powell1989semiparametric, horowitz2009semiparametric}, time series \cite{fan2008nonlinear}, and survival analysis \cite{lu2006class}. The model \eqref{eq:model fitting} is also commonly used in the theoretical deep learning community, see \cite{ge2018learning, lyu2019gradient, ge2019learning}. Suppose that we now solve $$ \hat W_1=\arg\min_{W_1}\frac{1}{n}\sum_{i=1}^n (Y_i-W_1 X_i)^2, $$ and then set $\hat h(x)=\hat W_1x$. The following theorem shows that this learned $\hat h$ is a good representation mapping for a rich class of data distributions. \begin{Theorem}\label{thm:ReLU:rep} Suppose $X_i$'s are i.i.d.~drawn from a symmetric \footnote{For a distribution with probability density $p$, we say this distribution is symmetric if and only if $p(x)=p(-x)$ for all $x$.} and sub-gaussian distribution with covariance matrix $\Sigma_X$ {and} positive densities on a compact support within $\{x\in\mathbb{R}^{d_1}:\|x\|\le C\}$ for some constant $C>0$. We also assume $c_1\le\lambda_{\min}(\Sigma_X)\le\lambda_{\max}(\Sigma_X)\le c_2$ for some universal constants $c_1,c_2$. Moreover, we denote $q(v)=W_k(\sigma(W_{k-1}(...\sigma(W_2v))$ and assume $q\not\equiv 0$. Letting $\gamma=\frac{1}{2}q(1)$ and $h(x)=\gamma W_1 x$, we then have with probability at least $1-n^{-2}$, $$ \mathbb{E}_{X}\|\hat h(X)-h(X)\|^2=O(\frac{d_1}{n}). $$ \end{Theorem} \remove{Analogous statements to Theorems~\ref{thm:sigmoid} and~\ref{thm:ReLU} hold for {\em any} $\hat p$ that is multi-calibrated with respect to the scaffolding{} sets output by Algorithm~\ref{alg:part}; the key difference is the calibration error $\alpha_n$, as in the bound given in Theorem~\ref{thm:mc wrt S}.} We remark that Theorem~\ref{thm:ReLU:rep} shows that $\hat h(x)$ is close to $h(x)=\gamma W_1 x$. Now, letting $w(h)=W_k(\sigma(W_{k-1}(...\sigma(h/\gamma))$, we have $w\circ h=p^*$. Using the set construction algorithm proposed above with input $\hat h(x)=\hat W_1x$, we then obtain the following corollary regarding the accuracy produced by multi-calibrating with respect to the output $\mathcal S$. \begin{Corollary}\label{cor:ReLU} Under the same conditions as in the statement of Theorem~\ref{thm:ReLU:rep}, and further assuming that the depth $k\le C_1$ and $\|W_j\|_2\le C_2$, for $j=1,2,...,k$ for some universal constants $C_1, C_2$, we have$$ \mathbb{E}_{X,D}[(p^*(X)-\hat p(X))^2]\lesssim \frac{d_1}{n}+ (\frac{\log n}{n^{1/3}})^2+\alpha_n^2. $$ \end{Corollary} \begin{Remark} The sub-Gaussian distribution is quite general in machine learning. For example, any data where the feature values are bounded are sub-Gaussian. This includes all image data since the pixel values are bounded. \end{Remark} \begin{Remark} We can interpret the symmetry requirement in two ways. First, in the practice of training neural networks, people often pre-process the data to make them centralized (a process also known as {\em standardization}). The symmetry requirement then becomes ``symmetric around the mean". Second, we can also augment the dataset to enforce it to satisfy this requirement, that is, for a sample $x$, we add a $-x$ to the training data. In image data, this augmentation corresponds to adding \textit{negative images} in photography. \end{Remark} \begin{proof}[Proofs of Theorems~\ref{thm:ReLU:rep} and Corollary~\ref{cor:ReLU}]\label{sec:proof:relu} We first present a handy lemma. \begin{Lemma}\label{lem:relu} Suppose $X_i$'s are i.i.d. sampled from a symmetric and sub-gaussian distribution, and denote $q(v)=W_k(\sigma(W_{k-1}(...\sigma(W_2v))$ with $\sigma$ being the ReLU function $\sigma(x)=\max\{x,0\}$, then we have $${\mathbb{E}}[Y_iX_i]={\mathbb{E}}[p^*(X_i)X_i]=\frac{1}{2}q(1)\cdot\Sigma_X W_1^\top.$$ \end{Lemma} The proof of Lemma~\ref{lem:relu} is deferred to the appendix. Now let us recall that $\gamma=\frac{1}{2}q(1)$. Since $\|W_j\|\lesssim 1$ for $j=1,2,...,k$, we have $g$ is $L$-Lipschitz for some universal constant $L$, which also implies $\gamma\le L$. We then analyze the convergence of $\hat W_1$. By definition, we have $$ \hat W_1=(\frac{1}{n}\sum_{i=1}^n X_iX_i^\top)^{-1}(\frac{1}{n}\sum_{i=1}^n X_iY_i). $$ Using standard concentration inequality for Wishart matrices for sub-gaussian distribution, we have with probability at least $1-n^{-2}$, $$ \|\frac{1}{n}\sum_{i=1}^n X_iX_i^\top-\Sigma_X\|=\|\frac{1}{n}\sum_{i=1}^n X_iX_i^\top-{\mathbb{E}}[X_iX_i^\top]\|=O(\sqrt\frac{d_1}{n}), $$ and $$ \|\frac{1}{n}\sum_{i=1}^n X_i Y_i-{\mathbb{E}}[X_iY_i]\|=O(\sqrt\frac{d_1}{n}). $$ Then using Lemma \ref{lem:relu}, suppose $\lambda_{\min}(\Sigma)\gtrsim c_1$ and $d_1/n\le c_2$ for some universal constants $c_1$ and $c_2$, we then have $$ \|\hat W_1-\gamma W_1\|=\|(\frac{1}{n}\sum_{i=1}^n X_iX_i^\top)^{-1}(\frac{1}{n}\sum_{i=1}^n X_iY_i)-\Sigma_X^{-1}{\mathbb{E}}[X_iY_i]\|=O_P(\sqrt\frac{d_1}{n}). $$ We now let $\hat h(x)=\hat W_1x$, $h(x)=\gamma W_1 x$. We then have with probability at least $1-n^{-2}$, $$ \mathbb{E}_x(\hat h(x)-h(x))^2= O(\frac{d_1}{n}). $$ Recall that $w(x)=W_3\sigma(W_2\sigma(u/\gamma))$. We then have $w$ is $1$-Lipschitz, and using Theorem~\ref{thm:mc wrt S}, we obtain $$ {\mathbb{E}}[(p^*(x)-\hat p(x))^2]\lesssim \frac{d_1}{n}+ (\frac{\log n}{n^{1/3}})^2+\alpha_n^2. $$ \end{proof} \subsection{Obtaining $\hat h$ in an inhomogeneous neural network} In the this section, we present a theorem showing that if we assume the input distribution is Gaussian, then we are able to allow $p^*$ to be an inhomogeneous neural network and include bias terms, that is, \begin{equation}\label{eq:model fitting2} p^*(x)=W_k(\sigma(W_{k-1}(\sigma(...\sigma(W_1 x+b_1))+b_{k-2})+b_{k-1}), \end{equation} where $x\in\mathbb{R}^{d_1}$, $W_1\in\mathbb{R}^{1\times d_1}$, $W_2\in\mathbb{R}^{d_2\times 1}, W_j\in\mathbb{R}^{d_j\times d_{j-1}}$ for $j=3,...,k-1$, $W_k\in\mathbb{R}^{d_k\times 1}$; $b_1\in\mathbb{R}, b_k\in\mathbb{R}^{d_k}$, and $\sigma(\cdot)$ being a general activation function. \begin{Theorem}\label{thm:sigmoid:rep} Suppose $X_i$'s are i.i.d.\,drawn from a Gaussian distribution $N_{d_1}(0,\Sigma_X)$. We also assume $c_1\le\lambda_{\min}(\Sigma_X)\le\lambda_{\max}(\Sigma_X)\le c_2$ for some universal constants $c_1,c_2$. Moreover, we denote $$g(u)=W_k(\sigma(W_{k-1}(\sigma(...\sigma(u+b_1))+b_{k-2})+b_{k-1})$$ and assume $g$ is $L$-Lipschitz with $L<C$ for some constant $C>0$, and $\gamma={\mathbb{E}}[g'(W_1x)]\neq 0$. Letting $h(x)=\gamma W_1 x$, we then have with probability at least $1-n^{-2}$, $$ \mathbb{E}_{X}\|\hat h(X)-h(X)\|^2=O(\frac{d_1}{n}). $$ \end{Theorem} \begin{Remark} Note that by taking $w(h)=W_k(\sigma(W_{k-1}(...\sigma(h/\gamma+b_1))+b_{k-2})+b_{k-1})$, we will have $w\circ h=p^*$. A bound on the MSE for $p^*$ analogous to that of Corollary~\ref{cor:ReLU} can be obtained by using Theorem~\ref{thm:sigmoid:rep} with slight modifications in the proof. \end{Remark} \begin{proof}[Proof of Theorem~\ref{thm:sigmoid:rep}] The proof of theorem~\ref{thm:sigmoid:rep} follows the same strategy of Theorem~\ref{thm:ReLU:rep}. We first present an analogue to Lemma~\ref{lem:relu}. \begin{Lemma}\label{lem:sigmoid} Suppose $X_i$'s are i.i.d.\,samples from $N_{d_1}(0,\Sigma_X)$ and denote $g(u)=W_k(\sigma(W_{k-1}(\sigma(...\sigma(u+b_1))+b_{k-2})+b_{k-1})$, with $\sigma$ being the a general activation function, Then $${\mathbb{E}}[Y_iX_i]={\mathbb{E}}[p^*(X_i)X_i]={\mathbb{E}}[g'(W_1x)]\Sigma_X W_1^\top.$$ \end{Lemma} Then following the exact same analysis in Section~\ref{sec:proof:relu}, we obtain the desired result. \noindent\textbf{Proof of Lemma~\ref{lem:sigmoid}:} We will use the First-order Stein's Identity \cite{diaconis2004use}. \begin{Lemma}[First-order Stein's Identity\cite{diaconis2004use}]\label{lm:stein} Let $X \in \mathbb{R}^d$ be a real-valued random vector with density $\rho$. Assume that $\rho$: $\mathbb{R}^d \to R$ is differentiable. In addition, let $g : \mathbb{R}^d \to \mathbb{R}$ be a continuous function such that ${\mathbb{E}}[\nabla g(X)]$ exists. Then it holds that$$ \mathbb{E}_{{X\sim \rho}}[g(X)\cdot S(X)]={\mathbb{E}}[\nabla g(X)], $$ where $S(X)=-\nabla \rho(x)/\rho(x)$. \end{Lemma} Now, let us plug in the density of $N_{d_1}(0,\Sigma_X)$, $p(x)=ce^{x^\top\Sigma_X^{-1}x/2}$ for some constant $c$. We then have $\nabla p(x)=ce^{x^\top\Sigma_X^{-1}x/2}\cdot \Sigma_X^{-1}x$ and $\nabla p(x)/p(x)= \Sigma_X^{-1} x$. As a result, we have $$ {\mathbb{E}}[p^*(x) \Sigma_{X}^{-1}x]={\mathbb{E}}[\nabla p^*(x)], $$ implying $$ {\mathbb{E}}[p^*(x)x]= \Sigma_{X}{\mathbb{E}}[\nabla p^*(x)]. $$ Then recall that $p^*(x)=g(W_1x)$, so we have $\nabla p^*(x)=g'(W_1x)W_1^\top$. Combining all the pieces, we obtain $$ {\mathbb{E}}[p^*(x)x]= \Sigma_{X}{\mathbb{E}}[g'(W_1x)]W_1^\top. $$ \end{proof} \subsection{Obtaining $\hat h$ through transfer learning} In this section, we present an example of obtaining $\hat h$ in the transfer learning setting \cite{du2020few,tripuraneni2021provable,deng2021adversarial}, where in addition to the samples from the target model, we have auxiliary samples from different but possibly related models. Following the terms in the transfer learning literature, we will refer to the target model as the {\em target task}, and the auxiliary models as the {\em source tasks}. In transfer learning, there are two principal settings: (1) {\em covariate shift}, where the marginal distributions of $X$ are assumed to be different across different source tasks; and (2) {\em concept shift}, where the conditional distribution $\mathbb{P}(Y\mid X)$ are different. We will consider both types of shift. \paragraph{Covariate shift.} In the setting in which the marginal distribution on $X$ vary across source tasks, we assume that there are $T$ source tasks, and in the $t$-th source task ($t\in[T]$), we observe $n$ $i.i.d.$ samples $(X_i^{(t)}, Y_i^{(t)})$ from the model $Y^{(t)}_i\sim Ber(p^*(X^{(t)}_i))$, where $p^*$ has the form \begin{equation}\label{eq:model fitting-2} p^*(x)=\Pr[Y=1\mid X=x]=W_k(\sigma(W_{k-1}(\sigma(...\sigma(W_1 x+b_1))+b_{k-2})+b_{k-1}), \end{equation} where $x\in\mathbb{R}^{d_1}$, $W_1\in\mathbb{R}^{r\times d_1}$, $W_2\in\mathbb{R}^{d_2\times r}, W_j\in\mathbb{R}^{d_j\times d_{j-1}}$ for $j=3,...,k-1$, $W_k\in\mathbb{R}^{1\times d_{k-1}}$, $b_1\in\mathbb{R}^r, b_k\in\mathbb{R}^{d_k}$, and $\sigma(\cdot)$ is a general activation function. We assume $r<d_1$, and note here in this model we treat $W_1 x$ as the representation function $h(x)$ in Section~\ref{sec:main_results}. {Note that the representation function $h$ is not unique. That is, let $h(x)=W_1x$; and let $w(u)= W_k(\sigma(W_{k-1}(\sigma(...\sigma(u+b_1))+b_{k-2})+b_{k-1})$. Then $p^*$ in \eqref{eq:model fitting-2} satisfies $p^*=w\circ h$; however, for any invertible matrix $Q\in\mathbb{R}^{r\times r}$, we can also find $\tilde w(u)=w(Q^{-1}u)$ and $\tilde h(x)=QW_1x$ such that $p^*=w\circ h=\tilde w\circ \tilde h$. Therefore, for simplicity of presentation, we assume $W_1$ is an orthogonal matrix such that $W_1W_1^\top=I_{r}$ (for an arbitrary matrix $W_1\in\mathbb{R}^{r\times d_1}$, the existence of the matrix $Q$ such that $QW_1$ is an orthogonal matrix is guaranteed by the singular value decomposition (SVD) if we assume $\lambda_{r}(W_1)>0$). } We now study how to learn {an approximation to} $W_1$. For each source task, we fit the data by a (smaller) linear model $$ \hat\beta^{(t)}=\arg\min\frac{1}{n}\sum_{i=1}^n (Y_i^{(t)}-\beta^\top X_i^{(t)})^2. $$ We can then learn $W_1$ by performing SVD on the matrix $\hat B=[\hat\beta^{(1)},\hat\beta^{(2)},...,\hat\beta^{(T)}]$. We denote the left top-r singular vectors of $\hat B$ as $\hat W_1$. Let $\mathbb{O}^{r\times r}$ be the class of all $r\times r$ orthonormal matrices. We will show that $\min_{O\in\mathcal{O}_{r\times r}}\| OW_1-\hat W_1\|_F$ vanishes as $n\to\infty$. To facilitate the theoretical derivation, we need a diversity assumption. Under the covariate shift setting, the distributions of $X_i^{(t)}$ are different over $t\in[T]$. For $g(u)=W_k(\sigma(W_{k-1}(\sigma(...\sigma(u+b_1))+b_{k-2})+b_{k-1})$ (for $u\in\mathbb{R}^{r}$), we define $m_t={\mathbb{E}}_{{X^{(t)}}}[\nabla {g}(W_1X^{(t)})]$ and $M=[m_1,...,m_T]$. The diversity assumption we impose here assumes that the $T$ marginal distributions of $X_i^{(t)}$ are diverse enough, that is, the $r$-th largest singular value $\lambda_{r}(MM^\top /T)>c$ for some universal constant $c>0$. We remark here that similar diversity assumptions have been appeared in other transfer learning papers, e.g. \cite{du2020few,tripuraneni2021provable}, where they consider two-layer neural network models. Under the diversity assumption mentioned above, we then present the following theorem. \begin{Theorem}\label{thm:sigmoid:rep:transfer} Suppose for the $t$-th task, $X_i^{(t)}$'s are i.i.d.\,drawn from a Gaussian distribution $N_{d_1}(0,\Sigma_{X^{(t)}})$. We also assume $c_1\le\lambda_{\min}(\Sigma_{X^{(t)}})\le\lambda_{\max}(\Sigma_{X^{(t)}})\le c_2$ for some universal constants $c_1,c_2>0$. Moreover, for the function $g(\cdot)$ and matrix $M$ defined in the previous paragraph, we assume $g$ is $L$-Lipschitz with $L<C$ for some constant $C>0$, and $c_1'\le\lambda_{r}(MM^\top /T)>\lambda_{\max}(MM^\top /T)\le c_2'$ for some universal constants $c_1',c_2'>0$. Suppose $T=O(d_1^2)$. Letting $\hat h(x)=\hat W_1 x$, $h(x)=O W_1 x$ where $O=\arg\min_{O\in\mathcal{O}_{r\times r}}\| OW_1-\hat W_1\|_F$, we then have with probability at least $1-o(1)$, $$ \mathbb{E}_{X}\|\hat h(X)-h(X)\|^2=O({\frac{r(d_1+T)}{nT}}). $$ \end{Theorem} \begin{proof} We first use Stein's identity (Lemma~\ref{lm:stein}) and obtain $$ \mathbb{E}_{{X^{(t)}}}[p^*(X^{(t)})X^{(t)}]=\Sigma_{X^{(t)}} W_1^\top {\mathbb{E}}[\nabla g(W_1X^{(t)})]. $$ We denote $\beta^{(t)}=\Sigma_{X^{(t)}}^{-1}{\mathbb{E}}[p^*(X^{(t)})X^{(t)}]= W_1^\top {\mathbb{E}}[\nabla g(W_1X^{(t)})]$ and $ B=[\beta^{(1)},\beta^{(2)},...,\beta^{(T)}]$. Then the diversity assumption implies that $\lambda_r(B)>c\sqrt{T}$. Moreover, using the same concentration analysis in the proof of Theorem~\ref{thm:ReLU:rep}, we have with probability at least $1-d_1^{-3}$, $$ \|\beta^{(t)}-\hat\beta^{(t)}\|\le \sqrt{\frac{d_1}{n}}. $$ It follows that with probability at least $1-Td_1^{-3}$, $$ \|B-\hat B\|_F\le \sqrt{\frac{d_1T}{n}}. $$ In the following, we provide an upper bound on $\|B-\hat B\|_{2}$. Recall that $\hat\beta^{(t)}=(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iY^{(t)}_i)$. We decompose $\hat\beta^{(t)}-\beta^{(t)}$ by \begin{align*} \hat\beta^{(t)}-\beta^{(t)}=&(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iY^{(t)}_i)-(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}]\\ +&(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}]-\Sigma_{X^{(t)}}^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}]. \end{align*} Since $ \|B-\hat B\|=\sup_{\|u\|,\|v\|=1}u^\top(B-\hat B)v, $ we then proceed to derive the concentration inequality for $u^\top(B-\hat B)v$ for any given $u\in{\mathbb R}^d$, $v\in{\mathbb R}^T$ satisfying $\|u\|,\|v\|=1$, \begin{align*} u^\top(B-\hat B)v=&\sum_{t=1}^T v_t u^\top((\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iY^{(t)}_i)-(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}])\\ +&\sum_{t=1}^Tv_t u^\top((\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}]-\Sigma_{X^{(t)}}^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}]). \end{align*} Since we have with probability at least $1-Td_1^{-3}$, $\lambda_{\min}(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)\ge c-\sqrt\frac{d}{n}$ holds for all $t\in[T]$, implying that $$ \|(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}u\|\le C, \text{ for all } t\in[T]. $$ Then, using Berstein's inequality, we have with probability at least $1-\delta$, $$ |\sum_{t=1}^T v_t u^\top((\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iY^{(t)}_i)-(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}])|\le C' \sqrt\frac{\log(1/\delta)}{n}. $$ Similarly, for the second term, using the fact that $$ (\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}-\Sigma_{X^{(t)}}^{-1}=(\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}((\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)-\Sigma_{X^{(t)}})\Sigma_{X^{(t)}}^{-1}, $$ and using Bernstein's inequality again, we obtain with probability at least $1-\delta$, $$ |\sum_{t=1}^Tv_t u^\top((\frac{1}{n}\sum_{i=1}^n X^{(t)}_iX^{(t)\top}_i)^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}]-\Sigma_{X^{(t)}}^{-1}{\mathbb{E}}[X^{(t)}Y^{(t)}])|\le C \sqrt\frac{\log(1/\delta)}{n}. $$ Combining these two pieces, we have that for any given $u\in{\mathbb R}^d$, $v\in{\mathbb R}^T$ satisfying $\|u\|,\|v\|=1$, we have $$ {\mathbb{P}}(u^T(\hat B-B)v)>C\sqrt\frac{\log(1/\delta)}{n})\le 2\delta. $$ Then we use the $\epsilon$-net argument \cite{vershynin2018high}, and we obtain that with probability at least $1-T^{-1}-d_1^{-1}-Td_1^{-3}$, $$ \|B-\hat B\|_{}\le C \sqrt{\frac{d_1+T}{n}}. $$ We then invoke the following lemma. \begin{Lemma}[A variant of Davis–Kahan Theorem \cite{yu2015useful}]\label{lm:dk} Assume $\min\{T,d\}>r$. For simplicity, we denote $\hat{\sigma}_1\ge \hat{\sigma}_2\ge \cdots \ge \hat{\sigma}_r$ as the top largest $r$ singular values of $\hat B$ and $\sigma_1\ge \sigma_2\ge \cdots \ge \sigma_r$ as the top largest $r$ singular values of $B$. Let $W_1^\top=(v_1,\cdots,v_r)$ be the orthonormal matrix consists of left singular vectors corresponding to $\{\sigma_i\}_{i=1}^r$ and $\hat W_1^{\top}=(\hat v_1,\cdots,\hat v_r)$ be the orthonormal matrix consists of left singular vectors corresponding to $\{\hat \sigma_i\}_{i=1}^r$. Then, there exists an orthogonal matrix ${O}\in {\mathbb R}^{r\times r}$, such that $$\|{O}\hat{W_1}-W_1\|_F\lesssim \frac{(2\sigma_1+\|\hat{B}-B\|_{})\min \{\sqrt{r}\|\hat{B}-B\|_{},\|\hat{B}-B\|_{F}\}}{\sigma^2_{r}}.$$ \end{Lemma} Plugging in the previously derived upper bound on $\|\hat B-B\|$ and $\|\hat B-B\|_F$, we can then have with probability $1-o(1)$, \begin{align*}\|{O}\hat{W_1}-W_1\|_F\lesssim& \frac{(2\sigma_1+\|\hat{B}-B\|_{})\min \{\sqrt{r}\|\hat{B}-B\|_{},\|\hat{B}-B\|_{F}\}}{\sigma^2_{r}}\\ \le& C \sqrt{\frac{r(d_1+T)}{nT}}. \end{align*} \end{proof} \paragraph{Concept shift.} Now we consider the concept shift setting. In this setting, where the conditional distribution on $Y$ given $X$ varies across source tasks, we assume that in the $t$-th source task, $t \in [T]$, we observe $n$ $i.i.d.$ samples from the model \begin{equation}\label{eq:model:transfer2} p_t^*(x)=\Pr[Y^{(t)}=1\mid X^{(t)}=x]=W_k^{(t)}(\sigma(W^{(t)}_{k-1}(\sigma(...\sigma(W_1 x+b^{(t)}_1))+b^{(t)}_{k-2})+b^{(t)}_{k-1}):=g_t(W_1 x), \end{equation} where $x\in\mathbb{R}^{d_1}$, $W_1\in\mathbb{R}^{r\times d_1}$, $W^{(t)}_2\in\mathbb{R}^{d_2\times r}, W^{(t)}_j\in\mathbb{R}^{d_j\times d_{j-1}}$ for $j=3,...,k-1$, $W^{(t)}_k\in\mathbb{R}^{1\times d_{k-1}}$, $b^{(t)}_1\in\mathbb{R}^r, b^{(t)}_k\in\mathbb{R}^{d_k}$, and $\sigma(\cdot)$ is a general activation function. We can then use the exactly same method as described for the covariate shift setting to learn $W_1$. In this setting, the theoretical derivation would require a different but similar diversity assumption. The new diversity assumption we need here assumes that the $T$ conditional distributions $\mathbb{P}(Y_i^{(t)}\mid X_i^{(t)})$ are diverse enough, or formally speaking, the $r$-th largest singular value $\lambda_{r}(\tilde M\tilde M^\top/T)>c$ for some universal constant $c>0$, where $\tilde M=[\tilde m_1,...,\tilde m_T]$, $\tilde m_t={\mathbb{E}}_{X}[\nabla g_t(W_1X)]$. {Here, as defined in \eqref{eq:model:transfer2}, $g_t(u) =W_k^{(t)}(\sigma(W^{(t)}_{k-1}(\sigma(...\sigma(u+b^{(t)}_1))+b^{(t)}_{k-2})+b^{(t)}_{k-1})$, for $u\in\mathbb{R}^{r}$.} \begin{Theorem}\label{thm:sigmoid:rep:transfer2} Suppose for the $t$-th task, $X_i^{(t)}$'s are i.i.d.\,drawn from a Gaussian distribution $N_{d_1}(0,\Sigma_{X})$. We also assume $c_1\le\lambda_{\min}(\Sigma_{X})\le\lambda_{\max}(\Sigma_{X})\le c_2$ for some universal constants $c_1,c_2>0$. Moreover, for the function $g_t(\cdot)$ and $\tilde M$ defined in the previous paragraph, we assume $g_t$'s are $L$-Lipschitz with $L<C$ for some constant $C>0$, and $c_1'\le\lambda_{r}(\tilde M\tilde M^\top /T)>\lambda_{\max}(\tilde M\tilde M^\top /T)\le c_2'$ for some universal constants $c_1',c_2'>0$. Suppose $T=O(d_1^2)$. Letting $h(x)=O W_1 x$ where $O=\arg\min_{O\in\mathcal{O}_{r\times r}}\| OW_1-\hat W_1\|_F$, we then have with probability at least $1-o(1)$, $$ \mathbb{E}_{X}\|\hat h(X)-h(X)\|^2=O({\frac{r(d_1+T)}{nT}}). $$ \end{Theorem} \begin{proof} The proof is quite similar to that of Theorem~\ref{thm:sigmoid:rep:transfer}. We again begin by using Stein's identity (Lemma~\ref{lm:stein}) to obtain $$ {\mathbb{E}}[p^*(X^{(t)})X^{(t)}]=\Sigma_{X} W_1^\top {\mathbb{E}}[\nabla g_t(W_1X^{(t)})]. $$ We denote $\beta^{(t)}=\Sigma_{X}^{-1}{\mathbb{E}}[p^*(X^{(t)})X^{(t)}]= W_1^\top {\mathbb{E}}[\nabla g_t(W_1X^{(t)})]$ and $ B=[\beta^{(1)},\beta^{(2)},...,\beta^{(T)}]$. Then the diversity assumption implies that $\lambda_r(B)>c\sqrt{T}$. We can also see that $W_1^\top$ is the left top-$r$ singular vectors of $B$. The rest of the proof is essentially the same to the proof of Theorem~\ref{thm:sigmoid:rep:transfer}. \end{proof} \section{The Power of Our Approach} \label{sec: benefit} In this Section we give two nontrivial examples of a data generation model for which, by using a neural net of a given class $\mathcal C$, together with training data, we can solve the scaffolding{} set problem for $p^*$ even though $p^*$ itself cannot be computed by any neural net in~$\mathcal C$. In the first example, we show that for any $k$-layer homogeneous neural network with bounded parameters ($k\in \mathbb{N}$), there exists $p^*$ that cannot be approximated well by any $k$-layer neural network in that family, but there exists a $k$-layer neural network in that family, for which, if we apply the Scaffolding{} Set algorithm using the mapping defined by any depth~$j$ prefix, $j=1,\cdots, k-1$, together with sufficient training data, we can recover $p^*$ well. In addition, when $j=1$, the representation mapping $\hat{h}$ can be found using the method of Section~\ref{sec: learning h}. {The second example is based on a result of Eldan and Shamir~\cite{eldan2016power} separating the computational power of depth~2 neural networks of polynomial (in the data dimension $d$) width and depth~3 networks of polynomial width. In particular, we adapt their construction to obtain a specific $p^*$ that can be expressed by a three-layer neural network of width polynomial in~$d$, but which cannot be approximated by any two-layer neural network of sub-exponential width.} {As a result, if ${\cal C}$ is a family of two-layer neural networks of moderate width, we cannot train any neural network in ${\cal C}$ to approximate $p^*$. In contrast, using the Meta-Algorithm with input $\hat h$ being the first layer of a specific two-layer neural network of only polynomial width, we obtain a predictor that approximates $p^*$ very well. } {These examples demonstrate that, while neural networks in ${\cal C}$ are insufficiently powerful and cannot approximate a specific $p^*$ well, the Scaffolding{} Set algorithm can nonetheless leverage the partial structure recovered by a specific neural network in ${\cal C}$ to construct sets leading, via multi-calibration, to a good estimator of $p^*$.} \subsection{Example of $k$-layer homogeneous neural networks} Fix an input dimension $d$ and consider the class $\mathcal C$ of neural nets of input dimension $d$ and depth $k$ of the following form: $f_k(x)=\sum_{i=1}^l w_{i}^\top \sigma(\phi_{k-1}(x))$, where $\sigma$ is the ReLU function, $w_i \in {\mathbb R}^l$, $\phi_{k-1}(x)=A_{k-1}\sigma(A_{k-2}\sigma(\cdots\sigma(A_1x)))$ is a homogeneous neural network, and $A_i\in{\mathbb R}^{l_i\times l_{i-1}}$ for $i=2,\cdots, k-2$ and $A_1\in{\mathbb R}^{l_1\times d}$, $A_{k-1}\in{\mathbb R}^{l\times l_{k-2}}$. In addition, all the parameters are bounded by a universal constant $C>0$, for instance, all the entries of the matrices $A_i$, $k=1,\dots,k$, belong to $[-C,C]$. \begin{Remark} Note that $f^*$ is a $k$-layer neural network, where its first $k-1$ layers belong to the same class as the first $k-1$ layers of $f_{k}$. However, the last layer of $f^*$ does not belong to the class of the last layer of $f_k$. \end{Remark} {The next theorem shows the existence of a $p^*$ that cannot be approximated well by any neural net in ${\cal C}$; however, the output of the $(k-1)$-th layer of a specific neural network in ${\cal C}$ provides a low-dimensional representation mapping $\hat h$ that, when given as input to the Meta-Algorithm, recovers $p^*$ very well.} \begin{Theorem}\label{thm:k layer} There exists a universal constant $c>0$, a distribution ${\cal D}$ on $\mathbb{R}^d$ that is sub-Gaussian and has positive density on a compact support, and a probability function $p^*: \mathbb{R}^d \rightarrow [0,1]$ of the form $$p^*(x) = f^*(x),$$ where $f^*(x)=w^{*\top}\sigma (\phi^*_{k-1}(x)),$ and $\phi_{k-1}^*(x)=A^*_{k-1}\sigma(A^*_{k-2}\sigma(\cdots\sigma(A^*_1x)))$ is a realization of the architecture of $k-1$ layer of the homogeneous ReLU neural network $\phi_{k-1}(x)$ with parameters bounded in $[-C,C]$ and $w^*$ is a vector with $\ell_2$-norm equals to $2Cl^{1.5}$, such that for any $f_k(x)$, $$\mathbb{E}_{X\sim {\cal D}}|p^*(X)- f_k(X)|^2\ge c .$$ Moreover, assume $k< C_1$ for a universal constant $C_1>0$, and suppose we apply the Scaffolding{} Set Algorithm to input $\hat h$ satisfying Assumption~\ref{assumption on h} with respect to $h(x)=A^*_{i}\sigma(A^*_{i-1}\sigma(\cdots\sigma(A^*_1x)))$, where $i=1,\cdots,k-1$ (when $i=1$, $h(x)=\sigma(A^*_1x)$) to obtain a collection of sets $\{S^{(\hat{h})}_k\}$ Then for any $\hat p$ that is $\alpha_n$-multi-calibrated with respect to $\{S^{(\hat{h})}_k\}$, and $\forall \delta>0$, if the sample size $n=\Omega(poly( l, 1/\delta))$, we have $$\mathbb{E}_{X\sim {\cal D}}|p^*(X)- \hat{p}(X)|^2\le \delta^2+ \upsilon e_{h}^2+\alpha_n^2,$$ where $\upsilon =O(poly(l))$. \end{Theorem} \begin{proof} Let ${\mathbb R}_C$ denote the interval ${\mathbb R}\cap [-C,C]$. Let ${\cal F}_{k-1}$ denote the class of functions computable by neural nets of the form $${\cal F}_{k-1} = \{\phi(x)|\phi(x)=A_{k-1}\sigma(A_{k-2}\sigma(\cdots\sigma(A_1x))), A_i\in{\mathbb R}_C^{l\times l}~\text{ for}~ i=2,\cdots, k-1~ \text{and\;} A_1\in{\mathbb R}_C^{l\times d}\}.$$ For all $x\in\mathbb{R}^d$, we define $$\phi^{(x)}_{k-1}= \mathop{\rm arg\max}_{\phi\in {\cal F}_{k-1}} \|\sigma(\phi(x))\|.$$ Since all the parameters are bounded, by continuity of $\phi$, the maximum can be achieved. If there are multiple maximizers, we can arbitrarily choose one. Since ${\cal F}_{k-1}$ is a collection of functions computable by homogeneous neural networks, we know that for any given $\lambda>0$ and all $x \in \mathbb{R}^d$, \begin{equation}\label{eq: linearity} \mathop{\rm arg\max}_{\phi\in {\cal F}_{k-1}} \|\sigma(\phi(x))\|=\mathop{\rm arg\max}_{\phi\in {\cal F}_{k-1}} \|\sigma(\phi(\lambda x))\| \end{equation} Thus\footnote{Equation~\ref{eq: linearity} is where we use the fact that these are ReLU networks.}, for any constant $a > 0$, we can choose $x^*$ such that $\|\sigma(\phi^{(x^*)}_{k-1}(x^*))\|=a$. Specifically, we choose $x^*$, such that $\|\sigma(\phi^{(x^*)}_{k-1}(x^*))\|=c_0l^{-1.5}$, for a constant $c_0$ that we will later specify and denote $\sigma(\phi^{(x^*)}_{k-1}(\cdot))$ simply by $\sigma(\phi^*_{k-1}(\cdot))$. Next, notice that for any $f_k$ and $x$, we have $$\|f_k(x)\|\le Cl^{3/2}\|\sigma(\phi^{(x)}_{k-1}(x))\|.$$ Let us choose $\lambda = 2Cl^{3/2}$ and set $w^*= \lambda\sigma( \phi^*_{k-1}(x^*))/\|\sigma(\phi^*_{k-1}(x^*))\|$. Now, we can choose the distribution ${\cal D}$ on $\mathbb{R}^d$ so that $\phi^*_{k-1}(\cdot)$ is uniformly distributed among $\{y:\|y-\sigma( \phi^*_{k-1}(x^*))\|\le \epsilon \|\sigma(\phi^*_{k-1}(x^*))\|\}$ for some small enough real number $\epsilon\le 0.05$. By the continuity of the functions in ${\cal F}_{k-1}$ and the activation function $\sigma$, we know such distribution must exist and can make it has bounded support, thus sub-Gaussian. \iffalse \begin{align*} \mathbb{E}_{x\sim \mathcal D}(p^*(x)-p_k(x))^2&{\ge}\left |\frac{e^{2Cl^{3/2}\|\phi^*_{k-1}(x^*))\|-2C\epsilon l^{3/2}\|\phi^*_{k-1}(x^*))\|}}{1+e^{2Cl^{3/2}\|\phi^*_{k-1}(x^*))\|-2C\epsilon l^{3/2}\|\phi^*_{k-1}(x^*))\|}} -\frac{e^{Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}{1+e^{Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}\right|^2 \\ &\ge\left |\frac{e^{1.9Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}{1+e^{1.9Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}} -\frac{e^{Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}{1+e^{Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}\right|^2 \\ &= \frac{e^{2cCl^{3/2}\|\phi^*_{k-1}(x^*))\|}}{(1+e^{cCl^{3/2}\|\phi^*_{k-1}(x^*))\|})^4}\\ &\ge \frac{e^{2c C}}{(1+e^{cC})^4}, \end{align*} for some $c\in[1,1.9]$, which further leads to a lower bound $\frac{e^{2C'}}{(1+e^{C'})^4}$ for some universal constant $C'$. \fi Recall that we chose $x^*$ such that $\|\sigma(\phi^{(x^*)}_{k-1}(x^*))\|=c_0l^{-1.5}$. We therefore have \begin{align*} \mathbb{E}_{x\sim \mathcal D}(p^*(x)-p_k(x))^2&{\ge}\left |{[2Cl^{3/2}\|\phi^*_{k-1}(x^*))\|-2C\epsilon l^{3/2}\|\phi^*_{k-1}(x^*))\|]} -{{Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}\right|^2 \\ &\ge\left |{{1.9Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}} -{{Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}\right|^2 \\ &= |{{0.9Cl^{3/2}\|\phi^*_{k-1}(x^*))\|}}|^2\\ &\ge0.81 c_0^2C^2, \end{align*} Choosing $c_0<1/(3C)$, we then have over the distribution $\mathcal D$ defined the same way as before, $p^*(x)\in(0,1)$, and $\mathbb{E}_x(p^*(x)-p_k(x))^2\ge c$. Notice the Lipchitz constant of the function is bounded by $2C l^{3/2}$. The rest of the theorem follows directly by applying Theorem \ref{thm:mc wrt S}. \end{proof} According to the above theorem, if $e_{h}$ and $\alpha_n$ vanish fast enough when $n$ goes to infinity, with moderately large sample size, the {Meta-Algorithm }(Algorithm~\ref{alg:full}) can be used to obtain an estimator $\hat{p}$, based on the output of some strict prefix of the network {\it i.e.}, the output of layer $k-1$ or some earlier layer, that is close to $p^*$, even though, in contrast, no $k$-layer neural network can approximate $p^*$ very well. A direct implication is the following corollary. We present informally for brevity. \begin{Corollary}[Informal] If we only consider networks of constant depth then we can obtain a suitable single-layer $\hat h$ via Theorem~\ref{thm:ReLU:rep} such that multi-calibration with respect to the output of the Scaffolding{} Set algorithm, applied to this $\hat h$ together with a training set of moderate size, yields a good approximation to~$p^*$. This holds despite the fact that no depth~$k$ network can approximate~$p^*$. \end{Corollary} \subsection{Example of inhomogeneous shallow neural networks} Let us briefly introduce the structure of neural networks we consider in this Section. Let $d$ be the input dimension. \begin{itemize} \item Two-layer neural network of width $l$: $x\mapsto \sum_{i=1}^l v_i\sigma(w_i^\top x +b_i)$, where $v_i\in {\mathbb R}$ and $w_i \in {\mathbb R}^d$. \item Three-layer neural network of width $l$: $x\mapsto \sum_{i=1}^l u_i\sigma \left(\sum_{j=1}^l v_{i,j}\sigma(w_{i,j}^\top x +b_{i,j})+c_i\right )$, where $u_i,c_i,b_{i,j}\in {\mathbb R}$, $w_{i,j}\in {\mathbb R}^d$. \end{itemize} The results in this Section apply to the case in which $\sigma$ is either the ReLU function $\sigma(x) = \max\{0,x\}$ or the Sigmoid function $\sigma(x) = \log(1+e^x)$ . The following theorem builds on a result of Eldan and Shamir, that separates the power of polynomial-width ReLU neural nets of depth~2 and depth~3. Specifically, they demonstrated the existence of a function $f$ and a distribution $\mathcal D$ such that $f$ is computable by an inhomogeneous ReLU network of polynomial width and depth~3, but cannot be approximated, in expectation over $\mathcal D$, by any polynomial-width ReLU network of depth~2. \begin{Theorem}\label{thm:2vs3} There exists a distribution ${\cal D}$ on $\mathbb{R}^d$ and constants $C,c, c'$, such that the following properties hold. Suppose the input dimension $d>C$, there exists a universal constant $\tilde{c}>0$ such that for any $\delta\in(0,1)$, there exists a probability function $p^*(x)= \sum_{i=1}^{l^*} u^*_i\sigma \Big(\sum_{i=1}^{l^*} v^*_{i,j}\sigma(w_{i,j}^{*\top} x +b^*_{i,j})+c^*_i\Big)$, with $l^* \le 64 c'/\tilde{c} d^5+1$ so that the following holds. \begin{itemize} \item[1.] If $l$ is an integer satisfying $l\le ce^{cd}$, then for any two-layer neural network $f$, \text{i.e.} $f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$ we have that $$\mathbb{E}_{x\sim {\cal D}}|f(x)-p^*(x)|^2\ge \tilde{c}^2/4.$$ \item[2.] However, if we use our method to build sets upon $\hat{h}$ satisfying learnablility assumption 4 (will modify later for assumption part) for $h=\sum_{j=1}^l v^*_{i,j}\sigma(w_{i,j}^{*\top} x +b^*_{i,j}),$ we can have that for any $\hat{p}$ that is $\alpha_n$-multi-calibrated on $\{S^{(\hat{h})}_k\}$, and if sample size $n=\Omega(poly( d,l^*,1/\delta))$, we have that $$E_{x\sim {\cal D}}|p^*(x)- \hat{p}(x)|^2\le \delta^2+ \upsilon e_{h}^{2}+\alpha_n^2,$$ where $\upsilon =O(poly(d,l^*,1/\tilde{c}))$. \end{itemize} \end{Theorem} \begin{proof} In Proposition $13$ and $17$ in~\cite{eldan2016power}, Eldan et.al.\,state when the activation function is ReLU or Sigmoid activation function, there exists a function $g(x)$ computable by a narrow three-layer neural network that cannot be approximated by a 2-layer neural net with width that is polynomial regarding input dimension. More formally, there exists a distribution ${\cal D}$ and constants $C,c, c'>0$, such that the following properties hold. Suppose the input dimension $d>C$, there exists a constant $\tilde{c}>0$ such that for any $\eta\in(0,1)$, there exists a three-layer neural network $g$, i.e. $$g=\sum_{i=1}^{l_g} u^g_i\sigma \left(\sum_{j=1}^{l_g} v^g_{i,j}\sigma(w_{i,j}^{g\top} x +b^g_{i,j})+c^g_i\right )$$ with width $l_g \le 8c'/\eta d^5+1$ so that the following holds. \begin{itemize} \item $g(x)\in [-2,2]$. \item For all integers $l$ satisfying $l\le ce^{cd}$ and any two-layer neural network $f$, \text{i.e.} $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$$ we have $$(\mathbb{E}_{x\sim {\cal D}}|f(x)-g(x)|^2)^{1/2}\ge \tilde{c}-\eta.$$ \item $\sum_{i=1}^{l_g} u^g_i\sigma \left(x+c^g_i\right )$ is $\gamma$-Lipschitz as a function of $x$, where $\gamma=O(poly(d,l^*,1/\tilde{c}))$. \end{itemize} Note that $g$ is already bounded in $[-2,2]$, thus we only need to prove that $\frac{1}{4}g+\frac{1}{2}$ shares the same properties as $g$, then we can take $$p^*=\frac{1}{4}g+\frac{1}{2},$$ since $\frac{1}{4}\tilde{g}+\frac{1}{2}\in [0,1]$. Consider $l$ to be an integer satisfying $l\le ce^{cd}$. We focus on studying any two-layer neural network $f$ with width $l-1$, \text{i.e.} $$f(x)=\sum_{i=1}^{l-1} v_i\sigma(w_i^\top x +b_i).$$ Let us denote $L_2({\cal D})$ as the $L_2$ norm regarding the distribution ${\cal D}$. By directly plugging in, we have \begin{align*} \|f-p^*\|_{L_2({\cal D})} = \frac{1}{4}\|4f-2-g\|_{L_2({\cal D})}. \end{align*} Notice $4f-2$ can be expressed by a two-layer neural network with width $l$. For instance, for ReLU activation function, we can scale $v_i$'s for $i=1,\cdots l$, by $4$ and add one single node for the extra $2$ by taking $v_l=-1, w_l=0, b_l=2$. For Sigmoid function, the transformation is similar Thus by the inapproximability of $l$-width two-layer neural network, we can obtain $$ \|f-p^*\|_{L_2({\cal D})} = \frac{1}{4}\|4f-2-g\|_{L_2({\cal D})}\ge \frac{1}{4}(\tilde{c}-\eta).$$ If we take $d$ to be large enough such that $ce^{cd}-1>(c/2)e^{cd/2}$, then we know for any $l'\le (c/2)e^{cd/2}$, we must have $l'+1\le ce^{cd}$ and any two layer neural network of width $l'$ $$f(x)=\sum_{i=1}^{l'} v_i\sigma(w_i^\top x +b_i),$$ then by the inapproximability of $l'+1$-width two-layer neural network, we have \begin{align*} \|f-p^*\|_{L_2({\cal D})} \ge \frac{1}{4}(\tilde{c}-\eta). \end{align*} Let us take $\eta=\tilde{c}/2$, the proof of bullet point $1$ is complete. The proof of bullet point $2$ is a straightfoward application of Theorem \ref{thm:mc wrt S}. \end{proof} According to the above theorem, if $e_{h}$ and $\alpha_n$ vanish fast enough when $n$ goes to infinity, with moderately large sample size, using the {Meta-Algorithm (Algorithm~\ref{alg:full}) we can obtain an estimator $\hat{p}$ that is close to $p^*$ while using any two-layer neural network cannot approximate $p^*$ very well unless the width is very large. \begin{Corollary}\label{cor:2vs3} Under the same settings as in Theorem \ref{thm:2vs3}. For any two-layer neural network $f$ that is not wide enough (unless is exponentially wide with respect to input dimension), \text{i.e.} $f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$ there exists a constant $c''$, such that $$\mathbb{E}_{x\sim N(0,I_d)}|f(x)-p^*(x)|^2\ge c''.$$ \end{Corollary} \begin{Remark} The conditions of Corollary ~\ref{cor:2vs3} satisfies the conditions of Theorem~\ref{thm:sigmoid:rep}, where we obtain an $\hat h$ and the resulting $\hat p$ satisfies $$ \mathbb{E}_{x\in N(0,I_d)}|f(x)-p^*(x)|^2\lesssim (\frac{\log n}{n^{1/3}})^2+\alpha_n^2.$$ When $n$ is large enough, using our method can obtain a better estimation of $p^*$ than directly using two neural networks, which are not wide enough. Following our proof, we can further extend the results of \cite{eldan2016power} to a wide class of density as long as that density $p$ is lower bounded on a large enough but bounded support that contains a certain range. \end{Remark} \section{More Proofs} \subsection{Proof of Lemma~\ref{lem:relu}} Recall that $X$ is symmetric, so $W_1 X$ is symmetric. As a result, we have \begin{align*} {\mathbb{E}}[YX]=&{\mathbb{E}}[p^*(X)X]={\mathbb{E}}[q(\sigma(W_1X))X]\\ =&\frac{1}{2}{\mathbb{E}}[q(\sigma(W_1X))X\mid W_1 X\ge 0]+\frac{1}{2}{\mathbb{E}}[q(\sigma(W_1X))X\mid W_1X<0]\\ =&\frac{1}{2}{\mathbb{E}}[q(\sigma(W_1X))X\mid W_1 X\ge 0]\\ =&\frac{1}{2}{\mathbb{E}}[q(1)XX^\top W_1^\top\mid W_1 X\ge 0]\\ =&\frac{1}{2}{\mathbb{E}}[q(1)XX^\top W_1^\top\mid W_1 X< 0]\\ =&\frac{1}{2}{\mathbb{E}}[q(1)XX^\top W_1^\top]=\frac{1}{2} q(1)\cdot\Sigma_XW_1^\top. \end{align*} \iffalse We first claim that for $p^*=\frac{1}{2}\tilde{g}+\frac{1}{2}$, there exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$ and let $l$ be an integer satisfying $l\le ce^{cd}$ for a universal constant $c$. Let $f$ be any two-layer neural network, \text{i.e.} $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i),$$ then, $$\mathbb{E}_{x\sim {\cal D}_x}|f(x)-p^*(x)|^2\ge \tilde{c}^2/\alpha^2$$ for a universal constant $\tilde{c}$. If not, for any $\varepsilon>0$, there exists a two-layer neural network $f_{\varepsilon}$ with $l\le ce^{cd}$, such that $$\mathbb{E}_{x\sim {\cal D}_x}|f_\varepsilon(x)-p^*(x)|^2\le \varepsilon^2.$$ Then, there must exist $f'_{\varepsilon}(x)$ with width at most $ce^{cd}+1$ such that $$\mathbb{E}_{x\sim {\cal D}_x}|f'_\varepsilon(x)-\tilde{g}(x)|^2\le 4\varepsilon^2,$$ since we can rescale the weights and bias and add at most one node to obtain $f'_\varepsilon(x)=2f_{\varepsilon}(x)-1$. Thus, for any $\varepsilon>0$, there exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$ and let $l$ be an integer satisfying $l\le 2ce^{2cd}$ for a universal constant $c$. there exists $f'_\varepsilon$, \text{i.e.} $$\mathbb{E}_{x\sim {\cal D}_x}|f'_\varepsilon(x)-\tilde{g}(x)|^2\le 4\varepsilon^2,$$ which contradicts. Secondly, notice we only need to add one extra node for the three-layer neural network and rescale the weights and bias so that there exists a universal constant $C>0$ such that the following holds. Suppose the input dimension $d>C$, $\alpha >C$, there exists a three-layer neural network $g'$, with width at most $8c_\sigma C/\delta \alpha^{3}d^5+2$ for a universal constant $c_\sigma$ such that $$\mathbb{E}_{x\sim {\cal D}_x}|\tilde{g}(x)-g'(x)|^2\le (\frac{\sqrt{3}}{\alpha d^{0.25}}+\delta)^2.$$ The proof is complete. \fi \subsection{Proof of Corollary \ref{cor:2vs3}} \paragraph{High-level intuition.} Before presenting our formal proof, we illustrate the high-level idea of \cite{eldan2016power}, and our modification. First, they construct a radial function (only as a function of $\|x\|$) with bounded support, denoted $\tilde{g}$. Then, they present a method to construct a three-layer neural network to approximate $\tilde{g}$. Specifically, they first use linear combinations of neurons to approximate $z\mapsto z^2$. Then, adding these combinations together, one for each coordinate, one can compute $x\mapsto\|x\|^2 =\sum_{i=1} x_i^2$ inside any bounded domain. They last layer computes a univariate function of $\|x\|$. Now, for any density function $\varphi^2$, and any candidate function $f$ to approximate $\tilde g$, we evauate the approxiamtion via the $L_2$ distance under the density function $\varphi^2$: $$\int (f-\tilde g)^2\varphi^2 dx =\int (f\varphi-\tilde g\varphi)^2 dx .$$ If the Fourier transformation of $f\varphi-\tilde g\varphi$ exists, then $$\int (f\varphi-\tilde g\varphi)^2 dx=\int (\widehat{f\varphi}-\widehat{\tilde g\varphi})^2dx$$ (here, $\hat{\cdot}$ denotes the Fourier transformation). The heart of the argument by Eldan et.al.is as follows. If $f$ is a two-layer neural network, then the support of $\widehat{f\varphi}$ is a union of tubes of bounded radius passing through the origin, with the number of tubes exactly corresponding to its width (Lemma~\ref{lm:span}). The construction of $\widehat{\tilde g\varphi}$ is radial and has relative large mass in all directions. Thus, to approximate $\widehat{\tilde g\varphi}$ well will require many tubes, which means that $f$ must be very wide. In our construction, we further show that for any not too wide two-layer neural network $f$ and indicator function $I$ for any ball with any radius, $\widehat{fI\varphi}$ also cannot approximate $\widehat{\tilde g \varphi}$ well. Since $\tilde g$ is of bounded support, if we choose the indicator function of ball with large enough radius, then $\tilde g I=g$. Thus, we can show that $\widehat{fI\varphi}$ cannot approximate $\widehat{\tilde g I \varphi}$ well. Thus, no bounded range $f$ can approximate $\tilde g$ well. Finally, we obtain our result by applying Equation \ref{eq:is}. \paragraph{Formal proof.}Now, let us formally prove our statements. We focus on proving the case where the activation function is the ReLU function or Sigmoid function. The two-layer neural network is of the form: $$f(x)=\sum_{i=1}^l v_i\sigma(w_i^\top x +b_i).$$ The form can also be abbreviated as $$f(x)=\sum_{i=1}^lf_i(\langle x,u_i \rangle)$$ for some unit vector $u_i \in {\mathbb R}^d$. We further introduce some notation. Let $B_d$ be the $d$-dimensional ball with unit radius and center $0$. The density function used in \cite{eldan2016power} is $\varphi^2(x)$, where $$\varphi(x)=(\frac{R_d}{\|x\|})^{d/2}J_{d/2}(2\pi R_d\|x\|) ,$$ where for non-negative integer $\alpha$, $J_\alpha$ is the corresponding Bessel function and $R_d = \sqrt{1/\pi}(\Gamma(d/2+1))^{1/d}$. We further denote $$\beta_R(x)=(\frac{R}{\|x\|})^{d/2}J_{d/2}(2\pi R\|x\|).$$ As shown in Lemma $2$ in \cite{eldan2016power}, $\beta_R$ is the Fourier transformation of the indicator function $1\{x\in RB_d\}$ and by duality theory, we have $$\hat{\beta}_R(w)=1\{w\in RB_d\} ,$$ where we use $\hat \cdot$ to denote the Fourier transformation throughout the proof. \textit{Generalized Fourier Transformation}: let ${\mathcal S}$ denote the space of Schwartz functions (functions with super-polynomial decaying values and derivatives) on ${\mathbb R}^d$. A tempered distribution $\mu$ in our context is a continuous linear operator from ${\mathcal S}$ to ${\mathbb R}$. In particular, any measurable function $h:{\mathbb R}^d\mapsto {\mathbb R}$, which satisfies a polynomial growth condition: $$|h(x)|\le C_1(1+\|x\|^{C_2})$$ for universal constants $C_1,C_2>0$, $h$ can be viewed as a tempered distribution defined as $$\psi\mapsto \langle h,\psi\rangle:=\int_{{\mathbb R}^d}h(x)\psi(x)dx,$$ where $\psi\in S$. The Fourier transformation $\hat h$ of a tempered distribution $h$ is also a tempered distribution, and defined as $$\langle\hat h,\psi\rangle:=\langle h,\hat \psi\rangle,$$ where $\hat \psi$ is the Fourier transformation of $\psi$. In addition, we say a tempered distribution $h$ is supported on some subset of ${\mathbb R}^d$, if $\langle h,\psi\rangle=0$ for any function $\psi\in{\mathcal S}$ which vanishes on that subset. Let us define $\tilde{f}_i(x)=f_i(\langle x,u_i\rangle)$. We define the following lemma. \begin{Lemma}\label{lm:span} Let $f=\sum_{i=1}^lf_i(\langle x,u_i \rangle)$ be a function such that $f1\{RB_d\}\varphi\in L_2$, and $$f_i(x)\le C(1+\|x\|^{\alpha})$$ for constants $C,\alpha>0$. Then, $$Supp(\reallywidehat{f1\{RB_d\}\varphi}) \subset \cup_{i=1}^l(Span\{u_i\}+R_dB_d).$$ \end{Lemma} \begin{Remark} The choice of ReLU and Sigmoid activation function satisfies the polynomial growth condition for $f_i$. Meanwhile, this lemma suggests that $Supp(\reallywidehat{f1\{RB_d\}\varphi})$ is contained in a union of ``tubes" passing through the origin. We can see that the number of tubes is exactly the width $l$, and this lemma suggests the limitation of the approximation power of two-layer neural networks. \end{Remark} \begin{proof} First, we notice that $\beta_R\in L_2$ and $\psi\in L_1$ for any $\psi\in {\mathcal S}$, then by convolution theorem, we have that $$\widehat{\beta_R\star\psi}=\hat{\beta}_R\hat{\psi},$$ where $\star$ is the convolution notation. Secondly, we have that \begin{align*} \langle \tilde{f}_i1\{RB_d\}, \hat{\psi}\rangle &=\int \tilde{f}_i(x)1\{x\in RB_d\}\hat{\psi}(x)dx\\ &=\int \tilde{f}_i(x)\hat{\beta}_R(x)\hat{\psi}(x)dx\\ &= \int \tilde{f}_i(x)\widehat{\beta_R\star\psi}(x)dx. \end{align*} By the similar calculation in Claim $2$ in \cite{eldan2016power}, we have that \begin{equation}\label{eq:1} \int_{{\mathbb R}^d}\tilde{f}_i(x)\hat{\gamma}_R(x)dx = \int_{{\mathbb R}} f_i(y)\hat{\gamma}_R(yu_i)dy \end{equation} where $\gamma_R =\beta_R\star\psi$. Next, for every $\psi\in{\mathcal S}$, by definition of generalized Fourier transformation $$\langle\reallywidehat{\tilde{f}_i1\{RB_d\}\varphi},\psi\rangle =\langle \tilde{f}_i1\{RB_d\}, \reallywidehat{1\{R_dB_d\}\star\psi}\rangle.$$ As a result, for $\phi=1\{R_dB_d\}\star\psi$ and any $\psi\in {\mathcal S}$ that vanishes on $Span\{u_i\}+R_dB_d$, then $\phi$ must vanish on $Span(u_i)$. Let $\phi_i(y)=\phi(yu_i)$ \begin{align*} \langle \reallywidehat{\tilde{f}_i1\{RB_d\}\varphi},\psi\rangle&=\langle \tilde{f}_i1\{RB_d\}, \varphi\hat{\psi}\rangle\\ &=\langle \tilde{f}_i1\{RB_d\}, \hat \phi\rangle\\ &= \langle \tilde{f}_i, \hat{\beta}_R\hat \phi\rangle\\ &=\int f_i(y)\widehat{\beta_R\star\phi}(yu_i)dy\quad\text{(by Equation \ref{eq:1})}\\ &= \int f_i(y)1\{|y|\le RVol(B_d)\}\hat\phi (yu_i)dy\\ &=\int f_i(y)1\{|y|\le RVol(B_d)\}\hat{\phi}_i(y) dy\\ &=0. \end{align*} The last equation is due to that by the definition of $\phi_i$, we know that if $\phi$ vanishes on $Span\{u_i\}$, thus $$\phi_i(x)=\phi(xu_i)=0,$$ which results in that $\hat\phi_i$ is a zero function. As a result, since $f(x)=\sum_{i=1}^lf_i(\langle x,u_i \rangle)$ $$Supp(\reallywidehat{f1\{RB_d\}\varphi}) \subset \cup_{i=1}^l(Span\{u_i\}+R_dB_d).$$ Since $f1\{RB_d\}\varphi\in L_2$, the tempered distribution coincides with the standard one, the result follows. \end{proof} Next, we recall the following lemma. \begin{Lemma}[Lemma $9$ in \cite{eldan2016power}] Let $q$ and $w$ be two functions of unit norm in $L_2$. Suppose that $q$ satisfies $$Supp(q)\subset \cup_{i=1}^l(Span\{v_i\}+R_dB_d)$$ for $l\in \mathbb{N}$. Moreover, suppose that $w$ is radial and that $\int_{2R_dB_d} w^2(x)dx\le 1-\delta$ for some $\delta\in[0,1]$. Then, $$\langle q,w\rangle_{L_2}\le 1-\delta/2+l\exp(-cd)$$ where $c>0$ is a universal constant. \end{Lemma} Finally, we consider $\tilde{g}(x)$ defined in Proposition $1$ in \cite{eldan2016power}. And the function $\tilde{g}$ is of bounded support $\cB$, thus, as long as $\cB\subset RB_d$, we have that $$\|f\varphi1\{RB_d\}-\tilde{g}\varphi 1\{RB_d\}\|_{L_2}=\|f\varphi1\{RB_d\}-\tilde{g}\varphi\|_{L_2}$$ Then, let us denote $q=\frac{\reallywidehat{f1\{R_dB_d\}\varphi}}{\|f1\{R_dB_d\}\varphi\|_{L_2}}$ and $w=\frac{\widehat{\tilde{g}\varphi}}{\|\tilde g\varphi\|_{L_2}}$ and by similar proof of Proposition $1$, we have that \begin{align*} \|f\varphi1\{RB_d\}-\tilde{g}\varphi 1\{RB_d\}\|_{L_2}=\|f\varphi1\{RB_d\}-\tilde{g}\varphi\|_{L_2}&=\|\|f1\{R_dB_d\}\varphi\|_{L_2} q-\|\tilde g\varphi\|_{L_2} w\|_{L_2}\\ &\ge \frac{1}{2}\|q-2\|_{L_2}\|\tilde{g}\|\\ &\ge \frac{1}{2}\sqrt{2(1-\langle q,w\rangle_{L_2})}\|\tilde{g}\varphi\|_{L_2}\\ &\ge C_3/\alpha \end{align*} for a universal constant $C_3$, where the last equation is due to Lemma $6$ and $7$ in \cite{eldan2016power}. Recall that by Lemma 10 in \cite{eldan2016power}, $p^*$ constructed in Theorem \ref{thm:2vs3} has a uniform approximation to $\tilde{g}$ in the sense that $$\sup_x|p^*(x)-\tilde g(x)|\le c.$$ for a small constant $c$ (can choose to be smaller than $C_3/(100\alpha))$ Thus, for Gaussian distribution $N(0,I_d)$, we can choose $R$ such that $\cB\subset RB_d$, such that $$\|f\varphi1\{RB_d\}-p^*\varphi 1\{RB_d\}\|_{L_2}\ge \|f\varphi1\{RB_d\}-\tilde{g}\varphi 1\{RB_d\}\|_{L_2}- \|\tilde{g}\varphi1\{RB_d\}-p^*\varphi 1\{RB_d\}\|_{L_2}\ge \frac{99C_3}{100\alpha}$$ Let $\tilde{p}$ denote the density function of Gaussian $N(0,I_d)$. We know that $\sqrt{\tilde{p}}/\varphi\ge C_5$ for a constant $C_5>0$ on $RB_d$ \begin{equation} \label{eq:is} \|f\sqrt{\tilde{p}} 1\{RB_d\}-p^*\sqrt{\tilde{p}} 1\{RB_d\}\|_{L_2}\ge C_5\|f\varphi1\{RB_d\}-p^*\varphi 1\{RB_d\}\|_{L_2}\ge \frac{99C_3C_5}{100\alpha}. \end{equation} The proof is complete.
{'timestamp': '2021-11-18T02:07:08', 'yymm': '2111', 'arxiv_id': '2111.03135', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03135'}
arxiv
\section*{Checklist} \input{sections/appendix} \end{document} \section{Preliminaries} \begin{figure*} [t] \centering \includegraphics[width=.9\textwidth]{figures/B-Pre_Main_Figure.pdf} \caption{Illustration of preference-based RL. Instead of assuming that the environment provides a (hand-engineered) reward, a teacher provides preferences between the agent's behaviors, and the agent uses this feedback in order to learn the desired behavior.} \label{fig:overview} \end{figure*} We consider an agent interacting with an environment in discrete time~\cite{sutton2018reinforcement}. At each timestep $t$, the agent receives a state $\mathbf{s}_t$ from the environment and chooses an action $\mathbf{a}_t$ based on its policy $\pi$. In traditional reinforcement learning, the environment also returns a reward $r (\mathbf{s}_t, \mathbf{a}_t)$ and the goal of agent is to maximize the discounted sum of rewards. However, for many complex domains and tasks, it is difficult to construct a suitable reward function. We consider the preference-based RL framework, where a (human) teacher provides preferences between the agent's behaviors and the agent uses this feedback to perform the task~\citep{preference_drl,ibarz2018preference_demo,pebble,leike2018scalable}. Formally, a segment $\sigma$ is a sequence of observations and actions $\{(\mathbf{s}_{1},\mathbf{a}_{1}), ...,(\mathbf{s}_{H}, \mathbf{a}_{H})\}$. Given a pair of segments $(\sigma^0, \sigma^1)$, a teacher indicates which segment is preferred, i.e., $y = (0,1)~\text{or}~(1,0)$, that the two segments are equally preferred $y=(0.5, 0.5)$, or that two segments are incomparable, i.e., discarding the query. The goal of preference-based RL is to train an agent to perform behaviors desirable to a human teacher using as few queries as possible. \section{B-Pref: Benchmarks environments for preference-based RL} \subsection{Design factors} \label{sec:design} While ideally we would evaluate algorithms’ real-world efficacy using real human feedback, designing a standardized and broadly available benchmark becomes challenging because we do not have ground truth access to the human’s reward function. Instead, we focus on solving a range of existing RL tasks (see Section~\ref{sec:task}) using a simulated human, whose preferences are based on a ground truth reward function. Because simulated human preferences are immediately generated by the ground truth reward, we are able to evaluate the agent quantitatively by measuring the true average return and do more rapid experiments. A major challenge with simulating human input is that real humans are not perfectly rational and will not provide perfect preferences. To alleviate this challenge, we propose to simulate human input using a wide array of irrationalities (see Section~\ref{sec:scripted_teachers}), and measure an algorithm's robustness in handling such input (see Section~\ref{sec:evaluation_metric}). \begin{algorithm}[t] \caption{\texttt{SimTeacher}: Simulated human teachers} \label{alg:scriptedteacher} \begin{algorithmic}[1] \footnotesize \Require Discount factor $\gamma$, rationality constant $\beta$, probability of making a mistake $\epsilon$ \Require Skip threshold $\delta_{\tt skip}$, equal threshold $\delta_{\tt equal}$ \Require Pair of segments $\sigma^0, \sigma^1$ \If{$\max_{i\in\{0,1\}} \sum_t r\left(\mathbf{s}^i_t, \mathbf{a}^i_t\right) < \delta_{\tt skip}$} {\textsc{// Skipping query}} \label{algo:skip} \State $y \leftarrow \emptyset$ \ElsIf{$\big| \sum_t r\left(\mathbf{s}^1_t, \mathbf{a}^1_t\right) - \sum_t r\left(\mathbf{s}^0_t, \mathbf{a}^0_t\right) \big| < \delta_{\tt equal}$} {\textsc{// Equally preferable}} \label{algo:equal} \State $y\leftarrow(0.5, 0.5)$ \ElsIf{$\sigma^0\succ\sigma^1 \sim P[\sigma^0\succ\sigma^1; \beta, \gamma]$} {\textsc{// Sampling preferences from \eqref{eq:bt_model}}} \label{algo:sample} \State $y\leftarrow(1, 0)$ with probability of $1-\epsilon$ \State $y\leftarrow(0, 1)$ otherwise {\textsc{// Making a mistake}} \label{algo:mistake_1} \Else \State $y\leftarrow(0, 1)$ with probability of $1-\epsilon$ \State $y\leftarrow(1, 0)$ otherwise {\textsc{// Making a mistake}} \label{algo:mistake_2} \EndIf \State $\textbf{return} \; y$ \end{algorithmic} \end{algorithm} \subsection{Simulated human teachers} \label{sec:scripted_teachers} We start from a (perfectly rational) deterministic teacher, which generates preferences as follows: \begin{align*} y = \left \{ \begin{array}{lll} (1, 0) & \mbox{If $\sum_{t=1}^{H} r(\mathbf{s}_{t}^0, \mathbf{a}_{t}^0) > \sum_{t=1}^{H} r(\mathbf{s}_{t}^1, \mathbf{a}_{t}^1)$} \vspace{0.05in}\\ (0, 1) & \mbox{otherwise}, \end{array} \right. \end{align*} where $H>0$ is a length of segment $\sigma$ and $r$ is the ground truth reward. We remark that prior works~\citep{preference_drl,ibarz2018preference_demo,pebble} evaluated their methods using this ideal teacher. However, evaluating the performance of preference-based RL only using the ideal teacher is unrealistic because there are many possible irrationalities~\citep{chan2021the, chipman2016oxford} affecting a teacher's preferences (and expression of preferences) in different ways. To design more realistic models of human teachers, we consider a common stochastic model~\citep{biyik2018batch,preference_drl,sadigh2017active} and systematically manipulate its terms and operators (see Algorithm~\ref{alg:scriptedteacher}): {\bf Stochastic preference model}. Because preferences from the human can be noisy, we generate preferences using a stochastic model defined as follows (Line~\ref{algo:sample}): \begin{align} P[\sigma^i\succ\sigma^j; \beta, \gamma] = \frac{\exp\left(\beta \sum_{t=1}^{H} \gamma^{H-t} r(\mathbf{s}_{t}^i, \mathbf{a}_{t}^i)\right)}{\exp \left( \beta \sum_{t=1}^{H} \gamma^{H-t} r(\mathbf{s}_{t}^i, \mathbf{a}_{t}^i)\right) + \exp \left( \beta \sum_{t=1}^{H} \gamma^{H-t} r(\mathbf{s}_{t}^j, \mathbf{a}_{t}^j)\right)}, \label{eq:bt_model} \end{align} where $\gamma \in (0, 1]$ is a discount factor to model myopic behavior, $\beta$ is a rationality constant, and $\sigma^i\succ\sigma^j$ denotes the event that segment $i$ is preferable to segment $j$. This follows the Bradley-Terry model~\citep{bradley1952rank}, which can be interpreted as assuming the probability of preferring a segment depends exponentially on the sum over the segment of an underlying reward. Note that this teacher becomes a perfectly rational and deterministic as $\beta \rightarrow \infty$, whereas $\beta=0$ produces uniformly random choices. {\bf Myopic behavior}. Humans are sometimes myopic (short-sighted), so a human teacher may remember and focus more on the behavior at the end of the clip they watched, for example. We model myopic behavior by introducing a weighted sum of rewards with a discount factor $\gamma$ in \eqref{eq:bt_model}, i.e., $\sum_{t=1}^{H} \gamma^{H-t} r(\mathbf{s}_{t}^i, \mathbf{a}_{t}^i)$, so that our simulated teacher places more weight on recent timesteps. {\bf Skipping queries}. If both segments do not contain a desired behavior, a teacher would like to mark them as incomparable and discard the query. We model this behavior by skipping a query if the sum over the segment of an underlying reward is smaller than skip threshold $\delta_{\tt skip}$, i.e., $\max_{i\in\{0,1\}} \sum_t r\left(\mathbf{s}^i_t, \mathbf{a}^i_t\right) < \delta_{\tt skip}$ (Line~\ref{algo:skip}). {\bf Equally preferable}. If the two segments are equally good, instead of selecting one segment as preferable, a teacher would like to mark the segments as equally preferable. Motivated by this, we provide an uniform distribution $(0.5, 0.5)$ as a response (Line~\ref{algo:equal}) if both segments have similar sum of rewards, i.e., $\big| \sum_t r\left(\mathbf{s}^1_t, \mathbf{a}^1_t\right) - \sum_t r\left(\mathbf{s}^0_t, \mathbf{a}^0_t\right) \big| < \delta_{\tt equal}$. {\bf Making a mistake}. Humans can make accidental errors when they respond. To reflect this, we flip the preference with probability of $\epsilon$ (Line~\ref{algo:mistake_1} and Line~\ref{algo:mistake_2}). \subsection{Evaluation metrics} \label{sec:evaluation_metric} We evaluate two key properties of preference-based RL: {\em performance of the RL agent under a fixed budget of feedback} and {\em robustness to potential irrationalities}. Because the simulated human teacher’s preferences are generated by a ground truth reward, we measure the true average return of trained agents as evaluation metric. To facilitate comparison across different RL algorithms, we normalize returns with respect to the baseline of RL training using the ground truth reward: \begin{align*} \texttt{Normalized returns} = \frac{\texttt{Average returns of preference-based RL}}{\texttt{Average returns of RL with ground truth reward}}. \end{align*} To evaluate the feedback-efficiency of preference-based RL algorithms, we compare normalized returns by varying the maximum budget of queries. To evaluate the robustness, we evaluate against the following simulated human teachers with different properties: \begin{itemize} [leftmargin=8mm] \setlength\itemsep{0.05em} \item Oracle: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \epsilon=0, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \item Stoc: \texttt{SimTeacher}$\left(\mybox{$\beta=1$}, \gamma=1, \epsilon=0, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \item Mistake: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \mybox{$\epsilon=0.1$}, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \item Skip: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \epsilon=0, \mybox{$\delta_{\tt skip}>0$}, \delta_{\tt equal}=0\right)$ \item Equal: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \epsilon=0, \delta_{\tt skip}=0, \mybox{$\delta_{\tt equal}>0$}\right)$ \item Myopic: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \mybox{$\gamma=0.9$}, \epsilon=0, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \end{itemize} In our evaluations, we consider one modification (i.e., irrationality) to the oracle teacher at a time, which allows us to isolate the individual effects. While each individually may not exactly model real human behavior, it would be straightforward to use our benchmark to create more complex teachers that combine multiple irrationalities. \subsection{Tasks} \label{sec:task} We consider two locomotion tasks (Walker-walk and Quadruped-walk) from DeepMind Control Suite (DMControl)~\citep{dmcontrol_old,dmcontrol_new} and two robotic manipulation tasks (Button Press and Sweep Into) from Meta-world~\citep{yu2020meta}. We focus on learning from the proprioceptive inputs and dense rewards because learning from visual observations and sparse rewards can cause additional issues, such as representation learning~\citep{laskin2020reinforcement,schwarzer2021dataefficient,srinivas2020curl,stooke2020decoupling,yarats2021image} and exploration~\citep{seo2021state}. However, we think it is an interesting and important direction for future work to consider visual observations and sparse rewards. \section{B-Pref: Algorithmic baselines for preference-based RL} Throughout this paper, we mainly focus on two of the most prominent preference-based RL algorithms~\citep{preference_drl,pebble}, which involve reward learning from preferences. Formally, a policy $\pi_\phi$ and reward function $\widehat{\reward}_\psi$ are updated as follows (see Algorithm~\ref{alg:overview} in the supplementary material): \begin{itemize} [leftmargin=8mm] \setlength\itemsep{0.1em} \item {\em Step 1 (agent learning)}: The policy $\pi_\phi$ interacts with environment to collect experiences and we update it using existing RL algorithms to maximize the sum of the learned rewards $\widehat{\reward}_\psi$. \item {\em Step 2 (reward learning)}: We optimize the reward function $\widehat{\reward}_\psi$ via supervised learning based on the feedback received from a teacher. \item Repeat {\em Step 1} and {\em Step 2}. \end{itemize} \subsection{Deep reinforcement learning from human preferences} In order to incorporate human preferences into deep RL, \citet{preference_drl} proposed a framework that learns a reward function $\widehat{r}_\psi$ from preferences~\cite{sadigh2017active, wilson2012bayesian}. Specifically, we first model a preference predictor using the reward function $\widehat{r}_\psi$ as follows: \begin{align} P_\psi[\sigma^1\succ\sigma^0] = \frac{\exp\sum_{t} \widehat{\reward}_\psi(\mathbf{s}_{t}^1, \mathbf{a}_{t}^1)}{\sum_{i\in \{0,1\}} \exp\sum_{t} \widehat{\reward}_\psi(\mathbf{s}_{t}^i, \mathbf{a}_{t}^i)},\label{eq:pref_model} \end{align} where $\sigma^i\succ\sigma^j$ denotes the event that segment $i$ is preferable to segment $j$. We remark that this corresponds to assume a stochastic teacher following the Bradley-Terry model~\citep{bradley1952rank} but we do not assume that the type and degree of irrationality or systematic bias is available in our experiments. Because this could lead to a poor preference inference~\citep{chan2021the}, future work may be able to further improve the efficiency of learning by approximating the teacher's irrationality. To align our preference predictor with the teacher's preferences, we consider a binary classification problem using the cross-entropy loss. Specifically, given a dataset of preferences $\mathcal{D}$, the reward function, modeled as a neural network with parameters $\psi$, is updated by minimizing the following loss: \begin{align} \mathcal{L}^{\tt Reward} = -\expec_{(\sigma^0,\sigma^1,y)\sim \mathcal{D}} \Big[ & y(0)\log P_\psi[\sigma^0\succ\sigma^1] + y(1) \log P_\psi[\sigma^1\succ\sigma^0]\Big]. \label{eq:reward-bce} \end{align} Once we learn a reward function ${\widehat r}_\psi$, we can update the policy $\pi_\phi$ using any RL algorithm. A caveat is that the reward function may be non-stationary because we update it during training. To mitigate the effects of a non-stationary reward function, \citet{preference_drl} used on-policy RL algorithms, such as TRPO~\citep{trpo} and A2C~\citep{mnih2016a2c}. We re-implemented this method using the state-of-the-art on-policy RL algorithm: PPO~\cite{ppo}. We refer to this baseline as PrefPPO. \subsection{PEBBLE} PEBBLE~\citep{pebble} is a state-of-the-art preference-based RL algorithm that improved the framework of \citet{preference_drl} using the following ideas: {\bf Unsupervised pre-training}. In the beginning of training, a naive agent executing a random policy does not provide good state coverage nor coherent behaviors. Therefore, the agent's queries are not diverse and a teacher can not convey much meaningful information. As a result, it requires many samples (and thus queries) for these methods to show initial progress. \citet{ibarz2018preference_demo} has addressed this issue by assuming that demonstrations are available at the beginning of the experiment. However, this is not ideal since suitable demonstrations are often prohibitively expensive to obtain in practice. Instead, PEBBLE pre-trains the policy only using intrinsic motivation~\citep{oudeyer2007intrinsic,schmidhuber2010formal} to learn how to generate diverse behaviors. Specifically, by updating the agent to maximize the state entropy $\mathcal{H}(\mathbf{s}) = -\mathbb{E}_{\mathbf{s} \sim p(\mathbf{s})} \left[ \log p(\mathbf{s}) \right]$, it encourages the agent to efficiently explore an environment and collect diverse experiences (see the supplementary material for more details). {\bf Off-policy RL with relabeling}. To overcome the poor sample-efficiency of on-policy RL algorithms, PEBBLE used the state-of-the-art off-policy RL algorithm: SAC~\citep{sac}. However, the learning process can be unstable because previous experiences in the replay buffer are labeled with previous learned rewards. PEBBLE stabilizes the learning process by relabeling all of the agent’s past experience every time it updates the reward model. \section{Related work} {\bf Benchmarks for deep reinforcement learning}. There is a large body of work focused on designing benchmarks for RL~\cite{ beattie2016deepmind,bellemare2013arcade, brockman2016openai, cobbe2019quantifying, cobbe2020leveraging, duan2016benchmarking, fu2020d4rl, gulcehre2020rl,henderson2018deep, ray2019benchmarking, dmcontrol_old,dmcontrol_new, yu2020meta}. The Arcade Learning Environment~\cite{bellemare2013arcade} has becomes a popular benchmark to measure the progress of RL algorithms for discrete control tasks. For continuous control tasks, \citet{duan2016benchmarking} presented a benchmark with baseline implementations of various RL algorithms, which in turn led to OpenAI Gym~\citep{brockman2016openai}. These benchmarks have significantly accelerated progress and have been strong contributors towards the discovery and evaluation of today's most widely used RL algorithms~\citep{sac,mnih2015human,trpo,schulman2015high,ppo}. Recently, researchers proposed more targeted RL benchmarks that have been designed for specific research purposes. \citet{cobbe2020leveraging} presented a suite of game-like environments where the train and test environments differ for evaluating generalization performance of RL agents. \citet{ray2019benchmarking} provided a Safety Gym for measuring progress towards RL agents that satisfy the safety constraints. D4RL~\cite{fu2020d4rl} and RL Unplugged~\cite{gulcehre2020rl} have been proposed to evaluate and compare offline RL algorithms. \citet{yu2020meta} proposed Meta-world to study meta- and multi-task RL. URLB~\citep{laskin2021urlb} benchmarks performance of unsupervised RL methods. However, none of the existing RL benchmarks are tailored towards preference-based RL. \citet{freire2020derail} proposed DERAIL, a benchmark suite for preference-based learning, but they focused on simple diagnostic tasks. In B-Pref, we consider learning a variety of complex locomotion and robotic manipulation tasks. Additionally, we design teachers with a wide array of irrationalities and benchmark state-of-the-art preference-based RL algorithms~\citep{preference_drl,pebble} in depth. {\bf Human-in-the-loop reinforcement learning}. Several works have successfully utilized feedback from real humans to train RL agents~\citep{deepcoach,preference_drl,ibarz2018preference_demo,tamer,pebble,coach,deeptamer}. \citet{coach} proposed a reward-free method, which utilizes a human feedback as an advantage function and optimizes the agents via a policy gradient. \citet{tamer} trained a reward model via regression using unbounded real-valued feedback. However, these approaches are difficult to scale to more complex learning problems that require substantial agent experience. Another promising direction has focused on utilizing the human preferences~\citep{akrour2011preference,preference_drl,ibarz2018preference_demo,pebble,leike2018scalable,pilarski2011online, stiennon2020learning, wilson2012bayesian,wu2021recursively}. \citet{preference_drl} scaled preference-based learning to utilize modern deep learning techniques, and \citet{ibarz2018preference_demo} improved the efficiency of this method by introducing additional forms of feedback such as demonstrations. Recently, \citet{pebble} proposed a feedback-efficient RL algorithm by utilizing off-policy learning and pre-training. \citet{stiennon2020learning} and \citet{wu2021recursively} showed that preference-based RL can be utilized to fine-tune GPT-3~\citep{brown2020language} for hard tasks like text and book summarization, respectively. We benchmark these state-of-the-art preference-based RL algorithms in this paper. \section{Conclusion} \label{sec:conclusion} In this paper, we present B-Pref, a benchmark specially designed for preference-based RL, covering a wide array of a teacher's irrationalities. We empirically investigate state-of-the-art preference-based RL algorithms in depth and analyze the effects of algorithmic design decisions on our benchmark. We find that existing methods often suffer from poor performance when teachers provide wrong labels, and the effects of design decisions are varied depending on the task setups. These observations call for new algorithms in active learning~\citep{biyik2018batch, biyik2020active, sadigh2017active} and meta-learning~\citep{xu2018meta,xu2020meta} to be developed. By providing an open-source release of the benchmark, we encourage other researchers to use B-Pref as a common starting point to study preference-based RL more systematically. {\bf Limitations.} There are several important properties that are not explored in-depth in B-Pref. One is robustness of learned reward functions to new environments with different dynamics or initial states~\cite{reddy2020learning}. Also, we focus on tasks with proprioceptive inputs and dense rewards, but extensions to visual observations and sparse rewards are interesting directions to explore. {\bf Potential negative impacts.} Preference-based RL has several advantages (e.g., teaching novel behaviors, and mitigating the effects of reward exploitation); however, it also has potential drawbacks. Malicious users might teach the bad behaviors/functionality using this framework. Therefore, researchers should consider the safety issues with particular thought. \section*{Acknowledgements} This research is supported in part by ONR PECASE N000141612723, NSF NRI \#2024675, ONR YIP, and Berkeley Deep Drive. Laura Smith was supported by NSF Graduate Research Fellowship. We thank Qiyang (Colin) Li and Olivia Watkins for providing helpful feedback and suggestions. We also thank anonymous reviewers for critically reading the manuscript and suggesting substantial improvements. \section{Using B-Pref to analyze algorithmic design decisions} \label{sec:exp} \begin{figure*} [t] \centering \subfigure[Walker] { \includegraphics[width=1\textwidth]{figures/figure1_walker_iqm.pdf} \label{fig:main_walker_iqm}} \subfigure[Quadruped] { \includegraphics[width=1\textwidth]{figures/figure1_quad_iqm.pdf} \label{fig:main_quad_iqm}} \subfigure[Button Press] { \includegraphics[width=1\textwidth]{figures/figure1_button_iqm.pdf} \label{fig:main_button_iqm}} \subfigure[Sweep Into] { \includegraphics[width=1\textwidth]{figures/figure1_sweep_iqm.pdf} \label{fig:main_sweep_iqm}} \caption{IQM normalized returns with 95\% confidence intervals across ten runs. Learning curves and other metrics (median, mean, optimality gap) are in the supplementary material.} \label{fig:main_iqm} \end{figure*} We design our experiments to investigate the following: \begin{itemize} [leftmargin=8mm] \setlength\itemsep{0.1em} \item How do existing preference-based RL methods compare against each other across environments with different complexity? \item How to use B-Pref to analyze algorithmic design decisions for preference-based RL? \end{itemize} \subsection{Training details} We implement PEBBLE and PrefPPO using publicly released implementations of SAC\footnote{\url{https://github.com/denisyarats/pytorch_sac}} and PPO.\footnote{\url{https://github.com/DLR-RM/stable-baselines3}} All hyperparameters of all algorithms are optimized independently for each environment. All of the experiments were processed using a single GPU (NVIDIA GTX 1080 Ti) and 8 CPU cores (Intel Xeon Gold 6126). For reliable evaluation~\cite{agarwal2021deep}, we measure the normalized returns\footnote{On robotic manipulation tasks, we measure the task success rate as defined by the Meta-world authors~\citep{yu2020meta}.} and report the interquartile mean (IQM) across ten runs using an open-source library {\em rliable}.\footnote{\url{https://github.com/google-research/rliable}} More experimental details (e.g., model architectures and the final hyperparameters) and all learning curves with standard deviation are in the supplementary material. \begin{figure*} [t] \centering \subfigure[PEBBLE with 2000 queries] { \includegraphics[width=1\textwidth]{figures/figure2_2K_iqm.pdf} \label{fig:sampling_2K_iqm}} \subfigure[PEBBLE with 1000 queries] { \includegraphics[width=1\textwidth]{figures/figure2_1K_iqm.pdf} \label{fig:sampling_1K_iqm}} \caption{IQM normalized returns of PEBBLE with various sampling schemes across ten runs on Quadruped. Learning curves and other metrics (median, mean, optimality gap) are in the supplementary material.} \label{fig:sampling_iqm} \end{figure*} \subsection{Benchmarking prior methods} Figure~\ref{fig:main_iqm} shows the IQM normalized returns of PEBBLE and PrefPPO at convergence on various simulated teachers listed in Section~\ref{sec:scripted_teachers} (see the supplementary material for experimental details). For a fair comparison, we apply unsupervised pre-training and disagreement-based sampling to all methods (including SAC and PPO). PEBBLE outperforms PrefPPO in most of the environments (especially achieving large gains on robotic manipulation tasks). Interestingly, providing uniform labels to equally preferable segments (Equal) or skipping the queries with similar behaviors (Skip) is more useful than relying only on perfect labels (Oracle) on hard environments like Quadruped (Figure~\ref{fig:main_quad_iqm}). While both PEBBLE and PrefPPO achieve fairly efficient performance on correct labels (Oracle, Equal and Skip), they often suffer from poor performance when teachers can provide the wrong labels (Mistake and Stoc). This suggests opportunities for further investigations and development of techniques that can improve the robustness to corrupted labels.\footnote{We find that label smoothing~\citep{szegedy2016rethinking} is not effective in handling corrupted labels in our experiments (see the supplementary material for supporting results). However, other regularization techniques, like label flipping, L2 regularization and weight decay, would be interesting for further study in future work.} \subsection{Impact of design decisions in reward learning} \label{sec:sampling} Reward learning from preferences involves several design decisions, which can affect the performance of the overall framework. We showcase the utility of B-Pref by using it to analyze the following algorithmic design choices in depth: {\bf Selecting informative queries}. During training, all experiences are stored in an annotation buffer $\mathcal{B}$ and we generate $N_{\tt query}$ pairs of segments\footnote{We do not compare segments of different lengths.} to ask teacher's preferences from this buffer at each feedback session. To reduce the burden on the human, we should solicit preferences so as to maximize the information received. While finding optimal queries is computationally intractable~\citep{ailon2012active}, several sampling schemes~\citep{biyik2018batch, biyik2020active, sadigh2017active} have been explored to find queries that are likely to change the reward model. Specifically, we consider the following sampling schemes, where more details are in the supplementary material: \begin{itemize} [leftmargin=8mm] \setlength\itemsep{0.1em} \item {\em Uniform sampling}: We pick $N_{\tt query}$ pairs of segments uniformly at random from the buffer $\mathcal{B}$. \item {\em Uncertainty-based sampling}: We first generate the initial batch of $N_{\tt init}$ pairs of segments $\mathcal{G}_{\tt init}$ uniformly at random, measure the uncertainty (e.g., variance across ensemble of preference predictors ~\cite{preference_drl} or entropy of a single preference predictor~\citep{pebble}), and then select the $N_{\tt query}$ pairs of segments with high uncertainty. \item {\em Coverage-based sampling}: From the initial batch $\mathcal{G}_{\tt init}$, we choose $N_{\tt query}$ center points such that the largest distance between a data point and its nearest center is minimized using a greedy selection strategy. \item {\em Hybrid sampling}: Similar to \citet{yu2006active}, we also consider hybrid sampling, which combines uncertainty-based sampling and coverage-based sampling. First, we select the $N_{\tt inter}$ pairs of segments $\mathcal{G}_{\tt un}$, using uncertainty-based sampling, where $N_{\tt init}>N_{\tt inter}$, and then choose $N_{\tt query}$ center points from $\mathcal{G}_{\tt un}$. \end{itemize} Figure~\ref{fig:sampling_iqm} shows the IQM normalized returns of PEBBLE with various sampling schemes on Quadruped. We find that the uncertainty-based sampling schemes (i.e., ensemble disagreement and entropy) are superior to other sampling schemes, while coverage-based sampling schemes do not improve on uniform sampling and slow down the sampling procedures. To analyze the effects of sampling schemes, we measure the fraction of equally preferable queries (i.e., $y=(0.5, 0.5)$) on the Equal teacher. Figure~\ref{fig:sampling_uniform} shows that uncertainty-based sampling schemes achieve high returns even though other sampling schemes receive more (non-uniform) perfect labels. We expect that this is because queries with high uncertainty provide significant information to the reward model. This also suggests opportunities for further investigations on uncertainty estimates like Bayesian methods~\citep{brown2019deep, gal2016dropout}. {\bf Feedback schedule}. We also investigate the impact of the feedback schedule, which decides the number of queries at each feedback session. \citet{pebble} used a uniform schedule, which always asks the same number of queries, and \citet{preference_drl,ibarz2018preference_demo} used a decay schedule, which decreases the number of queries, roughly proportional to $\frac{T}{t+T}$, where $t$ is the current timestep and $T$ is the episode length. We additionally consider an increase schedule, which increases the number of queries, roughly proportional to $\frac{T+t}{T}$. Figure~\ref{fig:scheduling_all} shows the learning curves of PEBBLE with different feedback schedule on the oracle teacher. Given the same total number of queries, increase and decay schedules change the size of the initial queries by a factor of 0.5 and 2, respectively. One can note that there is no big gain from rule-based schedules in most of the environments. Even though rule-based schedules are less effective than uniform scheduling, using an adaptive schedule like meta-gradient~\citep{xu2018meta,xu2020meta} would be interesting for further study in future work. \begin{figure*} [t] \centering \subfigure[Button Press] { \includegraphics[width=0.23\textwidth]{figures/fig3_button.pdf} \label{fig:scheduling_button_all}} \subfigure[Sweep Into] { \includegraphics[width=0.23\textwidth]{figures/fig3_sweep.pdf} \label{fig:scheduling_sweep_all}} \subfigure[Quadruped] { \includegraphics[width=0.23\textwidth]{figures/fig3_quadruped.pdf} \label{fig:scheduling_quad_all}} \subfigure[Walker] { \includegraphics[width=0.23\textwidth]{figures/fig3_walker.pdf} \label{fig:scheduling_walker_all}} \caption{Learning curves of PEBBLE with different feedback schedules on the oracle teacher. The solid line and shaded regions represent the mean and standard deviation, respectively, across ten runs. } \label{fig:scheduling_all} \end{figure*} {\bf Reward analysis}. To investigate the quality of the learned reward function, we compare the learned reward function with the ground truth reward. Figure~\ref{fig:reward_sweep} and Figure~\ref{fig:reward_walker} show the learned reward function optimized by PEBBLE on the oracle teacher in Sweep Into and Walker, where more evaluation results on other environments are also available in the supplementary material. Because we bound the output of the reward function using tanh function, the scale is different with the ground truth reward but the learned reward function is reasonably well-aligned. \begin{figure*} [t] \centering \subfigure[Sampling analysis] { \includegraphics[width=0.32\textwidth]{figures/table2_analyze.pdf} \label{fig:sampling_uniform}} \subfigure[Sweep Into] { \includegraphics[width=0.3\textwidth]{figures/fig4_metaworld_sweep-into-v2.pdf} \label{fig:reward_sweep}} \subfigure[Walker] { \includegraphics[width=0.3\textwidth]{figures/fig4_walker_walk.pdf} \label{fig:reward_walker}} \caption{(a) Fraction of equally preferable queries (red) and average returns (blue) on the Equal teacher. We use PEBBLE with different sampling schemes on Quadruped given a budget of 2000 queries. Even though a teacher provides more uniform labels, i.e., $y=(0.5, 0.5)$, to uncertainty-based sampling schemes, they achieve higher returns than other sampling schemes. (b/c) Time series of learned reward function (green) and the ground truth reward (red) using rollouts from a policy optimized by PEBBLE. Learned reward functions align with the ground truth rewards in (b) Sweep Into and (c) Walker.} \label{fig:analysis} \end{figure*} \section{Introduction} Deep reinforcement learning (RL) has emerged as a powerful method to solve a variety of sequential decision-making problems, including board games~\cite{alphago,alphazero}, video games~\cite{berner2019dota,mnih2015human,alphastar}, autonomous control~\cite{bellemare2020autonomous,trpo}, and robotic manipulation~\cite{andrychowicz2020learning, qtopt, policy-search, robot-rl}. However, scaling RL to many applications is difficult due to the challenges associated with defining a suitable reward function, which often requires substantial human effort. Specifying the reward function becomes harder as the tasks we want the agent to achieve become more complex (e.g., cooking or self-driving). In addition, RL agents are prone to exploit reward functions by discovering ways to achieve high returns in ways the reward designer did not expect nor intend. It is important to consider this phenomenon of reward exploitation, or reward hacking, since it may lead to unintended but dangerous consequences~\citep{hadfield2017inverse}. Further, there is nuance in how we might want agents to behave, such as obeying social norms that are difficult to account for and communicate effectively through an engineered reward function~\citep{amodei2016concrete,implicit-preferences, reward-side-effects}. Preference-based RL~\citep{preference_drl,ibarz2018preference_demo,pebble} provides an alternative: a (human) teacher provides preferences between the two agent behaviors, and the agent then uses this feedback to learn desired behaviors (see Figure~\ref{fig:overview}). This framework enables us to optimize the agent using RL without hand-engineered rewards by learning a reward function, which is consistent with the observed preferences~\citep{biyik2018batch, biyik2020active, sadigh2017active}. Because a teacher can interactively guide agents according to their progress, preference-based RL has shown promising results (e.g., solving a range of RL benchmarks~\citep{preference_drl,ibarz2018preference_demo}, teaching novel behaviors~\citep{stiennon2020learning,wu2021recursively}, and mitigating the effects of reward exploitation~\citep{pebble}). Despite significant progress on RL benchmarks designed for various purposes (e.g., offline RL~\citep{fu2020d4rl,gulcehre2020rl}, generalization~\cite{cobbe2019quantifying,cobbe2020leveraging}, meta RL~\citep{yu2020meta}, and safe RL~\cite{ray2019benchmarking}), existing benchmarks are not tailored towards preference-based RL. The lack of a standard evaluation benchmark makes it hard to quantify scientific progress. Indeed, without consistent evaluation, it is not easy to understand the effects of algorithmic and design decisions or compare them across papers. In this paper, we introduce B-Pref: a benchmark for preference-based RL consisting of various locomotion and robotic manipulation tasks from DeepMind Control Suite~\citep{dmcontrol_old,dmcontrol_new} and Meta-world~\citep{yu2020meta}. While utilizing real human input is ideal, this is prohibitive because it is hard to evaluate candidate algorithms quickly using real human input. Prior works~\citep{preference_drl,ibarz2018preference_demo,pebble} address this issue by simulating human input as giving perfect preferences with respect to an underlying ground truth reward function. However, evaluation on such ideal teachers is unrealistic because actual humans can exhibit various irrationalities~\citep{chipman2016oxford} in decision making. So, in our benchmark, we design simulated human teachers with a wide array of irrationalities and propose evaluation metrics not solely for performance but also for robustness to these potential irrationalities. To serve as a reference, we benchmark state-of-the-art preference-based RL algorithms~\citep{preference_drl,pebble} in B-Pref and showcase the utility of B-Pref by using it to analyze algorithmic design choices for preference-based RL. Although existing methods provide fairly efficient performance on perfectly rational teachers, the poor performance on more realistic, irrational teachers calls for new algorithms to be developed. The benchmark and reference implementations are available at \url{https://github.com/rll-research/B-Pref}. We believe that systematic evaluation and comparison will not only further our understanding of the strengths of existing algorithms, but also reveal their limitations and suggest directions for future research. \section{Preliminaries: Reinforcement learning algorithms} \label{app:rl_algo} {\bf Proximal policy optimization}. Proximal policy optimization (PPO)~\cite{ppo} is a state-of-the-art on-policy algorithm for learning a continuous or discrete control policy, $\pi_\phi(\mathbf{a}|\mathbf{s})$. PPO forms policy gradients using action-advantages, $A_t=A^\pi(\mathbf{a}_t,\mathbf{s}_t)=Q^\theta (\mathbf{a}_t,\mathbf{s}_t)-V^\pi(\mathbf{s}_t)$, and minimizes a clipped-ratio loss over minibatches of recent experience (collected under $\pi_{\bar \phi}$): \begin{equation} \label{eq:PPO_pi_Loss} \mathcal{L}^{\tt PPO}_{\pi} =-\mathbb{E}_{\tau_t \sim \pi}\left[\min\left(\rho_t(\phi) A_t, \ \text{clip}(\rho_t(\phi),1-\epsilon,1+\epsilon)A_t\right)\right], \quad \rho_t(\phi)=\frac{\pi_\phi(\mathbf{a}_t|\mathbf{s}_t)}{\pi_{\phi_{old}} (\mathbf{a}_t|\mathbf{s}_t)}, \end{equation} where ${\bar \phi}$ are the delayed parameters and $\epsilon$ is a clip ratio. Our PPO agents learn a state-value estimator, $V_\theta(\mathbf{s})$, which is regressed against a target of discounted returns and used with Generalized Advantage Estimation~\cite{schulman2015high}: \begin{equation} \label{eq:PPO_V_Loss} \mathcal{L}^{\tt PPO}_V(\theta) = \mathbb{E}_{\tau_t \sim\pi}\left[\left(V_\theta(\mathbf{s}_t)-V_{\bar \theta}(\mathbf{s}_t)\right)^2\right]. \end{equation} PPO is more robust to the non-stationarity in rewards caused by online learning. {\bf Soft actor-critic}. Soft actor-critic (SAC)~\citep{sac} is an off-policy actor-critic method based on the maximum entropy RL framework \citep{ziebart2010modeling}, which encourages exploration and greater robustness to noise by maximizing a weighted objective of the reward and the policy entropy. To update the parameters, SAC alternates between a soft policy evaluation and a soft policy improvement. At the soft policy evaluation step, a soft Q-function, which is modeled as a neural network with parameters $\theta$, is updated by minimizing the following soft Bellman residual: \begin{align} &\mathcal{L}^{\tt SAC}_{Q} = \mathbb{E}_{\tau_t \sim \mathcal{B}} \Big[\left(Q_\theta(\mathbf{s}_t,\mathbf{a}_t) - r_t -{\bar \gamma} {\bar V}(\mathbf{s}_{t+1}) \right)^2 \Big], \label{eq:sac_critic} \\ & \text{with} \quad {\bar V}(\mathbf{s}_t) = \mathbb{E}_{\mathbf{a}_t\sim \pi_\phi} \big[ Q_{\bar \theta} (\mathbf{s}_t,\mathbf{a}_t) - \alpha \log \pi_{\phi} (\mathbf{a}_t|\mathbf{s}_t) \big], \notag \end{align} where $\tau_t = (\mathbf{s}_t,\mathbf{a}_t,\mathbf{s}_{t+1},r_t)$ is a transition, $\mathcal{B}$ is a replay buffer, $\bar \theta$ are the delayed parameters, and $\alpha$ is a temperature parameter. At the soft policy improvement step, the policy $\pi_\phi$ is updated by minimizing the following objective: \begin{align} \mathcal{L}^{\tt SAC}_{\pi} = \mathbb{E}_{\mathbf{s}_t\sim \mathcal{B}, \mathbf{a}_{t}\sim \pi_\phi} \Big[ \alpha \log \pi_\phi (\mathbf{a}_t|\mathbf{s}_t) - Q_{ \theta} (\mathbf{s}_{t},\mathbf{a}_{t}) \Big]. \label{eq:sac_actor} \end{align} SAC enjoys good sample-efficiency relative to its on-policy counterparts by reusing its past experiences. However, for the same reason, SAC is not robust to a non-stationary reward function. \begin{algorithm}[h!] \caption{\texttt{EXPLORE}: Unsupervised exploration} \label{alg:unsuprl} \begin{algorithmic}[1] \footnotesize \State Initialize parameters of $\pi_\phi$ and a buffer $\mathcal{B} \leftarrow \emptyset$ \For{each iteration} \For{each timestep $t$} \State Collect $\mathbf{s}_{t+1}$ by taking $\mathbf{a}_t \sim \pi_\phi \left(\mathbf{a}_t | \mathbf{s}_t\right)$ \State Compute intrinsic reward $r_t^{\text{\tt int}}\leftarrow r^{\text{\tt int}}(\mathbf{s}_t)$ as in \eqref{eq:state_ent} \State Store transitions $\mathcal{B} \leftarrow \mathcal{B}\cup \{(\mathbf{s}_t,\mathbf{a}_t,\mathbf{s}_{t+1},r_t^{\text{\tt int}})\}$ \EndFor \For{each gradient step} \State Sample minibatch $\{\left(\mathbf{s}_j,\mathbf{a}_j,\mathbf{s}_{j+1},r_j^{\text{\tt int}}\right)\}_{j=1}^B\sim\mathcal{B}$ \State Optimize RL objective function with respect to $\phi$ \EndFor \EndFor \State $\textbf{return} \; \mathcal{B}, \pi_\phi$ \end{algorithmic} \end{algorithm} \section{Preference-based reinforcement learning} Algorithm~\ref{alg:overview} summarizes the full procedure of preference-based RL methods that we consider in this paper. We also utilize unsupervised pre-training which encourages our agent to visit a wider range of states by using the state entropy $\mathcal{H}(\mathbf{s}) = -\mathbb{E}_{\mathbf{s} \sim p(\mathbf{s})} \left[ \log p(\mathbf{s}) \right]$ as an intrinsic reward~\cite{liu2021unsupervised,hazan2019provably,lee2019efficient,seo2021state}. By following \citet{pebble}, we define the intrinsic reward of the current state $\mathbf{s}_t$ as follows: \begin{align} r^{\text{\tt int}}(\mathbf{s}_t) = \log (|| \mathbf{s}_{t} - \mathbf{s}_{t}^{k}||), \label{eq:state_ent} \end{align} where $\mathbf{s}_{i}^{k}$ is the $k$-NN of $\mathbf{s}_{i}$ within a set $\{\mathbf{s}_{i}\}_{i=1}^{N}$. The full procedure of unsupervised pre-training is summarized in Algorithm~\ref{alg:unsuprl}. \begin{algorithm}[t!] \caption{Preference-based RL with reward learning} \label{alg:overview} \begin{algorithmic}[1] \footnotesize \Require frequency of teacher feedback $K$ \Require number of queries $N_{\tt query}$ per feedback session \State Initialize parameters of $\pi_\phi$, $\widehat{\reward}_\psi$, a dataset of preferences $\mathcal{D} \leftarrow \emptyset$, and a buffer $\mathcal{B} \leftarrow \emptyset$ \State {{\textsc{// Exploration phase}}} \State $\mathcal{B}, \pi_\phi \leftarrow\texttt{EXPLORE}()$ in Algorithm~\ref{alg:unsuprl} \For{each iteration} \State {{\textsc{// Reward learning}}} \If{iteration \% $K == 0$} \For{$m$ in $1\ldots N_{\tt query}$} \State $(\sigma^0, \sigma^1)\sim\texttt{SAMPLE()}$ (see Section~\ref{app:sampling}) and query \texttt{SimTeacher} in Algorithm~\ref{alg:scriptedteacher} for $y$ \State Store preference $\mathcal{D} \leftarrow \mathcal{D}\cup \{(\sigma^0, \sigma^1,y)\}$ \EndFor \For{each gradient step} \State Sample minibatch $\{(\sigma^0, \sigma^1,y)_j\}_{j=1}^D\sim\mathcal{D}$ and optimize $\mathcal{L}^{\tt Reward}$ in \eqref{eq:reward-bce} with respect to $\psi$ \EndFor \EndIf \State {{\textsc{// Policy learning}}} \For{each timestep $t$} \State Collect $\mathbf{s}_{t+1}$ by taking $\mathbf{a}_t \sim \pi(\mathbf{a}_t | \mathbf{s}_t)$ and store transitions $\mathcal{B} \leftarrow \mathcal{B}\cup \{(\mathbf{s}_t,\mathbf{a}_t,\mathbf{s}_{t+1},\widehat{\reward}_\psi(\mathbf{s}_t))\}$ \EndFor \For{each gradient step} \State Sample random minibatch $\{\left(\tau_j\right)\}_{j=1}^B\sim\mathcal{B}$ and optimize RL objective function with respect to $\phi$ \EndFor \State Reset $\mathcal{B} \leftarrow \emptyset$ if on-policy RL algorithm is used \EndFor \end{algorithmic} \end{algorithm} \section{Sampling schemes} \label{app:sampling} We consider the following sampling schemes in this paper: \begin{itemize} [leftmargin=8mm] \setlength\itemsep{0.1em} \item {\em Uniform sampling}: We pick $N_{\tt query}$ pairs of segments uniformly at random from the buffer $\mathcal{B}$. \item {\em Disagreement}: We first generate the initial batch of $N_{\tt inter}$ pairs of segments $\mathcal{G}_{\tt init}$ uniformly at random, measure the variance across ensemble of preference predictors $\{P_{\psi_i}[\sigma^1\succ\sigma^0]\}_{i=1}^{N_{\tt en}}$, and then select the $N_{\tt query}$ pairs of segments with high uncertainty. \item {\em Entropy}: We first generate the initial batch of $N_{\tt inter}$ pairs of segments $\mathcal{G}_{\tt init}$ uniformly at random, measure the entropy of a single preference predictor $\mathcal{H}(P_{\psi})$, and then select the $N_{\tt query}$ pairs of segments with high uncertainty. \item {\em Coverage}: From the initial batch $\mathcal{G}_{\tt init}$, we choose center points, which increase the dissimilarity between the selected queries. Specifically, we concatenate the states of segments, i.e., $\mathbf{s}_{\tt concat} = {\tt Concat}(\mathbf{s}^0_{k+1},\cdots,\mathbf{s}^0_{k+H},\mathbf{s}^1_{k+1},\cdots,\mathbf{s}^1_{k+H})$\footnote{Concatenating states would not be an optimal choice because it is not permutation-invariant, which is also not handled in the prior work~\citep{biyik2018batch}. However, we expect that an issue from permutation-variance is not significant because a probability to sample two segments in a different order is very low. However, it is an interesting future direction to explore to address this limitation.} and measure the Euclidean distance. Then, we choose $N_{\tt query}$ center points such that the largest distance between a data point and its nearest center is minimized using a greedy selection strategy. \item {\em Disagreement + Coverage}: We first select the $N_{\tt inter}$ pairs of segments $\mathcal{G}_{\tt un}$, using the disagreement sampling, where $N_{\tt init}>N_{\tt inter}$, and then choose $N_{\tt query}$ center points from $\mathcal{G}_{\tt un}$. \item {\em Entropy + Coverage}: We first select the $N_{\tt inter}$ pairs of segments $\mathcal{G}_{\tt un}$, using the entropy sampling, and then choose $N_{\tt query}$ center points from $\mathcal{G}_{\tt un}$. \end{itemize} \section{Experimental Details} \label{app:exp_setup} {\bf Training details}. We use PEBBLE and PrefPPO\footnote{For Meta-world, the frequency is chosen from $\{8K, 16K, 32K, 64K\}$ and \# of queries per session is chosen from $\{50, 100, 250, 500, 1000\}$.} with a full list of hyperparameters in Table~\ref{table:hyperparameters_sac} and Table~\ref{table:hyperparameters_ppo}, respectively. We pre-train an agent for 10K timesteps and 32K timesteps for PEBBLE and PrefPPO, respectively. \begin{table}[h!] \begin{center} \resizebox{\columnwidth}{!}{ \begin{tabular}{ll|ll} \toprule \textbf{Hyperparameter} & \textbf{Value} & \textbf{Hyperparameter} & \textbf{Value} \\ \midrule Initial temperature & $0.1$ & Hidden units per each layer & $1024$ (DMControl), $256$ (Meta-world) \\ Segment of length & $50$ (DMControl), $25$ (Meta-world) & \# of layers & $2$ (DMControl), $3$ (Meta-world)\\ Learning rate & $0.0003$ (Meta-world) & Batch Size & $1024$ (DMControl), $512$ (Meta-world)\\ & $0.0001$ (Quadruped), $0.0005$ (Walker) & Optimizer & Adam~\citep{kingma2014adam}\\ Critic target update freq & $2$ & Critic EMA $\tau$ & $0.005$ \\ $(\beta_1,\beta_2)$ & $(.9,.999)$ & Discount ${\bar \gamma}$ & $.99$\\ Frequency of feedback & $5000$ (Meta-world), $20000$ (Walker) & Maximum budget / & $2000/200, 1000/100, 500/50$ (DMControl) \\ & $30000$ (Quadruped) & \# of queries per session & $20K/100, 10K/50$ (Meta-world)\\ \bottomrule \end{tabular}} \end{center} \caption{Hyperparameters of the PEBBLE algorithm. } \label{table:hyperparameters_sac} \end{table} \begin{table}[h!] \begin{center} \resizebox{\columnwidth}{!}{ \begin{tabular}{ll|ll} \toprule \textbf{Hyperparameter} & \textbf{Value} & \textbf{Hyperparameter} & \textbf{Value} \\ \midrule GAE parameter $\lambda$ & $0.9$ (Quadruped), $0.92$ (otherwise) & Hidden units per each layer & $256$ \\ Segment of length & $50$ (DMControl), $25$ (Meta-world) & \# of layers & $3$ \\ Learning rate & $0.0003$ (Meta-world) & Batch Size & $64$ (Walker), $256$ (Sweep Into)\\ & $5e^{-5}$ (DMControl) & & $128$ (Quadruped, Button) \\ Discount ${\bar \gamma}$ & $.99$ & Frequency of feedback & $32000$ (DMControl) \\ \# of environments per worker & $8$ (Button), $16$ (Quadruped), & PPO clip range & $0.4$ \\ & $32$ (Walker, Sweep Into) & Entropy bonus & $0.0$ \\ \# of timesteprs per rollout & $500$ (DMControl) & Maximum budget / & \multirow{2}{*}{$2000/200, 1000/100$ (DMControl)} \\ & $250$ (Meta-world) & \# of queries per session & \\ \bottomrule \end{tabular}} \end{center} \caption{Hyperparameters of the PrefPPO algorithm.} \label{table:hyperparameters_ppo} \end{table} {\bf Reward model}. For the reward model, we use a three-layer neural network with 256 hidden units each, using leaky ReLUs. To improve the stability in reward learning, we use an ensemble of three reward models, and bound the output using tanh function. Each model is trained by optimizing the cross-entropy loss defined in \eqref{eq:reward-bce} using ADAM learning rule~\citep{kingma2014adam} with the initial learning rate of 0.0003. {\bf Simulated human teachers}. For all experiments, To evaluate the robustness, we evaluate against the following simulated human teachers with different hyperparameters: \begin{itemize} [leftmargin=8mm] \setlength\itemsep{0.05em} \item Oracle: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \epsilon=0, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \item Stoc: \texttt{SimTeacher}$\left(\mybox{$\beta=1$}, \gamma=1, \epsilon=0, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \item Mistake: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \mybox{$\epsilon=0.1$}, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \item Skip: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \epsilon=0, \mybox{$\delta_{\tt skip}=\delta_{\tt adapt}(\epsilon_{\tt adapt}, t)$}, \delta_{\tt equal}=0\right)$ \item Equal: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \gamma=1, \epsilon=0, \delta_{\tt skip}=0, \mybox{$\delta_{\tt adapt}=\delta_{\tt skip}(\epsilon_{\tt adapt}, t)$}\right)$ \item Myopic: \texttt{SimTeacher}$\left(\mybox{$\beta\rightarrow\infty$}, \mybox{$\gamma=0.9$}, \epsilon=0, \delta_{\tt skip}=0, \delta_{\tt equal}=0\right)$ \end{itemize} Because each environment has a different scale of ground truth rewards, it is hard to design standardized Skip and Equal teachers using hard threshold. To address this issue, we use an adaptive threshold, which is defined as follows: \begin{align} \delta_{\tt adapt}(\epsilon_{\tt adapt}, t) = \frac{H}{T} R_{\tt avg} (\phi_t) \epsilon_{\tt adapt}, \end{align} where $t$ is the current timestep, $\epsilon_{\tt adapt}\in[0,1]$ is hyperparameters to control the threshold, $T$ is the episode length, $H$ is a length of segment and $R_{\tt avg} (\pi_t)$ is the average returns of current policy with the parameters $\pi_t$. By adaptively rescaling the threshold based on the performance of agent, a teacher skips queries or provides uniform labels (i.e., $y=(0.5, 0.5)$. For all experiments, we choose $\epsilon_{\tt adapt}=0.1$. \section{Additional experimental results} {\bf Reward analysis}. Figure~\ref{fig:reward_all} shows the learned reward function optimized by PEBBLE on the oracle teacher in all tested environments. Because we bound the output using tanh function, the scale is different with the ground truth reward but the learned reward function is reasonably well-aligned. {\bf Regularization for handling corrupted labels}. To improve the robustness to corrupted labels, we apply the label smoothing~\cite{szegedy2016rethinking}. By following \citet{preference_drl, ibarz2018preference_demo}, we use a soft label $\widehat y = 0.9*y +0.05$ for the cross-entropy computation. As shown in Figure~\ref{fig:learning_curve_softlearning}, we find that the gains from label smoothing are marginal. \begin{figure*} [h] \centering \subfigure[Button Press] { \includegraphics[width=0.23\textwidth]{figures/fig4_metaworld_button-press-v2.pdf} \label{fig:reward_button_all}} \subfigure[Sweep Into] { \includegraphics[width=0.23\textwidth]{figures/fig4_metaworld_sweep-into-v2.pdf} \label{fig:reward_sweep_all}} \subfigure[Quadruped] { \includegraphics[width=0.23\textwidth]{figures/fig4_quadruped_walk.pdf} \label{fig:reward_quad_all}} \subfigure[Walker] { \includegraphics[width=0.23\textwidth]{figures/fig4_walker_walk.pdf} \label{fig:reward_walker_all}} \caption{Time series of learned reward function (green) and the ground truth reward (red) using rollouts from a policy optimized by PEBBLE.} \label{fig:reward_all} \end{figure*} \begin{figure*} [h] \centering \includegraphics[width=0.9\textwidth]{figures/appendix_walker_walk.pdf} \caption{Learning curves of PEBBLE with 500 queries on Walker on the Mistake teacher. The solid line and shaded regions represent the mean and standard deviation, respectively, across five runs.} \label{fig:learning_curve_softlearning} \end{figure*} \newpage \section{Learning curves} \begin{figure*} [h] \centering \includegraphics[width=1\textwidth]{figures/table1_walker_walk.pdf} \caption{Learning curves of PEBBLE and PrefPPO on Walker-walk as measured on the ground truth reward. The solid line and shaded regions represent the mean and standard deviation, respectively, across ten runs. Asymptotic performance of PPO and PrefPPO is indicated by dotted lines of the corresponding color.} \label{fig:learning_curve_walker} \end{figure*} \begin{figure*} [h] \centering \includegraphics[width=1\textwidth]{figures/table1_quadruped_walk.pdf} \caption{Learning curves of PEBBLE and PrefPPO on Quadruped-walk as measured on the ground truth reward. The solid line and shaded regions represent the mean and standard deviation, respectively, across ten runs. Asymptotic performance of PPO and PrefPPO is indicated by dotted lines of the corresponding color.} \label{fig:learning_curve_quad} \end{figure*} \begin{figure*} [h] \centering \includegraphics[width=1\textwidth]{figures/table1_metaworld_sweep-into-v2.pdf} \caption{Learning curves of PEBBLE and PrefPPO on Sweep Into as measured on the success rate. The solid line and shaded regions represent the mean and standard deviation, respectively, across ten runs. Asymptotic performance of PPO and PrefPPO is indicated by dotted lines of the corresponding color.} \label{fig:learning_curve_sweep} \end{figure*} \begin{figure*} [h] \centering \includegraphics[width=1\textwidth]{figures/table1_metaworld_button-press-v2.pdf} \caption{Learning curves of PEBBLE and PrefPPO on Button Press as measured on the success rate. The solid line and shaded regions represent the mean and standard deviation, respectively, across ten runs. Asymptotic performance of PPO and PrefPPO is indicated by dotted lines of the corresponding color.} \label{fig:learning_curve_button} \end{figure*} \begin{figure*} [h] \centering \includegraphics[width=0.9\textwidth]{figures/table2_quadruped_walk_feed_200.pdf} \caption{Learning curves of PEBBLE with 2000 queries on Quadruped-walk as measured on the ground truth reward. The solid line and shaded regions represent the mean and standard deviation, respectively, across ten runs.} \label{fig:learning_curve_sampling_2000_quad} \end{figure*} \begin{figure*} [h] \centering \includegraphics[width=0.9\textwidth]{figures/table2_quadruped_walk_feed_100.pdf} \caption{Learning curves of PEBBLE with 1000 queries on Quadruped-walk as measured on the ground truth reward. The solid line and shaded regions represent the mean and standard deviation, respectively, across ten runs.} \label{fig:learning_curve_sampling_1000_quad} \end{figure*} \begin{figure*} [t] \centering \subfigure[Mean] { \includegraphics[width=1\textwidth]{figures/figure1_walker_mean.pdf} \label{fig:walker_mean}} \subfigure[Median] { \includegraphics[width=1\textwidth]{figures/figure1_walker_med.pdf} \label{fig:walker_med}} \subfigure[IQM] { \includegraphics[width=1\textwidth]{figures/figure1_walker_iqm.pdf} \label{fig:walker_iqm}} \subfigure[Optimality Gap] { \includegraphics[width=1\textwidth]{figures/figure1_walker_opgap.pdf} \label{fig:walker_og}} \caption{Aggregate metrics on Walker with 95\% confidence intervals (CIs) across ten runs. Higher mean, median and IQM scores and lower optimality gap are better. The CIs are estimated using the percentile bootstrap with stratified sampling.} \label{fig:walker} \end{figure*} \begin{figure*} [t] \centering \subfigure[Mean] { \includegraphics[width=1\textwidth]{figures/figure1_quad_mean.pdf} \label{fig:quad_mean}} \subfigure[Median] { \includegraphics[width=1\textwidth]{figures/figure1_quad_med.pdf} \label{fig:quad_med}} \subfigure[IQM] { \includegraphics[width=1\textwidth]{figures/figure1_quad_iqm.pdf} \label{fig:quad_iqm}} \subfigure[Optimality Gap] { \includegraphics[width=1\textwidth]{figures/figure1_quad_opgap.pdf} \label{fig:quad_og}} \caption{Aggregate metrics on Quadruped with 95\% confidence intervals (CIs) across ten runs. Higher mean, median and IQM scores and lower optimality gap are better. The CIs are estimated using the percentile bootstrap with stratified sampling.} \label{fig:quad_all} \end{figure*} \begin{figure*} [t] \centering \subfigure[Mean] { \includegraphics[width=1\textwidth]{figures/figure1_button_mean.pdf} \label{fig:button_mean}} \subfigure[Median] { \includegraphics[width=1\textwidth]{figures/figure1_button_med.pdf} \label{fig:button_med}} \subfigure[IQM] { \includegraphics[width=1\textwidth]{figures/figure1_button_iqm.pdf} \label{fig:button_iqm}} \subfigure[Optimality Gap] { \includegraphics[width=1\textwidth]{figures/figure1_button_opgap.pdf} \label{fig:button_og}} \caption{Aggregate metrics on Button Press with 95\% confidence intervals (CIs) across ten runs. Higher mean, median and IQM scores and lower optimality gap are better. The CIs are estimated using the percentile bootstrap with stratified sampling.} \label{fig:button} \end{figure*} \begin{figure*} [t] \centering \subfigure[Mean] { \includegraphics[width=1\textwidth]{figures/figure1_sweep_mean.pdf} \label{fig:sweep_mean}} \subfigure[Median] { \includegraphics[width=1\textwidth]{figures/figure1_sweep_med.pdf} \label{fig:sweep_med}} \subfigure[IQM] { \includegraphics[width=1\textwidth]{figures/figure1_sweep_iqm.pdf} \label{fig:sweep_iqm}} \subfigure[Optimality Gap] { \includegraphics[width=1\textwidth]{figures/figure1_sweep_opgap.pdf} \label{fig:sweep_og}} \caption{Aggregate metrics on Sweep Into with 95\% confidence intervals (CIs) across ten runs. Higher mean, median and IQM scores and lower optimality gap are better. The CIs are estimated using the percentile bootstrap with stratified sampling.} \label{fig:sweep} \end{figure*} \begin{figure*} [t] \centering \subfigure[Mean] { \includegraphics[width=1\textwidth]{figures/figure2_2K_mean.pdf} \label{fig:quad_sampling_2K_mean}} \subfigure[Median] { \includegraphics[width=1\textwidth]{figures/figure2_2K_med.pdf} \label{fig:quad_sampling_2K_med}} \subfigure[IQM] { \includegraphics[width=1\textwidth]{figures/figure2_2K_iqm.pdf} \label{fig:quad_sampling_2K_iqm}} \subfigure[Optimality Gap] { \includegraphics[width=1\textwidth]{figures/figure2_2K_opgap.pdf} \label{fig:quad_sampling_2K_og}} \caption{Aggregate metrics of PEBBLE on Quadruped with 2000 queries across ten runs. Higher mean, median and IQM scores and lower optimality gap are better. The CIs are estimated using the percentile bootstrap with stratified sampling.} \label{fig:quad_sampling_2K} \end{figure*} \begin{figure*} [t] \centering \subfigure[Mean] { \includegraphics[width=1\textwidth]{figures/figure2_1K_mean.pdf} \label{fig:quad_sampling_1K_mean}} \subfigure[Median] { \includegraphics[width=1\textwidth]{figures/figure2_1K_med.pdf} \label{fig:quad_sampling_1K_med}} \subfigure[IQM] { \includegraphics[width=1\textwidth]{figures/figure2_1K_iqm.pdf} \label{fig:quad_sampling_1K_iqm}} \subfigure[Optimality Gap] { \includegraphics[width=1\textwidth]{figures/figure2_1K_opgap.pdf} \label{fig:quad_sampling_1K_og}} \caption{Aggregate metrics of PEBBLE on Quadruped with 1000 queries across ten runs. Higher mean, median and IQM scores and lower optimality gap are better. The CIs are estimated using the percentile bootstrap with stratified sampling.} \label{fig:quad_sampling_1K} \end{figure*}
{'timestamp': '2021-11-05T01:21:55', 'yymm': '2111', 'arxiv_id': '2111.03026', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03026'}
arxiv
\section{Introduction} Hand dexterity is fundamental to daily human activities, requiring complex and precise control of finger movements. While most animals exhibit fine-grained motor controls for movement and many show elementary skills for manipulation, the functionality and the efficacy of human dexterity is unrivaled by others, rendering humans the unique ability to perform most sophisticated tasks with ease. Therefore, developing similarly-intelligent control strategies for robotic hands has been considered a holy grail for research on autonomous robots. However, it is an exceptionally challenging problem because of its high-dimensional action space and complex intermittent hand-object interactions. Reinforcement learning (RL) has been growing in popularity for solving sensorimotor control tasks because of its capability to discover behaviors without laborious manual engineering~\cite{heess2017emergence,levine2016end}. Prior works have also demonstrated that with large-scale compute, RL policies can acquire useful skills to control dexterous hands from purely simulated experience and perform complex tasks in the real world, including in-hand rotation~\cite{andrychowicz2020learning} and solving Rubik's Cube~\cite{akkaya2019solving}. \begin{figure}[t] \centering \includegraphics[scale=.25]{images/teaser.jpg} \vspace{-0.25in} \caption{\small Our goal in this work is to train a single policy that can perform in-hand manipulation on a large number of objects. We show surprising results that simple multi-task learning combined with appropriate representation not only achieves the aforementioned goal but also outperforms the single-task oracles, on both training and unseen objects.} \vspace{-0.1in} \label{fig:teaser} \end{figure} \begin{figure*}[t] \centering \includegraphics[width=\linewidth]{images/method.pdf} \vspace{-0.1in} \caption{\small We show that simple extensions to existing RL algorithms can produce geometry-aware dexterous manipulation policies that are robust to over 100 diverse objects. We first train an object representation encoder using object point clouds (left). Then we perform multi-task RL training on a large number of objects leveraging the encoded object representation (right).} \vspace{-0.15in} \label{fig:method} \end{figure*} However, the manipulation policies developed by these methods are typically only concerned with a single pre-determined object, making them impractical for real-world use. As there are countless objects a robot may encounter in the real world, it is infeasible to develop an individual system for each of them. Therefore, it is imperative for a policy to exhibit strong robustness to object variations, preferably in a zero-shot manner as humans do. However, generalization to completely unseen and geometrically-diverse objects for dexterous manipulation policies has been under-explored in the community, mostly due to the specious belief that such generalization is out of reach for current RL algorithms. In this work, we show that with simple modifications, existing RL algorithms can produce strong and generalizable policies for a robotic hand with high degrees of freedom. First, we show that contrary to the common belief of the community, a multi-task jointly-trained policy does not necessarily lead to decreased performance than if it were to be trained on each task individually. In fact, we show that in the context of dexterous manipulation, a multi-task policy can be a \textit{generalist} that can match the performance of those single-task \textit{specialist} policies. Second, we demonstrate that with appropriate representation that can meaningfully associate the tasks, such a multi-task policy can even outperform the single-task \textit{specialists} on completely unseen objects, where the \textit{specialists} are trained on those objects. Furthermore, we show a linear scaling effect of better generalization when trained on more objects, revealing the possibility of future improvement. We hope that our work can serve as a key step towards building a general-purpose controller for dexterous hands. Our contributions are as follows: \begin{itemize} \item We show that a multi-task policy trained on many objects can match the performance of the oracles, i.e. policies trained on those objects individually. \item We present a simple representation encoder that not only facilitates training but also leads to stronger zero-shot performance on unseen objects than what is possible by the oracles of those objects. \item We provide detailed analysis of the potential scaling effect and the relevant design decisions of our method. \item We release a simulated benchmark, built upon OpenAI Gym~\cite{openaigym} and existing 3D object datasets, that contains over 100 geometrically-diverse real-world objects to encourage future studies of dexterous hand manipulation and generalization properties. \end{itemize} \section{Geometry-Aware Multi-Task Learning} Prior works have shown that a standard off-policy algorithm DDPG~\cite{lillicrap2015continuous} combined with an implicit curriculum method HER~\cite{andrychowicz2017hindsight} can learn dexterous manipulation policies to control an object with simple geometries, such as a cube or an egg~\cite{plappert2018multi}. However, whether a single policy can work well on a large number of geometrically-diverse objects has been under-explored. To this end, we first show that a simple extension to the existing algorithm can lead to a high-performing policy on diverse objects. Then we present a representation encoder module that can meaningfully leverage skills learned from different tasks, and we show the additional strong generalization properties it provides when appropriately leveraged in policy learning. \subsection{Multi-Task Joint Training} A straightforward way to implement a policy $\pi_{\theta_p}$, parameterized by $\theta_p$ where $p$ stands for "policy", that can manipulate a large number of $N$ objects is to train the policy on those objects jointly. We thus formulate it as a multi-task learning problem, where the goal is to optimize the sum of rewards across all $N$ objects: \begin{align} \text{max}_{\theta_p}\; \mathlarger{\mathbb{E}}_{\pi_{\theta_p}} \;\mathlarger{\sum}_{i=1}^N \mathlarger{\sum}_{t=0}^{\infty} \bigg[ \gamma^t\; r_t^i(s_{t}, \; \pi_{\theta_p}(s_t)) \bigg] \label{eq:policy} \\ \text{where} \; \gamma \; \text{is the discount factor.} \nonumber \end{align} We refer to such a multi-task policy as \textbf{Vanilla Multi-Task Policy}. A conventional wisdom is that a multi-task agent needs to act conservatively to simultaneously learn multiple tasks as a result of challenging joint optimization. However, to our surprise, a dexterous manipulation policy trained with this simple objective function can perform in-hand rotation remarkably well on a large number of objects. In fact, as we will show in Section~\ref{sec:joint-train}, a joint policy is comparable to individual single-task oracle policies on the trained objects while being $17$ times more sample-efficient. We optimize the objective in Equation~\ref{eq:policy} using the same DDPG and HER setup used for training a single object, with only one modification that gradients are summed over all tasks before applying updates. \subsection{Geometry-Aware Object Representation} \label{sec:method-rep} One issue arises when naively following the above setup to train a single policy on many different objects: the objects are indistinguishable from each other to the policy, and the policy would likely find a common strategy for all the objects due to the effect of joint optimization. Yet humans execute different finger gaits to manipulate geometrically different objects, and we desire the same property to emerge for a robotic hand policy. In fact, in addition to the standard proprioceptive inputs (i.e. joint positions and joint velocities of the robot), most existing works only consider the 6 DoF pose of the object in the state space as a result of single-object training. To explicitly model the object geometries, we propose to learn an object representation encoder based on object point clouds. A standard approach to learn useful representation such that different objects can be distinguished is to perform classification. However, as we want the representation to beneficial for the downstream in-hand rotation task and potentially useful for the policy to model hand-object contact implicitly, the representation has to be rotation-aware. A natural implementation for this might be predicting the rotation matrix based on the input point cloud. However, in the presence of many different objects, we lack a canonical coordinate frame for them, making rotation matrix prediction based on a single point cloud an ill-defined problem. We resolve this by making the encoder module take as input two copies of the same object point cloud. The first describes the current orientation at time $t$ and the second describes the desired orientation. The encoder is tasked with predicting the correct class of the object and the relative rotation matrix between the two point clouds. We build the encoder module using a $3$-layered PointNet~\cite{qi2017pointnet} parameterized by $\theta_e$. The training objective is defined as: \begin{align} \min_{\theta_e}\; & L_{e} = L_{cls} + \alpha L_{rot} \label{eq:encoder} \\ & \text{where} \; \alpha \; \text{is weighting coefficient.} \nonumber \end{align} $L_{cls}$ is standard cross entropy loss for classification. Following~\cite{suwajanakorn2018discovery}, we define the rotation prediction loss $L_{rot}$ as: \begin{align} & L_{rot} = 2 \; \text{arcsin} \; \bigg(\frac{1}{2 \sqrt{2}} \big\Vert \hat{R} - R \big\Vert_{F} \bigg) \label{eq:rotation} \end{align} We first pre-train the encoder on the set of training objects by randomly sampling points on object surface and randomly rotating the point cloud and its copy. After pre-training, we freeze the encoder's weights and use it in the RL training by conditioning both actor and critic networks on the encoded representation. We refer to such multi-task policy equipped with object representation as \textbf{Geometry-Aware Multi-Task Policy}, which is the main contribution of this paper. \section{Experiment Setup} \label{sec:exp-setup} We investigate our approach in the MuJoCo~\cite{todorov2012mujoco} simulated environments of the Shadow Dexterous Hand, an anthropomorphic robotic hand with $24$ degrees of freedom. We consider the task of in-hand rotation, a commonly-evaluated task for dexterous manipulation. The goal is to rotate an object to a pre-specified orientation, without dropping the object. Below we discuss the details of the evaluated objects and the environment design. \subsection{Evaluated Objects} \label{sec:objects} The standard benchmarks like the Shadow Hand tasks from OpenAI Gym~\cite{openaigym} often contain a limited number of objects. To better study the generalization properties across objects, we build upon the existing environment in Gym by extending it with two object datasets, ContactDB~\cite{brahmbhatt2019contactdb} and YCB~\cite{calli2015ycb}. The two datasets contain a diverse set of real-world objects, representative of those that would often be manipulated in daily life. Since many of the object meshes are too large for in-hand manipulation, we proportionally scale down each object along its shortest axis such that the object can be fit into the palm and can be touched by the fingers. After scaling, the longest axis of all objects has an average length of $0.102m$ and a range of $[0.065m, 0.130m]$, and the shortest axis has an average length of $0.057m$ and a range of $[0.010m, 0.065m]$. Finally, to ensure the diversity of the dataset, we visually inspect each object and filter out the geometrically similar ones. In the end, we obtain a set of $114$ objects. A subset of the objects are visualized in Fig~\ref{fig:teaser}, Fig~\ref{fig:method}, and Fig~\ref{fig:spectrum}. \subsection{Train/Test Split} \label{sec:split} To study the generalization properties of the proposed method, we split the objects into two disjoint sets of $85$ and $29$ objects, one for training and the other one for zero-shot testing. Because the object geometries are vastly different from each other, leading to different levels of difficulties for the manipulation policies, a random split may not ensure fair evaluations. Therefore, we use the same DDPG + HER algorithm to train an oracle single-task RL policy for each object, following the setup from~\cite{plappert2018multi}. Then we split the objects according to the success rate of its oracle, ensuring that the training and held-out objects have similar difficulties on average. \subsection{Environment Details} \label{sec:env-details} \paragraph{State Space} We define the state space $s = \{s_{r}, s_{o}, g\}$. $s_{r}$ is the proprioceptive robot states which contain joint angles and joint velocities. $s_{o}$ contains the object's Cartesian coordinates, quaternion, translational velocities, and rotational velocities. For methods that use a point cloud encoder, $s_{o}$ also includes a set of $128$ points sampled from the surface of the object and their surface normal vectors. The points are re-sampled at each timestep. $g$ is a $4$-dimensional vector specifying the desired quaternion of the object. \paragraph{Action Space} The action is a $20$-dimensional vector containing desired absolute joint positions for the 20 non-coupled joints of Shadow Hand. The remaining 4 joints are coupled joints which do not require control input. The action frequency is $f = 25\;$Hz. \paragraph{Reward} At timestep $t$, the agent receives a binary reward $r_t$ of $1$ if the angle between current object orientation and goal orientation is within $0.1$ radians and $0$ otherwise. \paragraph{Environment Initialization and Goal Selection} Following the environment design in~\cite{plappert2018multi}, initial position of object is set to be above the palm to avoid penetration with the hand and further perturbed with a Gaussian noise sampled from $N(0, 5\mathrm{e}{-5})$. The initial and goal orientation are sampled independently and randomly about the $z$-axis for each episode. With a diverse set of objects, we find this setting to be a good middle ground for the oracle policies we consider~\cite{plappert2018multi}, not as difficult as sampling from $SO(3)$ and not too easy as sampling from a set of pre-determined goals. \section{Results and Ablations} \label{sec:experiments} Instead of focusing on how a policy performs on a specific object, our goal is to evaluate its zero-shot generalization to unseen ones. To this end, except for the oracle policies that serve as references, we evaluate all methods using the train/test split described in Section~\ref{sec:split}. Videos at~\url{https://huangwl18.github.io/geometry-dex}. We examine the effectiveness of our proposed method by asking the following three questions: \begin{itemize} \item Can vanilla multi-task policy attain competitive performance on a large number of objects? \item Leveraging object representation, can a single geometry-aware policy interpolate its experience and outperform single-task oracles? \item{What are the generalization properties of a geometry-aware policy?} \end{itemize} For each experiment, we report the success rate at the last timestep of an episode, averaged over $3$ training runs with different random seeds. \subsection{Effectiveness of Multi-Task Training} \label{sec:joint-train} In this section, our goal is to investigate the effect of joint multi-task training alone, without leveraging object representation. We refer to such policies as \textbf{Vanilla Multi-Task Policy}. It is supplied with $s_{o}$ which only contains the object's 6 DoF pose. Below we discuss its training and generalization performance. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{images/rep_oracle_train.pdf} \caption{\small Success rate difference between geometry-aware multi-task policy and individual oracles on the 85 training objects, calculated as $\Delta S = (S_{\text{ours}} - S_{\text{oracle}})$. It shows that a single geometry-aware multi-task policy can attain even better performance than individual single-task oracles on most training objects. It demonstrates that the policy can leverage skills learned from many tasks, leading to an overall stronger policy. The success rate reported are averaged across 100 episodes.} \vspace{-0.25in} \label{fig:multi_oracle} \end{figure} \paragraph{Training Performance} We first compare the vanilla multi-task policy to the individual oracle policies trained for each object. We train the policy jointly on all 85 training objects. As shown in Fig~\ref{fig:multi_repr}, the vanilla multi-task policy is surprisingly effective in learning a joint policy for all training objects, attaining a performance on par with each object's oracle policy. In fact, it also converges to the average performance of the oracles. Furthermore, the joint-trained policy is $17$ times more sample efficient than the ensemble of single-task oracles, needing a total of $200$M samples compared to $3400$M used by all oracles. \paragraph{Zero-Shot Generalization} As shown in Fig~\ref{fig:multi_repr}, the vanilla multi-task policy, when evaluated on the 29 unseen objects in a zero-shot manner, performs only slightly worse than the oracles trained for the held-out objects. It shows that a simple vanilla multi-task training can produce surprisingly effective policy to handle most objects at test time. However, by ranking the objects by the performance difference between the multi-task policy and the oracles, we find that the multi-task policy generally has similar performance to the oracles on medium-sized spherical objects and performs significantly worse on irregular-shaped objects. Similar observation and analysis are also provided in Sec~\ref{sec:rep-generalization}. Overall, our suggests that the multi-task policy, though performing well on majority of objects, likely finds a common strategy that works well for majority of objects but fails to handle the uncommon ones. We refer the readers to the videos for qualitative results. \subsection{Role of Object Representation} In this section, we aim to tackle geometry-awareness by investigating the role of object representation in learning multi-task dexterous manipulation policies.\footnote{We note that the representation is multi-task in nature as it is obtained by a point cloud encoder that is pre-trained on all objects, instead of a single object. Since the pre-training task is classification, a single-task representation is trivially not meaningful under this setting.} The representation is expressed as a $512$-dim feature vector taken from the last layer of a frozen point cloud encoder, described in Section~\ref{sec:method-rep}. It is updated every timestep using the latest sampled point cloud along with its rotated copy that indicates the goal orientation. We will first compare the training performance of the geometry-aware policy to its vanilla counterpart, and then we will discuss the remarkable generalization properties by making use of object representation. \begin{figure}[t] \vspace{0.06in} \centering \includegraphics[scale=.48]{images/repr_train_test.pdf} \caption{\small Average success rate across $85$ training objects and across $29$ held-out objects. The plot shows that multi-task joint training can lead to a surprisingly robust policy on both training and testing, with similar performance compared to the average of individual single-task oracle trained for each object. Furthermore, when combined with object representation, a joint policy can even outperform the oracles on held-out objects, in a completely zero-shot manner. The success rate reported are averaged across 425 and 145 episodes, respectively for all training objects and all held-out objects.} \vspace{-0.1in} \label{fig:multi_repr} \end{figure} \paragraph{Training Performance} As shown in both Fig~\ref{fig:multi_repr}, by making use of object representation, the joint policy significantly outperforms its vanilla variant. Notably, as shown by Fig~\ref{fig:multi_oracle}, it also outperforms the single-task oracles on most objects, demonstrating that when combined with correct representation, multi-task policy does not act conservatively with decreased single-task performance to accommodate other tasks, contradictory to the common belief of the community. Furthermore, it reaches the average oracle performance at $50$M timesteps while the ensemble of oracles is trained on $3400$M timesteps, showing that a multi-task policy combined with appropriate representation can effectively interpolate and leverage its experience across all tasks and attain an overall better performance. \begin{figure}[t] \centering \includegraphics[scale=.36]{images/sr-delta-spectrum.pdf} \caption{\small Visualization of held-out objects ranked by the performance gains of geometry-aware policy, calculated as $\Delta S = (S_{\text{ours}} - S_{\text{vanilla}})$. Notice that the gains are the highest for objects with irregular shapes and the lowest for medium-sized and spherical objects, showing the policy can effectively leverage object representation to adopt specific strategies even for challenging unseen objects.} \vspace{-0.23in} \label{fig:spectrum} \end{figure} \begin{figure}[t] \vspace{0.06in} \centering \includegraphics[width=\linewidth]{images/irregular-frames.pdf} \caption{\small The top row shows the progression of geometry-aware policy and the bottom row shows the vanilla policy on the "bleach\_cleanser" object. Image on the right of each hand shows goal orientation. Our geometry-aware policy can reason about shape and move thumb and finger accordingly so as to rotate the object while vanilla policy can't as shown by circles.} \vspace{-0.1in} \label{fig:frames} \end{figure} \paragraph{Zero-Shot Generalization} \label{sec:rep-generalization} We evaluate our method on 29 unseen objects in a zero-shot manner. As with the comparisons for training performance, Fig~\ref{fig:multi_repr} shows that the multi-task policy trained with representation is superior than both its vanilla counterpart and even the single-task oracles that are trained on held-out objects. To validate our hypothesis that the policy is geometry-aware and can effectively handle irregular-shaped objects, we rank all 29 held-out objects by the performance gains compared to the vanilla policy and visualize 5 objects on both sides of the spectrum in Fig~\ref{fig:spectrum}, where the gains are the highest and the lowest. Not only does the policy outperforms its vanilla counterpart on all held-out objects, but notably the objects for which the performance gains are the highest have the largest variations in shapes. It shows the vanilla policy has difficulties dealing with such objects, yet the policy endowed with object representation, though never trained on these objects, learns specific strategies based on their geometries. On the other side of the spectrum, we observe that the gains are the smallest for objects that are medium-sized and spherical-shaped, suggesting that a common strategy likely works well for these objects and geometry-awareness is not needed. To further investigate the behaviors learned by our method when dealing with challenging objects, we visualize both our method and the vanilla baseline on a held-out object, shown in Fig~\ref{fig:frames}. To successfully perform a 180-degree-turn for a long and thin object, a policy must execute precise finger movement to not only grasp the object firmly but also not have the object blocked by fingers. Consistent with our hypothesis, knowing the object geometry allows the policy to precisely grip the object using the little finger at $t = 10$ and move away the thumb at $t = 15$ which was blocking the object. On the contrary, such irregular-shaped object proves to be difficult for the vanilla policy that fails to make any progress to rotate the object. We refer the readers to the video results for more qualitative comparisons. \subsection{Ablations} \subsubsection{Does training on more objects lead to better generalization?} \begin{figure}[t] \centering \includegraphics[scale=.45]{images/scaling.pdf} \vspace{-0.05in} \caption{\small Comparisons of the effect of the number of training objects on zero-shot generalization. More training objects would lead to a more robust policy that can even surpass single-task oracles on held-out objects. } \vspace{-0.23in} \label{fig:scaling} \end{figure} We investigate the effect of the number of training objects on the zero-shot generalization to unseen objects. For each method, we run three sets of experiments with 10, 40, and 85 training objects respectively, where each set uses 3 random seeds. Then we evaluate the trained models on the same 29 held-out objects and report the average success rate over 145 episodes. As shown in Fig~\ref{fig:scaling}, both multi-task joint training models become gradually more robust to held-out objects when trained on more objects. Notably, the method that uses object representation exhibits better scaling law than the one that doesn't. It shows a promising sign that the trend could extrapolate when trained on even more objects than what are available in this work. \begin{table}[t] \vspace{0.06in} \centering \begin{tabular}{l|l|l} % & w/ Object Rep. & w/o Object Rep.\\ \midrule large\_clamp & $\bold{97.00\%}$ & $46.00\%$ \\ door\_knob & $\bold{84.00\%}$ & $65.00\%$ \\ large\_clamp & $\bold{92.00\%}$ & $74.00\%$ \\ \end{tabular} \caption{\small Effect of object representation used for single-task training. The objects are randomly selected from the held-out set. Even though the frozen encoder has not seen the objects in the pre-training phase, the encoded representation is still shown to be beneficial for single-task RL training, suggesting geometry-awareness is important for dexterous manipulation policies.} \label{tab:multirep-single} \end{table} \subsubsection{Can object representation boost performance of single-task policies?} Given the benefits shown for object representation when trained on a large number of objects, one natural question is what the effect is when it is used for a single task. Specifically, we take the point cloud encoder pre-trained on all 85 training objects, freeze its parameters, and use it to train an oracle policy for a held-out object from scratch, by using the same DDPG + HER algorithm. Note that the pre-trained and frozen encoder never sees the held-out object in training. Since evaluating on all 29 held-out objects are compute-intensive, we randomly select 3 objects whose average oracle success rate is similar to that of all held-out objects. We report the success rate of evaluating on 100 episodes. As shown in Table~\ref{tab:multirep-single}, the learned representation by pre-training on a large number of objects can also bring improvement to single-task training, demonstrating the object representation is universally useful for dexterous manipulation. As the majority of the current RL methods do not model object geometry explicitly, this result suggests that a geometry-aware policy may bring significant improvement to the current baseline. \begin{table}[t] \centering \begin{tabular}{l|l|l} % & Frozen Encoder & Fine-tuned Encoder\\ \midrule Training Success Rate & $\bold{71.88\%}$ & $61.62\%$ \\ Held-Out Success Rate & $\bold{68.80\%}$ & $59.84\%$ \\ \end{tabular} \caption{\small Comparisons of frozen encoder vs. fine-tuned encoder. Frozen encoder has much better performance than fine-tuned variant, whose performance is similar to that of vanilla multi-task policy without an encoder. The success rate reported are averaged across 425 and 145 episodes, respectively for 85 training objects and 29 held-out objects.} \label{tab:frozen-finetune} \vspace{-0.1in} \end{table} \subsubsection{Is it necessary to freeze the weights of point cloud encoder?} \label{sec:frozen} The object representation is obtained by a frozen, pre-trained point cloud encoder and has been shown to be useful in policy training. However, what if one allows the fine-tuning of the encoder? As shown in Table~\ref{tab:frozen-finetune}, a fine-tuned encoder leads to degraded performance, reducing to the same performance of a vanilla multi-task policy that doesn't have an encoder. A hypothesis is that the pre-trained encoder loses its useful representation early in the policy training due to the noisy gradient signals. \section{Related Works} \label{sec:related} There has been a rapid development of anthropomorphic robotic hands~\cite{butterfass2001dlr,xu2016design}, but realizing a human-level, precise, and intelligent control of high-DoF hands has remained an unsolved problem. A series of prior works based on motion planning and optimization have been developed~\cite{sundaralingam2018geometric,bai2014dexterous,dogar2010push,kolbert2016experimental,andrews2013goal,chavan2018hand}. However, these methods require precise characterization of the systems and often fail to scale up to more complex tasks. Data-driven learning approaches, on the other hand, provide a promising alternative to learn behaviors directly from data. Prior works have leveraged demonstrations collected by human to either perform imitation learning or facilitate discoveries of manipulation strategies~\cite{gupta2016learning,rajeswaran2017learning,radosavovic2020state,jeong2020learning,kumar2016learning}. Another line of works directly use reinforcement learning and learn policies without expert knowledge from humans~\cite{zhu2019dexterous,andrychowicz2020learning,akkaya2019solving,van2015learning,nagabandi2020deep,kumar2016learning,charlesworth2021solving}, but they often exhibit limited generalization capabilities:~\cite{kumar2016learning} shows generalization to different initial position of the object,~\cite{nagabandi2020deep} studies generalization to different goal settings,~\cite{rajeswaran2017learning} demonstrates generalization to the same object but with parametric variations of size and mass,~\cite{andrychowicz2020learning,akkaya2019solving} reveal the possibility of generalizing to the real world with only simulated experience but consider only one pre-determined object with simple geometries.~\cite{van2015learning,radosavovic2020state} study generalization to novel objects at test time as we do. However, they only consider generalization to one or few objects, many of which are geometrically similar to the training object. There has been growing interest and development in multi-task learning, where a single model is trained to perform multiple tasks simultaneously~\cite{teh2017distral, yu2020gradient, hessel2019multi, espeholt2018impala}. We note that the development of better multi-task learning algorithms is orthogonal to our method. As we adopt the simplest of its form by simply summing the gradients from all tasks, one may expect further improvement by leveraging the benefits provided by the state-of-the-art multi-task learning algorithm. Our approach of learning object representation also bears resemblance to learning task encoding in the context of multi-task reinforcement learning. This recent line of works typically encodes past experience into a task-specific embedding to interpolate learned skills from different tasks~\cite{hausman2018learning, duan2016rl, wang2016learning, mishra2017simple, rakelly2019efficient}. While these methods can be applied to dexterous manipulation to learn one policy for many objects, we propose to model the objects directly as the differences between each task are fully attributed to the differences in objects. \noindent\textbf{Concurrent Work:} A parallel work also studies dexterous manipulation on a variety of objects~\cite{chen2021simple}. However, their approach does not condition the multi-task learning on the object geometric representation. Hence, it forces the policy to discover a common "generally" good strategy that works across many distinct objects of simpler shapes but may suffer to generalize to objects of more challenging geometries. \section{Conclusion} \label{sec:conclusion} In this work, we present a simple framework for learning dexterous manipulation policies for a large variety of objects. We show that combined with simple multi-task learning and appropriate representation, existing RL algorithms can produce a single robust policy for over 100 diverse objects, which we also release as a benchmark. Overall, we hope our findings can serve as a key step towards developing general-purpose controllers for dexterous manipulation and facilitate future studies that further improve generalization across objects. \section*{Acknowledgements} We would like to thank Kenny Shaw and Aravind Sivakumar for feedback on the early drafts of the paper. The work was supported in part by Berkeley Deep Drive, NSF IIS-2024594 and GoodAI Research Award. \bibliographystyle{IEEEtran}
{'timestamp': '2021-11-05T01:22:41', 'yymm': '2111', 'arxiv_id': '2111.03062', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03062'}
arxiv
\section{Introduction} \label{sec:intro} \begin{figure}[t!] \centering \includegraphics[width=0.95\columnwidth,clip,trim=0 0 0 0.1in]{figs/teaser_task.pdf} \includegraphics[width=\columnwidth,clip,trim=0 2.9in 0 0]{figs/teaser_graph.pdf} \caption{We develop formal models of the predictions of neural language models in \emph{surprising contexts} in which local information (e.g.\ the most recent token) and global information (e.g.\ the rest of the sentence) conflict (top). In these out-of-distribution contexts, predictors trained on both synthetic and natural languages favor either local or global information, but are best approximated by an \emph{interpolation} of a local-only and global-only predictor (bottom).} \label{fig:teaser} \end{figure} Neural language models (LMs) play a key role in language processing systems for tasks as diverse as machine translation, dialogue, and automated speech recognition \citep{baziotis2020language,sordoni2015neural,mikolov2010recurrent}. These LMs, which model distributions over words in context via recurrent, convolutional, or attentional neural networks, have been found to consistently outperform finite-state approaches to language modeling based on hidden Markov models \cite{kuhn1994ergodic} or $n$-gram statistics \cite{miller1950verbal}. But improved predictive power comes at the cost of increased model complexity and a loss of transparency. While it is possible to characterize (and even control) how finite-state models will behave in previously unseen contexts, generalization in neural LMs is not nearly as well understood. Consider the following sentence prefixes: \begin{itemize}[noitemsep] \item[(a)] \textit{The pandemic won't end children can\ldots} \item[(b)] \textit{Let him easter\dots} \item[(c)] \textit{After we ate the pizza, the pizza ate\dots} \end{itemize} Each of these prefixes should be assigned a low probability under any reasonable statistical model of English: (a) is missing a word, (b) has a noun used in place of a verb, and (c) a features a selectional restriction violation.\footnote{In fact, all three are examples of naturally occurring text: (a) was originally published (as a typo) on the New York Times homepage \cite{nyttweet}, (b) appears in \citet{hopkins1918} and (c) in by \citet{bench2013}.} When exposed to these surprising contexts, what word will language models predict next? For finite-state models of language, the answer is clear: $n$-gram models back off to the shortest context in which statistics can be reliably estimated (e.g.\ just the final word; \citealt{katz1987estimation}), and hidden Markov models explicitly integrate the possibility of an unexpected part-of-speech transition and an unexpected word choice \cite{freitag1999information}. But in neural models, model behavior in-distribution provides little insight into behavior in novel contexts like the ones shown in (a--c). Characterizing neural LMs' behavior on inputs like these is important for many reasons---including evaluating their robustness, characterizing their effectiveness as models of human language processing, and identifying inductive biases relevant to deployment in new tasks. This paper offers three steps toward such a characterization: \begin{enumerate} \item We present an empirical description of neural LM behavior in out-of-distribution contexts like the ones shown in (a--c). We introduce two idealized models of prediction in these contexts: a \emph{local context model} in which generalization is consistent with the last word observed (ignoring global sentence structure), and a \emph{global context model}, in which generalization is consistent with the global structure of the input (ignoring unexpected words). In experiments on English, Finnish, Mandarin, and a collection of random regular languages, we show that neural LM behavior is reasonably well approximated by either the local or global context model, and even better predicted by an \emph{interpolation} of the two: neural LMs reconcile conflicting information from local and global context by modeling their contributions independently and combining their predictions post-hoc (\cref{fig:teaser}). \item We further show that, in regular languages, \emph{noise} introduced at training time modulates the relative strength of local and global context in this interpolation: input noise (in the form of random word substitution) encourages global generalization, while history noise (dropout applied to recurrent states or self-attention layers) encourages local generalization. These effects are small, but point toward a potential role for noise-based regularization schemes in controlling out-of-distribution behavior. \item Finally, we offer a preliminary mathematical explanation of the observed results by demonstrating that this interpolation behavior arises in any regularized log-linear model with separate local and global context features that are individually predictive of future tokens. \end{enumerate} Despite the complexity of current neural LMs, these results show that aspects of their out-of-distribution generalization can be characterized, controlled, and understood theoretically. \section{Background} \label{sec:background} \paragraph{Generalization in count-based LMs} Before the widespread use of neural approaches in NLP, statistical approaches to language modeling were typically \emph{defined} by explicit independence assumptions governing their generalization in contexts never observed in the training data. For example, $n$-gram models \citep{miller1950verbal,shannon1951prediction} ignore global sentence structure in favor of a local context of at most $n$ words. By contrast, latent-variable language models based on finite-state machines \citep{kuhn1994ergodic} (or more expressive automata; \citealt{chelba1998exploiting}, \citealt{pauls2012large}) explicitly incorporate information from the long-range context by conditioning next-word prediction on abstract global states constrained by global sentence structure. In models of both kinds, behavior in contexts unlike any seen at training time is be explicitly specified via \emph{backoff} and \emph{smoothing} schemes aimed at providing robust estimates of the frequency of rare events \cite{good1953population,katz1987estimation,kneser1995improved}. Like past work on backoff and smoothing, our work in this paper attempts to provide a general mechanism for both prediction and control in more complex, black-box neural LMs. \paragraph{Generalization in feature-based and neural LMs} Such mechanisms are necessary because, with the advent of feature-rich approaches to language modeling---including log-linear models \citep{rosenfeld1996maximum} and neural network models \citep{bengio2003neural,mikolov2010recurrent,vaswani2017attention}---the kinds of structured, engineered generalization available in finite-state models of language have largely been lost. Current models clearly generalize to new linguistic contexts (including those with semantic content very different from anything seen at training time; \citealt{radford2019language}). But the precise nature and limits of that generalization---especially its robustness to unusual syntax and its ability to incorporate information about global sentence structure---remain a topic of ongoing study. Current work largely focuses on controlled, linguistically motivated tests of generalization: measuring models' ability to capture long-range agreement, movement, and licensing phenomena on diagnostic datasets \citep[][]{gauthier2020syntaxgym}. For example, \citet{linzen-etal-2016-assessing} show that while RNNs are capable of storing the information necessary to enforce subject--verb agreement, the language modeling training objective does not encourage it; \citet{mccoy2020does} demonstrate that RNN models for a question formation task favor linear generalizations over hierarchical ones (roughly, lexical generalizations over syntactic ones) on out-of-distribution inputs. Rather than focusing on a specific language or class of linguistic phenomenon, our work in this paper aims to provide a general-purpose framework for reasoning about generalization in neural sequence models across contexts and languages. \paragraph{Generalization beyond NLP} The generalizations investigated in paper involve instances of covariate shift---a change in the distribution $p(x)$ for a conditional model $p(y \mid x)$---which has been extensively investigated in more general machine learning settings \citep[e.g.][]{storkey2009training}. Outside of NLP, there have been several attempts to describe more abstract inductive biases native to RNNs and transformers, including work focused on compositionality \citep{liska2018memorize,lake2018generalization,weber2018fine} and even more generic algorithmic priors \citep{lan2021minimum, kharitonov2020they}. Here we focus on the architectures and context shifts relevant to language processing tasks. We validate our models of generalization using real models trained on natural data and explain them in terms of measurable properties of these data distributions. \section{Models of Generalization} \label{sec:models} Consider the example contexts shown in (a--c). Each is an extremely unlikely sentence prefix, featuring text that is globally inconsistent with English syntax or semantic constraints. In such contexts, is it possible to predict \emph{a priori} what a neural LM trained on language data will do next? We can formalize the situation depicted in these examples as follows: Let $p(X_{1:n}) = p(X_1, X_2, \ldots, X_n)$ be a distribution over sentences with tokens $X_i$, and let \begin{equation} \lm(X_{1:n}) = \prod_{i=1}^n \lm(X_i \mid X_{1:i-1}) \end{equation} be a learned approximation to this distribution produced by an autoregressive model of the conditional distribution $\lm(X_n \mid X_{1:n-1})$. We will consider each \textbf{context} $X_{1:n-1}$ to comprise a \textbf{global context} $X_\mathrm{G} = X_{1:n-2}$ (all but the last word) and a \textbf{local context} $X_\mathrm{L} = X_{n-1}$ (the last word in the context). Then, given some thresholds $\epsilon$ and $\tau$, we will call a context $(X_\mathrm{G}, X_\mathrm{L})$ \textbf{surprising} if for some thresholds $\epsilon$ and $\tau$, \begin{align} \label{eq:eps} \lm(X_\mathrm{L} | X_\mathrm{G}) < \epsilon \\ \intertext{(the juxtaposition of $X_\mathrm{G}$ and $X_\mathrm{L}$ is low-probability), while:} \lm(X_\mathrm{L}) > \tau \\ \intertext{and each for each $i$} \lm({X_\mathrm{G}}_{,i} \mid {X_\mathrm{G}}_{,1:i}) > \tau \label{eq:tau} \end{align} ($X_\mathrm{G}$ and $X_\mathrm{L}$ are high-probability marginally). In example (c), $X_\mathrm{G} = $ \emph{the pizza}, $X_\mathrm{L} =$ \emph{ate}. Given a language model $\lm$, we wish to understand whether $\lm(X \mid X_\mathrm{G}, X_\mathrm{L})$ has systematic or predictable structure in surprising contexts---can it be explained in terms of statistics of the underlying distribution $p$ or the behavior of $\lm$ in unsurprising contexts? In the remainder of this section, we describe a set of candidate hypotheses about what this next-token distribution might look like, and in \cref{sec:experiments} evaluate the extent to which these hypotheses accurately predict the true behavior of $\lm$. \subsection{Local and global models of generalization} \label{sec:models-base} We focus on two idealized models of the generalization that might be exhibited by neural language models. \paragraph{Local context model} In this model, we hypothesize that predictors reconcile the conflicting information from $X_\mathrm{G}$ and $X_\mathrm{L}$ by ignoring the global component of the context, and making the next-token distribution \emph{locally} consistent with the last token seen, regardless of global sentence structure. We denote this model of generalization $\plocal$: \begin{equation} \plocal(X_n \mid X_\mathrm{G}, X_\mathrm{L}) \triangleq p(X_n \mid X_\mathrm{L}) ~ . \end{equation} $\plocal$ implements a form of backoff common in $n$-gram language models: faced with a long context in which the data distribution is unknown, models discard long-range information and use higher-quality estimates from a shorter context. We previously defined $X_\mathrm{L} = X_{n-1}$, so experiments with $\plocal$ will predict that neural LMs behave like bigram models; this could be naturally generalized to local contexts consisting of more than a single word. $\plocal$ can also be viewed as the hypothesis that NLMs implement a particular kind of lossy-context model \citep{futrell-levy-2017-noisy,futrell2020lossy}, who note that ``local contextual information plays a privileged role in [human] language comprehension''; as we will see, this appears to be the case for some neural models as well. Sequence models with backoff may also be given a hierarchical Bayesian interpretation \citep{teh2006bayesian}. \paragraph{Global context model} As an alternative, we consider the possibility that predictors rely \emph{exclusively} on the global component of the context, ignoring the unexpected final token: \begin{align} \pglobal(X_n \mid X_\mathrm{G}, X_\mathrm{L}) &\triangleq p(X_n \mid X_\mathrm{G}) \nonumber \\ &= \sum_v p(X_n \mid X_{n-1} = v, X_\mathrm{G}) \nonumber \\ & ~~~~ \times p(X_{n-1} = v \mid X_\mathrm{G}) ~ . \hspace{-2pt} \end{align} In the language of count-based models, this amounts to the hypothesis that NLMs generalize as \emph{skip-gram} models \citep{goodman2001bit,guthrie2006closer}, performing a kind of reverse backoff to context prior to the most recent word. In the global context model, it is the most recent word, and not the rest of the context, that as treated as a possible source of noise to be marginalized out rather than conditioned on. \subsection{Interpolated models} \label{sec:models-interp} Even when combined in surprising ways, both the local and global context are likely to carry useful information about the identity of the next word. Indeed, models and features implementing both kinds of context representation have been found useful in past work on language modeling \citep{goodman2001bit}. It is thus natural to consider the possibility that neural LMs \emph{interpolate} between the local context and global context models, combining evidence from $p(X_n \mid X_\mathrm{L})$ and $p(X_n \mid X_\mathrm{G})$ when there is no evidence for the specific context $p(X_n \mid X_\mathrm{L}, X_\mathrm{G})$. We consider two ways in which this evidence might be combined: \paragraph{Linear interpolation} In this model, \begin{align} \pinterpadd \triangleq \lambda \cdot \plocal + (1 - \lambda) \cdot \pglobal ~ . \end{align} Here we predict generalization according to a direct weighted combination of $\plocal$ and $\pglobal$, with the relative importance of the two hypotheses controlled by a parameter $\lambda \in [0, 1]$. Informally, this hypothesis assigns non-negligible probability to next tokens that are consistent with either base hypothesis. Similar interpolation schemes were proposed for $n$-gram modeling by \citet{jelinek1980interpolated}. \paragraph{Log-linear interpolation} In this model, \begin{align} \label{eq:llinterp} \pinterpmul &\stackrel{\triangle}{\propto} \pglobal^{\lambda_1} \cdot \plocal^{\lambda_2} ~ . \end{align} That is \begin{align} \log \pinterpmul &= \lambda_1 \log \pglobal + \lambda_2 \log \plocal - \log Z \end{align} for $\lambda_1$ and $\lambda_2 \in [0, 1]$ and some contextual normalizing constant $Z$ that depends on $X_{1:n-1}$. Here, probabilities from the two base hypotheses are added in log-space then renormalized; informally, this has the effect of assigning non-negligible probability to next tokens that are consistent with \emph{both} base hypotheses. A similar approach was proposed for count-based language modeling by \citet{klakow1998log}. \section{Experiments} \label{sec:experiments} Which of these models (if any) best describes the empirical behavior of neural LMs trained on real datasets? In this section, we present two sets of evaluations. The first aims to characterize how well $\plocal$, $\pglobal$, and combinations of the two predict the out-of-distribution behavior of RNN \citep{elman1990finding} and transformer \cite{vaswani2017attention} language models with standard training. The second explores whether these training procedures can be modified to control the relative strength of local and global generalization. Both sets of experiments investigate the behavior of RNN and transformer LMs on a diverse set of datasets: first, a collection of \emph{random regular languages} in which the true data distribution $p(X)$ can be precisely modeled; second, a collection of \emph{natural language} datasets from three languages (Mandarin Chinese, English, and Finnish) which vary in the flexibility of their word order and the complexity of their morphology. We begin with a more detailed discussion of models and datasets in \cref{sec:experiments-prelim}; then describe generalization experiments in \cref{sec:experiments-base} and control experiments in \cref{sec:experiments-interp}. \subsection{Preliminaries} \label{sec:experiments-prelim} \paragraph{Data: Formal languages} The first collection of evaluation datasets consists of a family of \emph{random regular languages}. We begin by generating three deterministic finite automata, each with 8 states and a vocabulary of 128 symbols. Using the algorithm in \cref{appendix:proofs}, we randomly add edges to the DFA to satisfy the following constraints: (1) every state is connected to approximately 4 other states, and (2) each symbol appears on approximately 4 edges. States are marked as accepting with probability $\frac{1}{2}$. Experiments on these carefully controlled synthetic languages are appealing for a number of reasons. First, because we have access to the true generative process underlying the training data, we can construct arbitrarily large training sets and surprising evaluation contexts $(X_\mathrm{G}, X_\mathrm{L})$ that are guaranteed to have \emph{zero} probability under the training distribution, ensuring that our experiments cleanly isolate out-of-distribution behavior. Second, the specific construction given above means that ``evidence'' for the local and global models of generalization is balanced: no tokens induce especially high uncertainty over the distribution of states that can follow, and no states induce especially high uncertainty over the set of tokens they can emit, meaning that a preference for local or global generalization must arise from the model rather than the underlying data distribution. In experiments on these datasets, we generate \emph{training} examples via a random walk through the DFA, choosing an out edge (or, if available, termination) uniformly at random from those available in the current state. We generate \emph{surprising} \emph{test} examples by again sampling a random walk, then appending a symbol that \emph{cannot} be produced along any out-edge from that random walk's final state. We compute $\plocal$ and $\pglobal$ using the ground-truth distribution from each DFA. In regular languages, the local context model thus hypothesizes that \emph{lexical} information governs out-of-distribution prediction, predicting that LM outputs are determined by the set of states attached to an edge labeled with the surprising symbol. Conversely, the global context model hypothesizes that \emph{structural} information governs out-of-distribution prediction: LM outputs are determined by the set of states reachable from the last state visited before the surprising symbol. RNN experiments use gated recurrent units \citep{cho2014learning} with a word embeddings of size 128 and a single hidden layer of size 256. Transformer experiments use a hidden size of 256, 4 self-attention layers, and ReLU nonlinearities. Both models are trained with the Adam optimizer and a learning rate of 3e$-$4 on 128,000 examples. \paragraph{Data: Natural languages} The second collection of evaluation datasets use natural language data. We conduct experiments on English, Finnish, and Mandarin Chinese. These languages exhibit varying degrees of morphological complexity and freedom of word order, with Finnish at one extreme (morphologically complex and freely ordered) and Mandarin at the other. English data comes from the WMT News Crawl corpus \cite{barrault-etal-2019-findings}. We used a 20,000-sentence subset of sentences from articles from 2007, tokenized using the SentencePiece byte-pair encoding \cite{sentencepiece} with a vocabulary size of $2^{14}$. We used a 2,000-sentence held-out set for validation. Finnish data comes from the Turku Dependency Treebank \cite{Haverinen2014}, and Chinese data from the Simplified GSD Treebank, both included in the Universal Dependencies corpus \cite{Nivre2020UniversalDV}. These datasets are already tokenized; for the Chinese data we used the existing tokenization, limited by a vocabulary size of $2^{14} - 2$ with added ``unknown'' and ``end-of-sentence'' tokens. For Finnish we also used the SentencePiece byte-pair encoding with a vocabulary size of $2^{14}$. \begin{figure*}[t!] \centering \includegraphics[width=0.98\textwidth,clip,trim=0 0 0 1cm]{figs/base-new} \vspace{-.5em} \caption{Accuracy $\textrm{acc}(\tilde{p}, \lm)$ of predicted generalization for various hypotheses $\tilde{p}$, with black lines showing one standard deviation across 5 (GRU) or 4 (transformer) random restarts. In some cases, generalization hypotheses are nearly as predictive as new neural models trained on the same data, suggesting that they explain most of extrapolation behavior that can be derived from data alone. Multiplicative interpolation is consistently a bit better than additive interpolation. Which of the two base hypotheses performs best (global or local generalization) varies substantially across languages. % } \label{fig:base} \end{figure*} To generate surprising natural language sentences $(X_\mathrm{G}, X_\mathrm{L})$, we first select $X_\mathrm{G}$ by truncating sentences from the validation set to uniformly random lengths. We then run our best trained model $\lm$ to determine $\lm(X_{n-1} | X_\mathrm{G})$, and choose a token $X_\mathrm{L}$ uniformly from among the set $\{X\ :\lm(X | X_\mathrm{G}) < \frac{1}{198}, X \in L\}$ where $L$ is the set of the 198 most-common tokens by unigram count (200 less the ``unknown'' and ``end-of-sentence'' tokens used in Chinese). In the framework of Equations \ref{eq:eps}--\ref{eq:tau}, $\epsilon$ is set to $\frac{1}{198}$ and $\tau$ to the smallest probability assigned in context to an in-distribution token. To compute generalization model predictions on natural language data, we estimate $\plocal$ from bigram counts in the training set: $\plocal(X_n | X_L) = \frac{\text{count}(X_n, X_L)}{\text{count}(X_L)}$. To estimate $\pglobal$, we train a second, random restart of the model $\lmp$. We then estimate $\pglobal$ using one step of beam search in $\lmp$ with a beam of size 15: \begin{multline} \label{eq:beam} \pglobal(X_n | X_\mathrm{G}) \\ \approx \sum_{i = 1}^{15} \lmp(v_i | X_\mathrm{G}) \lmp(X_n | X_\mathrm{G}, v_i) \end{multline} where the $v_i$ range over the 15 top predicted tokens after $X_\mathrm{G}$. Given a trained model that performs well on the \textit{in-distribution} validation set, we will have $\lm(v | X_\mathrm{G}) \approx p(v | X_\mathrm{G})$ and $\lm(X_n | X_G, v) \approx p(X_n | X_G, v)$, and therefore that \cref{eq:beam} gives a good approximation of $\pglobal$.\footnote{We compute this quantity with a second language model in order to prevent information about the true model's out-of-distribution behavior from leaking into our prediction.} For each natural language datasets, we trained GRUs with 2 hidden layers and word embedding and hidden sizes of 1024, and transformers with 4 heads, 2 layers, and hidden sizes of 512. All models were optimized with Adam using a learning rate of 3e-4 on shuffled length-aligned batches of up to 128 for 15 epochs. The model with the best held-out performance was then selected. \subsection{Which model of generalization fits best?} \label{sec:experiments-base} Given a dataset of surprising contexts $\{(X_\mathrm{G}, X_\mathrm{L})_i \}$, a hypothesis $\hyp$, and a trained model $\lm$, we compute the accuracy of the hypothesis $\hyp$ as \begin{align} \label{eq:acc} &\text{acc}(\hyp, \lm) = 1 - \text{err}(\hyp, \lm) \end{align} where \begin{align} &\text{err}(\hyp, \lm) = \nonumber \\ &\qquad \frac{1}{n}\sum_{X_\mathrm{G}, X_\mathrm{L}} \delta(\lm(\cdot \mid X_\mathrm{G}, X_\mathrm{L}), \hyp(\cdot \mid X_\mathrm{G}, X_\mathrm{L})) \nonumber \end{align} and $\delta$ is the total variation distance \begin{align} \delta(p_1, p_2) = \frac{1}{2} \| p_1 - p_2 \|_1 ~ . \end{align} In other words, we measure the accuracy of each hypothesis by computing the average $\ell_1$ distance between the hypothesized and true probability histograms across surprising contexts. $\text{acc}(\hyp, \lm)$ is between 0 and 1; a large value indicates that $\hyp$ is a good approximation to $\lm$.\footnote{The use of a bounded distance measure is important---intuitively, we should regard a hypothesis as accurate even if it makes very inaccurate predictions in a small fraction of contexts. However, the specific choice of measure does not appear to be very important; defining $\textrm{err}$ in terms of the Jensen--Shannon divergence gives similar results. } For hypotheses $\hyp$, we use (1) the local and global context (\cref{sec:models-base}), and (2) \emph{optimal} linear and log-linear interpolations between them (\cref{sec:models-interp}), choosing settings for $\lambda$ that minimize error on the evaluation set itself. To provide context for these results, we report the accuracy of a \textbf{unigram baseline}, which predicts the unigram distribution $p(X_n)$ independent of the context. We additionally report the error obtained by a \textbf{random restart}---a new model $p_{\theta'}$ trained from scratch (with a different initialization) on the same data as $\lm$; this model provides a rough upper bound on how much of $\lm$'s prediction can be explained by structural properties of the data distribution itself. $\mathrm{err}$ was computed from 100 samples for regular languages and 200 samples for natural languages. Results are shown in \cref{fig:base}. In each language, either the local or global model is a good fit to observed generalization behavior. There are substantial differences across languages: the local context model is a good predictor for regular languages and English, but a poor predictor for Finnish and Chinese, suggesting that generalization behavior is data-dependent but not tied to word order or morphological complexity. In general, GRU generalization is more predictable than transformer generalization. Finally, interpolation often substantially outperforms either base hypothesis (\cref{fig:interp-curve}), with log-linear interpolation slightly more predictive than linear interpolation. In several cases, interpolated hypotheses approach the accuracy of a randomly retrained predictor, suggesting that they capture much of the generalization behavior that is determined by the underlying data alone. \begin{figure} \centering \vspace{-.5em} \includegraphics[width=0.9\columnwidth,clip,trim=0.2in 0in 0.1in 0.1in]{figs/overlaid.pdf} \vspace{-1em} \caption{Effect of the log-linear interpolation parameter $\lambda_1$ (fixing $\lambda_2 = 1 - \lambda_1$; \cref{eq:llinterp}) when predicting out-of-distribution behavior in language models. As shown in \cref{fig:base}, in English, an all-local hypothesis ($\lambda=0$) is better than an all-global hypothesis ($\lambda=1$), but true model behavior is best approximated by a log-linear combination of the two ($\lambda \approx 0.5$). Finnish and Chinese are also best approximated by an interpolation, but are closer to the global than the local hypothesis. \vspace{-1em}}. \label{fig:interp-curve} \end{figure} \subsection{What controls interpolation?} \label{sec:experiments-interp} The previous section showed that $\pinterpmul$ gives the best fit to the empirical distribution of neural LM predictions across contexts: out-of-distribution prediction in both RNNs and transformers involves a mix of global and local information, with the precise weighting of these two sources of information dependent on structural properties of the language being modeled. A natural next question is whether this weighting can be \emph{controlled}: that is, whether modifications can be made to models or training procedures that affect the relative importance of the local and global hypotheses. In this section, we explore \emph{noise} as a possible source of this control. Models of both perceptual (local) noise and retrieval (global / contextual) noise play a key role in computational models of human sentence processing \cite{levy2008noisy}. In machine learning, various kinds of noise injected at training time---most prominently dropout \cite{srivastava2014dropout}, but also label noise and random word substitution and masking---are widely used as tools to regularize model training and limit overfitting. Here, we investigate whether these noising procedures qualitatively affect the \emph{kind} of generalization behavior that neural LMs exhibit in the out-of-distribution contexts explored in \cref{sec:experiments-base}. We investigate two kinds of noise: random word substitution and hidden state dropout. In all experiments, this noise is applied at training time only; model inference is run noiselessly when evaluating fit in \cref{eq:acc}. When computing $\pglobal$ with \cref{eq:beam} in these experiments, $\lmp$ is also trained without noise to approximate $\pglobal$. \paragraph{Random token substitution} With probability $p$, input tokens are randomly replaced with samples from the unigram distribution. Random word substitution plays an important role in masking-based pretraining schemes \citep{devlin2018bert}. \paragraph{Hidden state dropout} With probability $p$, features of context representations (RNN hidden states and transformer self-attention outputs) are randomly set to zero \citep{semeniuta2016recurrent}. \paragraph{} Results are shown in \cref{fig:interp}. Across languages, word substitution modestly increases the predictive accuracy of the global context model, while sometimes decreasing the accuracy of the local context model. For natural languages, however, the improvement in the global context model is matched by improvements in the \textit{unigram} baseline, indicating that these results may simply indicate decreased context-dependence. In regular languages, symbol-swapping noise increases the performance of the global hypothesis without improving the baseline, suggesting reliance on global information has actually increased. In all cases, state dropout improves the predictive accuracy of the local context model and often decreases the accuracy of both the global context model and the unigram baseline, suggesting indicating that state dropout encourages local generalization. \begin{figure}[t] \centering \includegraphics[width=\columnwidth,clip,trim=0.25in 2in 2.5in 0.25in]{figs/final_grid_nice.pdf} \caption{Accuracy $\textrm{acc}(\tilde{p}, \lm)$ of predicted generalization for English, Finnish, and regular-language GRUs when trained with token-swapping noise and state dropout noise. Token swapping sometimes improves the accuracy of the global context model, while state noising improves the accuracy of the local context model. Similar trends occur with Chinese; see Appendix \ref{appendix:extra-interp}.} \label{fig:interp} \end{figure} \section{Explaining the experiments} \label{sec:theory} With empirical evidence that interpolation between local and global models is a good approximation to out-of-distribution language model behavior, we next investigate whether this behavior can be explained theoretically. While we leave for future work a complete answer to this question, we conclude with the following proposition, which describes a set of conditions under which LM generalization will be well approximated by log-linear interpolation between $\plocal$ and $\pglobal$. \begin{proposition} \label{prop:main} Let $\theta$ be the parameters of a log-linear model optimizing: \begin{multline} \argmin_\theta \\ - \sum_{X_{1:n}} \log p(X_{n} \mid X_{1:n-1}; \theta) + \lambda \|\theta\|^2 \end{multline} where $p(X_n \mid X_{1:n-1}) \propto \exp\{ \theta_{X_n}^\top \phi(X_{1:n-1}) \}$ and $\phi(\cdot)$ has an indicator feature for each value of $X_\mathrm{G}$, $X_\mathrm{L}$, and the conjunction $(X_\mathrm{G}, X_\mathrm{L})$. Suppose further that models with \emph{only} local or global features are boundedly worse than this model: specifically, that: \begin{equation} \mathbb{E} |p(X_n \mid X_\mathrm{G}, X_\mathrm{L}) - p(X_n \mid \tilde{X})| < \epsilon \end{equation} uniformly for \emph{training} $\tilde{X}$ equal to either $X_\mathrm{G}$ or $X_\mathrm{L}$. Then, in surprising contexts, $p(x_n \mid x_{1:n-1}; \theta)$ can be approximated by $\tilde{p}_\times$: \begin{align} &\Big|p(X_n \mid X_\mathrm{G}, X_\mathrm{L}; \theta) \nonumber \\ & ~~~~ - ~ \tilde{p}_\times(X_n \mid X_\mathrm{G}, X_\mathrm{L}) \Big| < e^{4 \epsilon / \lambda} - 1 \end{align} where $\tilde{p}_\times(X_n \mid X_\mathrm{G}, X_\mathrm{L}) \propto \tilde{p}(X_n \mid X_\mathrm{G})~\tilde{p}(X_n \mid X_\mathrm{L})$ and each $\tilde{p}(X_n \mid X_\mathrm{L} \text{ or } X_\mathrm{G})$ is an $\ell_2$-regularized estimate of the corresponding distribution. \end{proposition} \noindent In other words, for log-linear language models with informative local and global features, the observed effectiveness of multiplicative interpolation is expected. Proof is given in \cref{appendix:proofs}. It is important to qualify this result in several ways: it relies on a feature function $\phi$ that may not be a realistic representation of the context feature produced by deep network models, involves strong assumptions about the independent predictive power of local and global features at training time, and becomes vacuous for large values of $\epsilon$ or small values of $\lambda$. It is weak in absolute sense ($e^{4\epsilon/\lambda}$ grows considerably faster than $\epsilon$ except for very large values of $\lambda$); its function is simply to relate predictions in surprising contexts to measurable properties of the training distribution. Nevertheless, the result shows that some aspects of interpolation behavior can be predicted from the parametric form of predictors alone; future work might strengthen this claim to more directly characterize the neural network predictors studied in this paper and explain the observed differences across languages. \section{Conclusion} When neural sequence models are exposed to out-of-distribution contexts with conflicting local and global information, their behavior can be predicted. Across natural and synthetic data distribution, sequence model generalization appears to be well approximated by either a local ($n$-gram-like) or global (skip-gram-like) predictor, and best approximated by a log-linear interpolation of the two whose weight can sometimes be controlled by noise-based regularization. This work suggests several avenues for future exploration: first, explaining \emph{data-dependent} aspects of the local--global tradeoff (especially cross-linguistic differences that are not clearly explained by typological differences between languages); second, determining whether \emph{architectural} improvements to standard sequence models can even more effectively target specific kinds of structured generalization. \section*{Acknowledgments} This research was supported by the MIT--IBM Watson AI Lab. \bibliographystyle{acl_natbib}
{'timestamp': '2021-11-08T02:02:28', 'yymm': '2111', 'arxiv_id': '2111.03108', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03108'}
arxiv
\section{Introduction} Brain-computer interfaces (BCIs) aim at translating brain activity into commands for control or communication~\cite{wolpaw_braincomputer_2002}. This technology raises hope for a lot of patients as it presents many clinical applications from the control of wheelchairs~\cite{carlson_brain-controlled_2013} to the communication with relatives \cite{naci_brains_2013} going through stroke rehabilitation~\cite{cervera_braincomputer_2018}. Mastering BCI control via a voluntary modulation of the cerebral activity remains a learned skill that requires subject training. Besides, a non-negligible portion of BCI users (around 30 \%) cannot control a BCI system after completing a training program. This phenomenon, associated to a high inter-subject variability, is referred in the literature as the ``BCI inefficiency''~\cite{thompson_critiquing_2018} and affects the usability of the BCI among the patients. To circumvent it, several approaches have been adopted. Among them are the proposal of new interaction paradigms~\cite{vidaurre_enhancing_2019}, the search of BCI performance predictors~\cite{blankertz_neurophysiological_2010-1, ahn_performance_2015, hammer_psychological_2012} and the design of more sophisticated classification algorithms to better discriminate the subjects' mental state~\cite{dahne_spoc_2014,de_cheveigne_joint_2014,sabbagh_predictive_2020}. In particular, Riemannian geometry-based methods \cite{yger2016riemannian, congedo2017riemannian} are now the gold standard by reaching the state-of-the-art performance~\cite{lotte_review_2018} and by winning several data competitions\footnote{See for example the $6$ competitions won by A. Barachant: \url{http://alexandre.barachant.org/challenges/}}~\cite{corsi_riemannian_2021}. Another approach would consist in taking into account the subjects' specificity by considering alternative features to be classified. In the particular case of left (or right) motor-imagery (MI) based BCI, the system relies on the desynchronization effect associated with a decrease of the power spectra computed within the contralateral sensorimotor area~\cite{pfurtscheller_event-related_1999}. Therefore, experimenters typically choose power spectra estimated in channels located above sensorimotor area as features. However, it does not capture the changes in communication between brain areas or said differently, it does not take into account the interconnected nature of brain activity. Functional Connectivity (FC), estimating the interaction between different brain areas~\cite{de2014graph,bastos_tutorial_2016}, is a promising tool for BCI~\cite{hamedi_electroencephalographic_2016, gonzalez-astudillo_network-based_2020}. Indeed, it has been proved to provide alternative features to discriminate subjects' mental states \cite{cattai_phaseamplitude_2021,cattai_improving_2021} and to study brain networks reorganization underlying MI-based BCI training~\cite{corsi_functional_2020, corsi_bci_2021}. On the above-mentioned elements, we hypothesized that combining functional connectivity estimators, Riemannian geometry and ensemble learning will lead to a performance improvement. Furthermore, we expect that the analysis of the selected features will give insights on the brain interactions the most relevant during MI-based BCI performance. Promising preliminary results have been obtained during the IEEE WCCI Clinical BCI Challenge~\cite{corsi_riemannian_2021}, where this approach ranked first on one of the two proposed tasks. In this paper, we led a comprehensive study in order to optimize the key parameters (functional connectivity estimators and frequency bands of interest) and to ensure the replicability of our results. \section{Materials and Methods} \subsection{Riemannian geometry} Riemannian geometry deals with smoothly curved spaces that locally behave like Euclidean spaces. For example, orthogonality or definite positive constraints in matrices can be shown to be smooth and can be dealt with a Riemannian geometry. In the manner of Russian dolls, Riemannian manifolds are built as the result of nested mathematical structures and this description goes beyond the scope of this introduction, we refer any interested reader to~\cite{yger2016riemannian} and references therein. The key point to remember is that a Riemannian manifold can be locally linearized at any point by a tangent space and each tangent space can be equipped with a scalar product. The notion of tangent space at a given point can be understood as the gradient of the curves passing through this point. For any Riemannian manifold, there exists a pair of inverse operations mapping points from the manifold to any given tangent space and vice versa. The exponential mapping transports a tangent vector, \emph{i.e.}, a point in a tangent space, to the manifold and the logarithmic mapping is locally defined to transport a point in the neighborhood of a point to the tangent space defined at this point. Then, the scalar product that equips each tangent space enables to measure distances in any tangent space. The definition of the geodesic, \emph{i.e.}, the shortest path on the manifold between two points, is inherited from the choice of the scalar product. For certain matrix constraints, several geometries can be defined over the same space but the choice of equipped scalar product will make a difference. The length of such geodesic then serves to measure the distance between two points along the curved surface. As a consequence, it becomes possible to extend some approaches in the Riemannian domain by substituting the Euclidean distance by a Riemannian distance. For example, for a given manifold $\mathcal{M}$ equipped with a Riemannian distance, the Fr\'echet mean extends the concept of mean and is defined as : \begin{align*} \Bar{X} = arg \min_{X\in \mathcal{M}} \sum_i \delta_r^2(X_i, X) \end{align*} Note that this is an optimization problem on a matrix manifold and taking advantage of the tangent spaces (together with approximations of the exponential mapping) it becomes possible to efficiently solve such a problem~\cite{absil2009optimization, boumal2020introduction}. A Riemannian average can be used to build a simpler yet robust classifier known as Minimum Distance to the Mean (MDM) where each class is represented by its Riemannian average and matrices are classified according to the closed class. Let us focus on the space of SPD matrices, noted $\mathcal{P}_n = \{X \in \mathbf{R}^{n \times n} | X = X^\top , X \succ 0\}$\footnote{In other words, it is the space of symmetric matrices of strictly positive eigenvalues}. It has been used successfully for handling covariance matrices from EEG signals. At every point $X$ of the space of SPD matrices, the tangent space $T_X \mathcal{P}_n $. Depending on the choice of the scalar product to equip the tangent spaces, one Euclidean and two different Riemannian geometries are defined for any pair of SPD matrices $X$ and $Y$ \begin{itemize} \item Euclidean distance : $\delta_e \left(X,Y\right) = ||X-Y||_\mathcal{F}$ \item LogEuclidean : $ \delta_{le}\left(X,Y\right) = ||\log(X)-\log(Y)||_\mathcal{F}$ \item Affine Invariant Riemannian Metric (AIRM) : $ \delta_{r}=\left(X,Y\right) =||\log (X^{-\frac{1}{2}}YX^{-\frac{1}{2}})||$ \end{itemize} The Euclidean distance is obtained by considering the space of SPD matrices as a subspace of the Euclidean space of symmetric matrices. Although this is quite natural and easy to implement, the Euclidean geometry suffers from three major drawbacks as documented in~\cite{yger2016riemannian}. First of all, in this geometry, it is possible to interpolate between SPD matrices but extrapolation can lead to a non-SPD result. Then, it is affected by the swelling effect, as the Euclidean interpolation between two matrices can have a bigger determinant as each of them and if we consider the determinant as a measure of information, interpolation then creates some artifact. Finally, it is not invariant to affine transformations (such as the left and right multiplication by an invertible matrix) and for example, if we scale $X$ and $Y$ by scalar bigger than $1$, the distance between them will grow. On the contrary, the AIRM distance is immune to those drawbacks but its computation is more computationally demanding. Hence, the LogEuclidean distance has been proposed as a trade-off between AIRM and LogEuclidean distances, retaining some interesting properties of the AIRM distance while being faster to compute~\cite{chevallier_review_2021}. Overall, the use of a Riemanning geometry (LogEuclidean or AIRM) leads to a simpler feature extraction step tampering with the need for spatial filtering and a less complex data processing pipeline. So far, the Riemannian geometry has been successfully applied for manipulating covariance matrices from EEG signals. The diagonal of those matrices carries information related to the electrodes power and it relates to the kind of information extracted by Common Spatial Patterns (CSP)-based methods. However, those matrices also contain the electrodes covariances and it is then a richer feature in terms of carried out information. Covariance matrices are at the heart of the interest for Riemannian geometry for BCI. However, connectivity information can be extracted in the form of SPD matrices and contains complementary information compared to covariance matrices. \subsection{Functional connectivity for EEG signals} \label{FC} Functional connectivity (FC) aims at estimating the interaction between different brain areas ~\cite{de2014graph,bastos_tutorial_2016}. There is plethora of FC estimators. Here, we considered complementary undirected FC estimators to identify which of them, being symmetric and positive definite, combined with Riemannian geometry, would best classify the data. For a given FC estimator, we averaged the FC values within specific frequency bands of interest. To ensure that all resulting matrices were SPD, ill-conditioned matrices were projected onto the manifold of SPD matrices, ensuring that all eigenvalues were strictly positive. \subsubsection{Spectral estimators} Two spectral estimators were considered here: the imaginary coherence and the instantaneous coherence. Both of them result from the coherency, \emph{i.e.}, the normalized cross-spectral density obtained from two given signals: \begin{equation} C_{ij}(f)=\frac{S_ij(f)}{\sqrt{S_{ii}(f).S_{jj}(f)}}\ \end{equation} where $S_{ij}(f)$ the cross-spectral density and $S_{ii}(f)$ the auto-spectral density. The imaginary part of coherence (ImCoh) is less sensitive to signal leakage and volume conduction effects~\cite{nolte_identifying_2004,colclough_how_2016}. The instantaneous coherence (Instantaneous) corresponds to the real part of the coherency~\cite{pascual-marqui_instantaneous_2007}. We estimated the cross-spectral density of each pair of EEG channels time courses, using multitapers \cite{slepian_prolate_1978}, with time windows of length 1 s with an overlap of 0.5 s for each trial. \subsubsection{Phase estimators} The Phase-Locking Value (PLV), and the Phase-Lag Index (PLI) assesses phase synchrony between signals in a specific frequency band. The PLV{} corresponds to the absolute value of the mean phase between $s_{i}$ and $s_{j}$, is defined as follows~\cite{lachaux_measuring_1999,tass_detection_1998, aydore_note_2013}: \begin{equation} PLV =|e^{i\Delta\phi(t)}| \end{equation} where $\Delta\phi(t)=arg(\frac{z_i(t).z_j^{*}(t)}{|z_i(t)|.|z_j(t)|})$. $\Delta\phi(t)$ represents the associated relative phase computed between signals and $z(t)=s(t)+i.h(s(t))$ the analytic signal obtained from the signal $s(t)$. The PLI{} assesses the asymmetry of the phase difference \cite{stam_phase_2007}. As a result, it is less sensitive to shared signals at zero phase lag. \begin{equation} PLI =|\text{sign} \sin\Delta\phi| \end{equation} Given its sensitivity to volume conduction and noise, we considered an additional phase-based metrics resulting from the PLI{}: the debiased estimator of squared weighted Phase Lag Index \cite{vinck_improved_2011} (wPLI2-d). The wPLI2-d{} is notably less sensitive to uncorrelated noise sources and its unbiased version enables a reduction of the sample-size bias. Functional connectivity estimations were made by using multitapers \cite{slepian_prolate_1978}, with time windows of length 1 s with an overlap of 0.5 s for each trial. \subsubsection{Amplitude coupling estimator} We computed the Amplitude Envelope Correlation (AEC) \cite{ hipp_large-scale_2012, brookes_measuring_2011,colclough_how_2016} which relies on the linear correlations of the envelopes of the band-pass filtered signals obtained from Hilbert transform. All the metrics considered in this paper are summarized in Table~\ref{tab:tab1}. They were estimated using MNE~\cite{gramfort_mne_2014} and PyRiemann\footnote{\url{https://pyriemann.readthedocs.io}} toolboxes. \begin{table}[] \caption{Functional connectivity metrics considered in the study} \label{tab:tab1} \center \begin{tabular}{lllll} FC metric & Abbreviation & Category & Ref. \\ \hline Instantaneous coherence & Instantaneous & Spectral coherence & \cite{pascual-marqui_instantaneous_2007} \\ Imaginary Coherence & ImCoh{} & Spectral coherence & \cite{nolte_identifying_2004} \\ Phase-Locking Value & PLV{} & Phase estimation & \cite{lachaux_measuring_1999} \\ Phase-Lagged Index & PLI{} & Phase estimation & \cite{stam_phase_2007} \\ debiased estimator of squared wPLI & wPLI2-d{} & Phase estimation & \cite{vinck_improved_2011} \\ Amplitude Envelope Coupling & AEC{} & Amplitude coupling & \cite{hipp_large-scale_2012, brookes_measuring_2011} \\ \hline \end{tabular} \end{table} \subsection{Proposed approach: FUnctional COnnectivity eNsemble mEthod (\fucone{})} \begin{figure*} \begin{center} \includegraphics[width=\textwidth]{figures/Fig1.pdf} \caption{\fucone{} approach (generic view). {\label{519840}} } \end{center} \end{figure*} Our approach consists of combining FC estimators and Riemannian Geometry with two levels of classification, as shown on Figure~\ref{519840}. For each type of estimator considered (\emph{i.e.}, covariance and functional connectivity metrics), we performed a first-level classification in the tangent space using an Elastic-Net classifier. This classifier aimed to find the weights $w$ that minimized the following objective function $\min_w || \vectorize{X}w - y ||^2_2 + \alpha \rho ||w||_1 + \alpha(1 - \rho)||w||^2_2$. The hyperparameters were set up through a preliminary study, with $\alpha = 1$ and $\rho = 0.15$, meaning that the penalty was a combination of $\ell_1$ and $\ell_2$ norms. The first-level classifiers were used as a stacked ensemble of classifiers, using an Elastic-Net as an ensemble classifier, with $\alpha = 1$ and $\rho = 0.15$. This ensemble classifier was trained through a stratified $k$-fold that contained five splits. \subsection{Dataset for preliminary study} To identify the most suited parameters, we worked with a publicly available dataset~\cite{cho_eeg_2017}. The authors performed a BCI experiment of left and right hands motor imagery with a 64-channel EEG montage. The sessions were composed of five to six runs each. For more details on the dataset, the reader can refer to the description provided by Cho et al \cite{cho_eeg_2017}. For a sake of efficiency and to get a subset of representative subjects, we preselected the five most and the five least responsive subjects. For that purpose, we based our selection on the FgMDM classification scores, which corresponds in our case to the state-of-the-art classification algorithm in motor imagery-based BCI \cite{barachant2010riemannian, barachant_classification_2013}. For a given FC estimator, a time window of [0s, 3s] was considered. To verify the generalization property of our approach, we conducted a replicability analysis on several datasets. The details are provided in section~\ref{sec:repli}. \subsection{Performance assessment} \subsubsection{Baseline pipelines} Our approach was compared to the state-of-the-art algorithms in BCI. For this purpose, we considered the following pipelines: \begin{itemize} \item "RegCSP+shLDA" refers to a CSP based on Ledoit-Wolf shrinkage of the covariance term, followed by a Linear Discriminant Analysis (LDA) classifier~\cite{lotte_regularizing_2011} \item "CSP+optSVM" corresponds to a CSP followed by a Support Vector Machine (SVM) with grid search to find optimal parameters~\cite{ang_filter_2008} \item "FgMDM": it refers to the geodesic filtering followed by a Minimum Distance to Mean classification~\cite{yger2016riemannian} \end{itemize} The classification scores for all pipelines, \fucone{} included, were evaluated with a balanced accuracy measure, either using 5-fold cross-validation for within-session evaluation or with \emph{leave-one-session-out} for cross-session evaluation. \subsubsection{Statistical analysis} Within a dataset, depending on whether the number of subjects exceeded 20, a one-tailed paired $t$-test or a Wilcoxon signed-rank test for each pair of pipelines was considered. To assess the replicability of our method, we tested it on several datasets. Accordingly to the approach proposed in \cite{jayaram_moabb_2018}, $p$-values were combined by applying the Stouffer's method \cite{stouffer_american_1949}. Then a Bonferroni correction was performed to prevent it from false positive. Effect size was computed via the standardized mean difference within datasets and combined with Stouffer's method. \subsubsection{Diversity} To determine the possible improvement brought by a pipeline relying on a given functional connectivity estimator $\fcidx$, to covariance-based pipelines $\text{Cov}$, we built a diversity index upon the work of~\cite{kuncheva2003measures}. Diversity corresponds here to the proportion of trials misclassified by the $\text{Cov}$ that have actually been correctly classified by $\fcidx$. Extending the definition given in~\cite{chevallier_extending_2020}, the diversity $\ensuremath{\Theta}$ is defined as follows: \begin{equation} \ensuremath{\Theta} = \Omega^{\text{Cov}}_{FN+FP} \cap \Omega^{\fcidx}_{TP+TN} \end{equation} with $\Omega^{\text{Cov}}_{FN+FP}$ the number of trials incorrectly classified with covariance-based pipeline, that is false positive $FP$ and false negative $FN$ trials. The number of trials correctly classified by $\fcidx$ pipeline $\Omega^{\fcidx}_{TP+TN}$, that is true positive $TP$ and true negative $TN$. We distinguished two kinds of diversity measurements: the first one is the \textit{potential improvement} $\frac{\ensuremath{\Theta}}{|\Omega|}$, with $|\Omega|$ is the total number of trials and the \textit{relative diversity} $\frac{\ensuremath{\Theta}}{\Omega^{\text{Cov}}_{FN+FP}}$. \section{Results} \subsection{Thorough evaluation of FC-based pipelines} In this section, we investigated the relative contributions of the key parameters for FC-based pipelines, with the objective of selecting the best parameters for designing the \fucone{} approach. Among the considered items were the FC estimators, the frequency bands of interest and the combination of first-level classifiers into our workflow. \subsubsection{Impact of FC estimators} The first step consisted of identifying the FC estimators that discriminated the best signals. We considered the estimators defined in section~\ref{FC}. We compared the accuracy obtained across the ten subjects (see Figure~{\ref{519843}}A). Here, we considered the 8-35~Hz frequency band. We observed that the three best FC estimators were the instantaneous coherence (0.74 $\pm$ 0.23), the phase-locking value (0.68 $\pm$ 0.20) and the imaginary part of coherence (0.63 $\pm$ 0.15). Indeed, they performed significantly better than AEC{} ($p <$ 0.017). Instantaneous{} and PLV{} performed significantly better ($p <$ 0.03) than PLI{}, and wPLI2-d{} (see Figure~{\ref{519843}}B). Then, we explored the results at the sub-group level. We considered the most and the least responsive subjects separately in order to identify potential FC estimators susceptible to favor the most and/or the least responsive subjects (see Figure~{\ref{519843}}B). As expected, Instantaneous{}, PLV{} and ImCoh{} showed the highest performance with the most responsive group, with a mean accuracy respectively of 0.94, 0.87 and 0.71 (see Figure~{\ref{519843}}C). wPLI2-d{} and ImCoh{} showed higher accuracy than the other estimators with the least responsive group, with an accuracy respectively of 0.58 and 0.56 (see Figure~{\ref{519843}}D). In order to take into account both the group tendency and the need to provide alternative methods to discriminate least responsive subjects' mental state, we reduced our pool of FC estimators to the following estimators: Instantaneous, PLV{}, ImCoh{} and wPLI2-d{}. \begin{figure*} \begin{center} \includegraphics[width=\textwidth]{figures/Fig2.pdf} \caption{Functional connectivity estimators - (A) Group-level analysis. Barplots of the accuracy obtained over the group of ten subjects. (B) Group-level analysis. Statistical comparisons of each couple of pipelines. The color represents the significance level of the difference of accuracy obtained with two given pipelines associated to two specific FC estimators. (C) Subgroup analysis. Barplots of the obtained accuracy over the group of most responsive subjects (N=5 subjects). (D) Subgroup analysis. Barplots of the obtained accuracy over the group of least responsive subjects ($N$=5 subjects). {\label{519843}} } \end{center} \end{figure*} \subsubsection{Frequency bands of interest} To further investigate the influence of the key parameters on the performance of our approach, we compared the accuracy over different frequency bands. The sensorimotor rhythms gather mu-rhythm (\emph{i.e.}, between 8 and 12~Hz), often accompanied with a beta component (\emph{i.e.} 12 to 30 Hz) and a low gamma component (between 30 and 40Hz)~\cite{kubler_chapter_2016}. Here, we broadened our study to the following frequency bands: delta $\delta$ [2, 4~Hz], theta $\theta$ [4, 8~Hz], alpha $\alpha$ [8, 12~Hz], beta $\beta$ [15, 30~Hz], (low) gamma $\gamma$ [30, 45~Hz] and the default band [8, 35~Hz]. We performed the classification for each preselected FC estimator and each frequency band of interest separately. We analyzed the performance obtained (see Figure~\ref{519846}). We did not observe a frequency band effect (one-way ANOVA, $p >$ 0.05), meaning that we did not observe that a specific frequency band outperformed. Nevertheless, it appeared that higher scores were obtained in the default band since we obtained an average accuracy of 0.66$\pm$0.17, whereas we obtained 0.57$\pm$0.17, 0.59$\pm$0.13, 0.59$\pm$0.13, and 0.62$\pm$0.17, respectively for the delta, the theta, the alpha, the beta, and the gamma bands. Furthermore, as previously mentioned, the default band is the closest to the sensorimotor rhythm. As a result, we chose to work with this frequency band. \begin{figure*} \begin{center} \includegraphics[width=\textwidth]{figures/Fig3.pdf} \caption{Frequency bands - Group-level analysis. For each pipeline, we plotted the distribution of the scores obtained over the subjects. Each color corresponds to a specific frequency band. {\label{519846}} } \end{center} \end{figure*} \subsubsection{Stacking classifiers for ensemble learning} Once the preselected FC estimators and the frequency band identified, the next step consisted of finding the best combination of single-level classifiers. For that purpose, we considered different combinations and compared them to the pipelines associated with the FC estimators taken separately (see Figure~{\ref{519851}A}). At the group level, the configuration that performed the best consisted of combining the covariance, the instantaneous coherence and the imaginary part of coherence estimations with an average score of 0.72$\pm$0.22. It was the only configuration that presented a higher performance than both FC estimators and covariance. The three other combinations, (Instantaneous + ImCoh), (Instantaneous + ImCoh + PLV), (Instantaneous + ImCoh + PLV + wPLI2-d), showed similar performance, always superior to the ones obtained with FC estimators taken alone, with respectively 0.71$\pm$0.20, 0.70$\pm$0.20 and 0.70$\pm$0.20. As a result, we chose to work with the configuration presented in Figure~\ref{519851}C that includes the estimation of the covariance, the estimation of the instantaneous coherence and the imaginary part of coherence. All of them were associated with an Elastic-Net classifier. The ensemble classifier was also an Elastic-Net. In the next sections, when we mention our pipeline \fucone{} we will refer to the configuration proposed in Figure~\ref{519851}B. We compared the performance of our \fucone{} pipeline with the state-of-the-art (see Figure \ref{519851}C). At the group level, we observed that our approach gave the highest score with respect to the FgMDM, the CSP+optSVM, and the RegCSP+shLDA approaches that showed respectively of 0.70$\pm$0.20, 0.68$\pm$0.22 and 0.68$\pm$0.20. Notably, our approach performed better both for the most and the least responsive subjects. \begin{figure*} \begin{center} \includegraphics[width=\textwidth]{figures/Fig4.pdf} \caption{Stacking classifiers for ensemble learning. (A) Performance comparison between different combinations of pipelines and each FC estimator taken separately. Each bar corresponds to a specific configuration. (B) \fucone{} approach. From EEG recordings, covariance, Instantaneous{} and ImCoh{} estimations are computed and classified with an Elastic-Net approach followed by an ensemble classifier relying on an Elastic-Net that provides the decision. (C) Comparison with the state-of-the-art. On the left, the bar plots represent the scores obtained from each pipeline at the group-level. The last two raincloud plots represent, for each pipeline, the distribution of the scores over the subgroups composed by respectively the most and the least responsive subjects. {\label{519851}}% } \end{center} \end{figure*} \subsection{\fucone{}, a replicable approach to improve MI classification} \label{sec:repli} In order to assess the robustness and the replicability of our approach, we tested it through a larger number of subjects, datasets and motor imagery tasks. We also considered two types of performance evaluation: within-session and cross-session. \subsubsection{Considered datasets} To perform this analysis, we only used open-access datasets in which the participants are healthy. The Table~\ref{tab:tab2} provides a description of the datasets we used. \begin{table}[] \caption{Datasets included in the replicability study} \label{tab:tab2} \begin{tabular}{cccccccc} ID & \#subjects & \#channels & Sampling rate & \#sessions & \#tasks & \#trials/class & Ref. \\ \hline \hline Cho2017 & 52 & 64 & 512~Hz & 1 & 2 & 100 & \cite{cho_eeg_2017} \\ \hline Weibo2014 & 10 & 60 & 200~Hz & 1 & 7 & 80 & \cite{yi_evaluation_2014} \\ \hline Schirrmeister2017 & 14 & 128 & 500~Hz & 1 & 4 & 120 & \cite{schirrmeister_deep_2017} \\ \hline Zhou2016 & 4 & 14 & 250~Hz & 3 & 3 & 160 & \cite{zhou_fully_2016} \\ \hline 001-2014 & 10 & 22 & 250~Hz & 2 & 4 & 144 & \cite{tangermann_review_2012} \\ \hline 001-2015 & 13 & 13 & 512~Hz & 1 & 2 & 200 & \cite{faller_autocalibration_2012} \\ \hline 002-2014 & 14 & 15 & 512~Hz & 5 & 2 & 80 & \cite{steyrl_random_2016} \\ \hline 004-2014 & 10 & 3 & 250~Hz & 1 & 2 & 360 & \cite{leeb_brain-computer_2007} \\ \hline \hline \end{tabular} \end{table} \subsubsection{Within-session evaluation} In this section, we compared our score with those obtained with the state-of-the-art pipelines (see Figure~\ref{fig:meta}A) by applying a within-session evaluation. We pushed the limits of our approach by considering datasets with an increased number of tasks performed by the subjects. In particular, it enabled us to verify that our approach was not specific to the classic "left vs right" hand motor imagery. \textit{2 classes - right hand versus feet (rf)} -- In this case, we considered five datasets. For four of them, \fucone{} showed the best results, both in terms of average accuracy (ranging from 0.82 to 0.91) and variability (ranging from $\pm$0.08 to $\pm$0.14). In Zhou2016, the pipeline Cov+EN{} showed the best results (0.913$\pm$0.07) while ours was in second position (0.905$\pm$0.08). \textit{2 classes - left hand versus right hand (lhrh)} -- Four datasets were considered here. \fucone{} presented the best results for three of them (001-2014, 004-2014, and Schirrmeister2017) with an average accuracy ranging from 0.74 to 0.84 and a standard deviation ranging from $\pm$0.13 to $\pm$0.16. In Zhou2016, our approach ranked second (0.873 $\pm$0.101) after the Cov+EN{} pipeline (0.874$\pm$0.106). \textit{3 classes} -- We took into account three datasets. For two of them (001-2014, Weibo2014), \fucone{} showed the best performance, with accuracy ranging from to 0.73 to 0.80 and standard deviations ranging from $\pm$0.13 to $\pm$0.14. Here again, in Zhou2016, the pipeline Cov+EN{} showed the best results (0.844$\pm$0.08) while ours was in second position (0.839$\pm$0.08). \textit{4 classes} -- Two datasets were considered here (Schirrmeister2017 and Weibo2014). In both cases, \fucone{} showed the best accuracies (ranging from 0.80 to 0.86) and variability (ranging from $\pm$0.09 to $\pm$0.10). \subsubsection{Cross-session evaluation} To investigate the possibility to predict the performance across sessions for a given subject, we led a study with datasets that invited the participants to come twice. The training set gather all but one session, that is used a test set to estimate the prediction score, as in~\cite{khazem_minimizing_2021}. We compared our score with those obtained with the state-of-the-art pipelines (see Figure~\ref{fig:meta}A) by applying a cross-session evaluation this time. Here, we only had access to datasets associated with two motor imagery tasks (see Table \ref{tab:tab2}). \textit{2 classes - lhrh} -- In this case, we tested the pipelines on three datasets. For two of them, \fucone{} showed the best performance (from 0.72 $\pm$0.13 to 0.78 $\pm$0.12). In Zhou2016, the pipeline Cov+EN{} showed the best results (0.794$\pm$0.14) while ours was in second position (0.791$\pm$0.14). \textit{2 classes - rh-f} -- In this case, three datasets were considered. For all of them, \fucone{} ranked second after the Cov+EN{} one, with accuracy ranging from 0.79 to 0.86 (respectively from 0.79 to 0.85 with our pipeline) and standard deviations ranging from $\pm$0.09 to $\pm$0.14 (respectively from $\pm$0.10 to $\pm$0.13 with our pipeline). From a more general perspective, given that the pipelines Cov+EN{} and \fucone{} were the two best approaches, significantly better than the other state-of-the-art pipelines, and for a sake of brevity, we focused our statistical comparison to these two pipelines (see Figure~\ref{fig:meta}C). We observed that \fucone{} was significantly better than Cov+EN{} in three cases: 2 classes "right hand vs feet" both in within-session ($p^{\text{meta}}=0.026$) and cross-session ($p^{\text{meta}}=0.023$), and 4 classes in within-session ($p^{\text{meta}}=0.002$). \fucone{} showed similar performance with Cov+EN{} in the case of 2 classes "right hand vs left hand" (both in within and cross-session) and in the 3-class configuration (within session). For an exhaustive description of the statistical comparisons made between the whole set of pipelines, the reader can refer to Figures \textit{S1-6}. \begin{figure*} \begin{center} \includegraphics[width=450pt]{figures/Fig5.pdf} \caption{{Replicability assessments and comparison with state-of-the-art pipelines. (A) Within-session evaluation. On the left top, analysis performed with 2-class (lhrh stands for left hand vs right hand) datasets; on the left bottom, a comparison made with 2-class (rhf stands for right hand vs feet) datasets; on the right top, an analysis performed with 3-class datasets; on the right bottom, an analysis with 4-class datasets. (B) Cross-session evaluation. On the left, an analysis performed with 2-class (lhrh stands for left hand vs right hand) datasets; on the right, an analysis performed with 2-class (rhf stands for right hand vs feet) datasets. (C) Meta-effect assessment. Here we compared the two best pipelines: Cov+EN{} and \fucone{}. {\label{fig:meta}}% }} \end{center} \end{figure*} \section{Discussion} \subsection{Parameter optimization} The proof-of-concept of \fucone{} have been tested during the IEEE WCCI Clinical BCI Competition~\cite{corsi_riemannian_2021}, achieving top results. Still, several open questions were left in the aftermath of the competition. The first one was the potential improvement of the approach and complete evaluation of the parameters. The second question was to investigate if the \fucone{} approach actually leads to an general improvement of the MI-based BCI performance or if its improvement is restricted only to the competition dataset. The last question dealt with the reasons behind this improved performance and the explanation of the higher scores. To answer the first question, we listed the key parameters to be carefully tuned: the FC estimators, the frequency band of interest, and the pipeline combination to be taken into account by the ensemble method. \textit{FC estimators} -- We preselected six complementary FC estimators (see Table \ref{tab:tab1}). By comparing the performance obtained at the first-level classification, we reduced our pool of estimators to the following metrics: the instantaneous coherence, the imaginary part of coherence, the phase-locking value and the debiased wPLI. Metrics derived from the coherence have previously proved to be of interest for MI-based BCI \cite{hamedi_electroencephalographic_2016, gonzalez-astudillo_network-based_2020} both in the classification \cite{mottaz_modulating_2018, cattai_phaseamplitude_2021} and in the study of mechanisms underlying the tasks performance \cite{corsi_functional_2020, corsi_bci_2021}. As refer to PLV, previous studies explored the possibility to use this estimator as alternative features with contradictory results. In, \cite{spiegler_phase_2004}, no particular changes were observed between mu rhythms in both hemispheres in phase coupling. In \cite{brunner_online_2006}, classification performance relying on power spectra features were better than those relying on PLV. In \cite{gysels_phase_2004}, PLV{} outperformed coherence and combining power with PLV{} features also gave the best performance. Finally, in \cite{yi_evaluation_2014}, the authors used PLV{} to identify patterns of simple and compound limb MI tasks. They notably elicited specific interactions between central and occipital areas within the $\theta$ band. A reduced number of studies investigated the use of connectivity features derived from the phase-lag index. Recently in \cite{feng_functional_2020}, the authors compared the performance obtained from PLI, wPLI2-d{} and PLV{} features. They observed that the FC features reached accuracy higher than 85\% and that PLI{} performed better than the filter-bank common spatial pattern. In our study, we proposed to take into account complementary FC metrics in our ensemble method to take advantage of their physical properties. \textit{Frequency band} -- The second key parameter we optimized is the frequency band of interest. Surprisingly, any of the tested frequency bands led to significantly improved performance. An alternative approach would consist in considering a fine-tuned subject-specific system, in which each frequency band would be individually defined accordingly to the individual alpha peak \cite{klimesch_eeg_1999} as previously tested \cite{pichiorri_brain-computer_2015, corsi_functional_2020}. Even though this approach is particularly interesting and meaningful, it makes the interpretation harder at the meta-analysis level, especially in this work. To ensure the interpretability of our results, we preferred to work with broadband filters. \textit{Ensemble} -- The last key parameter we tuned is the combination of pipelines to be taken into account by the ensemble method. The best configuration, corresponding to our \fucone{} approach, consisted of combining pipelines that respectively relied on instantaneous coherence, imaginary part of coherence, and covariance features. To our knowledge, there is no previous example of a combination of pipelines relying both on covariance matrices and connectivity estimations. Previous works investigated the possibility to combine FC with power spectra features, with contradictory outcomes~\cite{gysels_phase_2004, wang_phase_2006, krusienski_value_2012, cattai_phaseamplitude_2021}. Indeed, in~\cite{krusienski_value_2012}, pipelines relying on Fast Fourier Transform were not improved with PLV nor magnitude squared coherence, whereas in~\cite{wang_phase_2006}, the configuration combining large-scale synchrony and power features gave the best score. Here, to test the replicability of our results, we proposed to apply our \fucone{} approach a large number of datasets associated with MI tasks. \subsection{Interpretation of discriminating connectivity features} In the previous sections, we proved that our approach enabled a better discrimination between subjects' mental state, over a large number of datasets and configuration. Nevertheless, a remaining aspect to be taken into account is the variability, both in terms of BCI setup and at the individual level. Indeed, while having access to signals recorded by a large number of electrodes provides valuable information on brain connectivity, it engenders an increase of the experiment duration and of the subject's tiredness, as well as a decrease in Riemannian's performance~\cite{yamamoto_subspace_2021}. Defining a minimum number of electrodes to be used by our approach is necessary. We proposed an additional step in the features selection consisting in a dimensional reduction (DR) approach. For a given training set, we performed a paired t-test to elicit the most discriminant interactions ($p < 0.05$ between the considered conditions). To ensure that the extracted features still consisted in symmetric positive definite matrices, we extracted the N channels that were the most frequently involved in discriminant interactions, meaning that they could be considered as hubs in terms of discriminant power. Finally, we took into account only the matrices (NxN) formed by these hubs. We tested our approach on a dataset for which an EEG montage of 128 electrodes was used \cite{schirrmeister_deep_2017} (for more details on the dataset, the reader can refer to Table~\ref{tab:tab2}). We tested different sets of channels ranging from 16 to 96 electrodes. First, we analyzed the performance at the group-level (see Figure \textit{S9}). Both for ImCoh{} and Instantaneous{} the performance reached a plateau at $n_{\text{dr}}=32$, with an accuracy respectively of 0.675$\pm$0.123 and 0.754$\pm$0.14. These results indicated that only one fourth of the EEG montage set was sufficient to reach the maximum of the accuracy with \fucone{}. These methods gave access to the electrodes chosen over the subjects. We plotted the associated topographical maps that represented the occurrences over the subjects (see Figure \textit{S8}). We observed that at $n_{\text{dr}}=16$ the most frequently chosen channels were located above the bilateral sensorimotor area, which is in line with the areas involved during left- vs right-hand motor imagery. Then, as the number $n_{\text{dr}}$ increased, we observed a more diffused area selected by our approach, around the core one that consisted in the regions associated with the configuration $n_{\text{dr=16}}$. These more diffused regions were located above the parietal and occipital areas, both related to associative areas, known to play a crucial role in motor sequence learning as well as in abstract task learning~\cite{mcdougle_taking_2016,hetu_neural_2013,hardwick_neural_2018,dayan_neuroplasticity_2011} and in MI tasks performance~\cite{guillot_neurophysiological_2010}. These observations are in line with previous works conducted with functional connectivity to elicit markers of motor imagery-based BCI performance~\cite{corsi_functional_2020}. At the individual level, we observed the "plateau effect" for ten to fourteen subjects (see Figure~\textit{S10}). For the remaining four subjects, two cases were observed: an increase of the performance with a larger number of electrodes considered (subjects 3, 4 and 8) or a decrease of the performance above $n_{\text{dr}}=32$ (subject 1). This last point means that considering the DR approach can be valuable to individually adapt the number of considered electrodes. \subsection{Study on post-stroke patient} Another crucial element is the inter- and intra-subject variability. This is particularly true for clinical applications where attention must be paid to customize the BCI system to the patients' ability to perform a motor imagery task and their neurophysiological signature~\cite{scherer_individually_2015} (\emph{e.g.}, brain lesions caused by the stroke can engender a modification of the spatial and frequency locations of the features). Our DR approach can provide a valuable tool to take into account the patient's specificity. We tested our pipeline with one of the patients who were the least responsive to the BCI training in~\cite{scherer_individually_2015}: patient A (42 years old) who suffered from a locked-in syndrome due to brainstem stroke. Among the different motor imagery tasks proposed, the poorer results were obtained when he performed the right hand vs feet motor imagery. We applied our approach on the EEG recordings and compared our results to the state-of-the-art pipelines (see Figure \textit{S11}). We slightly modified the pipeline described in the previous paragraph so that the algorithm chose the most suited number of electrodes (ranging from 10\% to 30\% of the available set of electrodes) according to the performance obtained on the training set. Interestingly, our approach based on the combination of \fucone{} with DR showed the best results (0.54$\pm$0.09) and performed better than \fucone{} taken alone (0.45$\pm$0.17). This last point highlights the need to take into account the patient's specificity in the classification pipeline. More importantly, as previously explained, DR gives access to the electrodes that are selected for the classification (see Figure \textit{S11}). In our example, we observed that among the 30 EEG electrodes, the most suited electrodes for ImCoh{} were CP3 and P4 and that with Instantaneous, we selected C4 and O1. The location of the preselected channels, mostly above the sensorimotor area and the associative areas, reinforces the idea that our approach enables a relevant selection of channels, in line with previous works based on functional connectivity~\cite{yi_evaluation_2014, corsi_functional_2020}. Nevertheless, we are perfectly aware that applying the DR approach after \fucone{} consists in an additional computation step. Therefore, we think that it should be considered in specific cases: to identify the most suited electrodes to be used and for patients who are less responsive to motor imagery-based BCI. \subsection{Characterizing potential contributions of functional connectivity} One important improvement of \fucone{} is to enhance the results for the most difficult cases, that is for the least responsive subjects. Those subjects obtain very low classification accuracy with all state-of-the-art methods and are the focus of many research works~\cite{jeunet_predicting_2015,corsi_bci_2021}. Our approach systematically increase the average accuracy for these subjects, for eight datasets and different MI classes, as shown on Figure \textit{S11}. The reason behind this improvement are mostly imputable to the robustness brought by the combination of multiple feature spaces (covariance and FC) to yield the final prediction. To further investigate the FC estimator contribution to covariance-based pipelines, we tested the diversity and reported the results on BNCI001-2015 in Supplementary material (see Figures \textit{S12-13}). We also tested other datasets and the results were significantly the same across datasets. The instantaneous coherence had a very low relative diversity and potential improvement when compared to ImCoh, PLV, PLI, wPLI2-d{} and AEC{} estimators. The ImCoh{} estimator showed the highest relative diversity and potential improvement, but PLV, PLI, wPLI2-d{} and AEC{} were very close in absolute value. It is interesting to see that the instantaneous coherence displayed the lowest diversity score whereas it was the FC estimator achieving the highest accuracy, after Cov+EN{} and that other FC estimators showed high diversity and low classification accuracy. The diversity score reflects the potential improvement that is possible to achieve by combining several estimators. As \fucone{} relies on an ensemble classifier that evaluates the confidence of each pipeline, FC-based pipelines with low accuracy have a low confidence even if their diversity scores are high. This point out that there is a potential room to improve the combination of FC estimators and covariance measure. A feature space that builds upon the careful aggregation of those estimators could have a real impact on classification performance. The most difficult part of this challenge is either to find the correct geometry to define such feature space or to be able to assess the reliability of the FC pipelines. \subsection{Caveats and limitations} Even though our approach enabled an improvement of the BCI accuracy over a large number of datasets, this study presents several caveats that need to be acknowledged. A first limitation is related with the requirements made for estimating covariance or FC features. The estimators need to provide symmetric and positive definite matrices in order to apply the Riemannian framework. We ensured this critical point by projecting onto the manifold the matrices that were ill-conditionned, \emph{i.e.}, with eigenvalues closed to zero~\cite{chevallier_riemannian_2018}. This is a common problem for covariance estimators when a Common Average Reference (CAR) is applied or when using a combination of working electrodes to estimate the signal of a disconnected electrode. We did not use any electrode re-referencing or missing signal completion in this work, and this was sufficient to ensure that our approach was working properly. For low quality EEG acquisition with missing data, it is still possible to rely on robust estimation to obtain accurate results~\cite{yger_geodesically-convex_2020}. Secondly, we still observed an inter-subject variability in terms of classification performance. Several elements can explain it. In an effort to test our approach in conditions closest to real-life scenarios, we applied the \fucone{} method on datasets that presented a strong diversity in terms of MI tasks and of number of channels considered without preprocessing. The inter-subject variability can reflect a variety in the possible ways to detect neurophysiological properties underlying the MI performance. We led our analysis by considering both covariance and FC features. However, further analysis, possibly in the source space, could be of interest to provide a more accurate description of the neural mechanisms underlying the control of a BCI~\cite{corsi_functional_2020}. This inter-subject variability is strongly linked to the BCI inefficiency phenomenon that is a multifaceted problem that cannot be only addressed by improving our way to discriminate the subjects' mental state. Indeed, machine-centered and user-centered approaches, relying on the subjects' similarities~\cite{khazem_minimizing_2021} or on the subjects' cognitive profile~\cite{jeunet_predicting_2015} for example, should be considered together to improve BCI systems~\cite{thompson_critiquing_2018}. Lastly, the \fucone{} approach has only been tested offline. To propose a reliable alternative to current classification pipelines, an online implementation is required. Before considering testing it online, we wanted first to ensure that the \fucone{} method was replicable. Nevertheless, we led a feasibility study and we observed that our approach may engender a delay caused by the processing time. Such a delay strongly depends on the time window of interest used to extract the FC features. In this work, we chose to work with epochs of 1s. This led to a processing time in the order of 100 ms, that is compatible for an online implementation. By working with overlapping epochs, we can reduce the time delay in order to refresh the feedback more often and ensure the subject's sense of agency following a similar approach to~\cite{kalunga_online_2016}. \section{Conclusion} In this work, we introduced our approach, named \fucone{}, that consists of a Riemannian take on functional connectivity estimators, by combining the decision in each feature space with an ensemble classifier. We thoroughly optimized the key parameters on a reference dataset. We evaluated \fucone{} on eight MI datasets, considering different imaginary movement combinations and evaluating results when trained on the same session (within-session evaluation) or trained on different sessions (cross-session evaluation). Consistent with our hypothesis, our approach was significantly better than state-of-the-art methods, both for CSP-based and for covariance-based Riemannian classifiers. An extension of our method, relying on a dimensional reduction, elicited a subset of electrodes, located above sensorimotor and associative areas, that were sufficient to achieve high accuracy. Such a technique proved to be relevant for clinical applications. A characterization of the contribution of functional connectivity estimators to covariance-based pipeline led us to point out that there is room for a potential improvement of the combination of decision. Taken together, our results offer new insights into the need to consider functional connectivity based methods to improve the BCI performance. \section{Acknowledgments} FDVF and MCC acknowledge support from the European Research Council (ERC) under the European Union’s Horizon 2020 research and innovation programme (grant agreement No. 864729). FY acknowledges the support of the ANR as part of the ``Investissements d'avenir'' program, reference ANR-19-P3IA-0001 (PRAIRIE 3IA Institute). The funders had no role in study design, data collection and analysis, decision to publish, or preparation of the manuscript. \section{Data and code availability} The code used to perform the analysis and the data that support the findings of this study are publicly available in this Github repository: \url{https://github.com/mccorsi/FUCONE.git}. \section{Authors contributions} MCC, SC, and FY initiated research; MCC, SC, FY and FDVF designed research; MCC, SC, and FY performed research; MCC, SC, and FY contributed analytic tools; MCC and SC analyzed data; and MCC, SC, FY and FDVF wrote the paper. All authors revised and approved the manuscript. \section{Additional Information} Supplementary Information accompanies this paper. \bibliographystyle{nature_mag} \section*{Supplementary Figures} \begin{figure}[ht!] \begin{center} \includegraphics[width=\textwidth]{figures/Supplem/SI_1.pdf} \caption{Meta-analysis performed over four datasets, 2 classes (left- vs. right-hand motor imagery) with a within-session evaluation.} \label{Figure1} \end{center} \end{figure} \newpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_2.pdf} \caption{Meta-analysis performed over five datasets, 2 classes (feet vs. right-hand motor imagery) with a within-session evaluation.} \label{Figure2} \end{figure} \newpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_3.pdf} \caption{Meta-analysis performed over three datasets, 3 classes with a within-session evaluation.} \label{Figure3} \end{figure} \newpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_4.pdf} \caption{Meta-analysis performed over two datasets, 4 classes with a within-session evaluation.} \label{Figure4} \end{figure} \newpage \begin{figure}[ht!] \begin{center} \includegraphics[width=\textwidth]{figures/Supplem/SI_5.pdf} \caption{Meta-analysis performed over three datasets, 2 classes (left- vs. right-hand motor imagery) with a cross-session evaluation.} \label{Figure5} \end{center} \end{figure} \newpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_6.pdf} \caption{Meta-analysis performed over three datasets, 2 classes (feet vs right-hand motor imagery) with a cross-session evaluation.} \label{Figure6} \end{figure} \newpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_7.pdf} \caption{Comparison of FUCONE with Cov+EN in the least responsive subjects (\emph{i.e.}, 30\% subjects who presented the weakest performance, both at the single dataset level and at a global over for a given configuration (\emph{i.e.}, number of tasks). } \label{Figure7} \end{figure} \newpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_8.pdf} \caption{Evolution of the features selection of an increasing number of channels considered. Each topography represents the occurrence associated to each sensor over the fourteen subjects included in the dataset from Schirrmeister et al. }\label{Figure8} \end{figure} \newpage \clearpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_9.pdf} \caption{Evolution of the performance with an increasing number of channels considered. It corresponds to the group-level analysis performed over the fourteen subjects included in the dataset from Schirrmeister et al. }\label{Figure9} \end{figure} \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_10.pdf} \caption{Evolution of the performance with an increasing number of channels considered. It corresponds to the individual analysis performed over the fourteen subjects included in the dataset from Schirrmeister et al. }\label{Figure10} \end{figure} \newpage \clearpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_11.pdf} \caption{Clinical application of our approach. (A) Comparison of the performance obtained from our FUCONE approaches and the state-of-the-art pipelines. We used the dataset provided by Scherer et al. More particularly, we chose the patient who was the least responsive in right hand vs feet motor imagery tasks. (B) Electrodes selected by our DR approach. }\label{Figure11} \end{figure} \newpage \clearpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_12.pdf} \caption{Relative diversity plots, displayed for instantaneous coherence, ImCoh, PLV, PLI, wPLI debiased and AEC estimators compared to covariance. The results are obtained on the dataset BNCI001-2015. }\label{Figure12} \end{figure} \newpage \clearpage \begin{figure} \centering \includegraphics[width=\textwidth]{figures/Supplem/SI_13.pdf} \caption{Potential improvement plots displayed for the same estimators compared to covariance. The results are obtained on the dataset BNCI001-2015. }\label{Figure13} \end{figure} \newpage \clearpage \end{document}
{'timestamp': '2021-11-08T02:03:19', 'yymm': '2111', 'arxiv_id': '2111.03122', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03122'}
arxiv
\section{INTRODUCTION} Air combat may occur in two primary forms: Within Visual Range (WVR) and Beyond Visual Range (BVR)~\cite{kurniawan2019empirical}, with the latter being recently more developed in the operational context, due to more extensive availability of more advanced weapons and sensors~\cite{higby2005promise}. Notice that, even though modern air combat may still end WVR, through a series of complex decisions and maneuvers, it usually begins BVR, which frequently is the most critical phase of the combat since it may provide advantages and drawbacks for succeeding phases~\cite{yuan2016design}. There is no clear definition of the distance to differentiate these two forms of air combat since this may be subject to the conditions in which the air combat happens. BVR conditions force the pilots to rely more on a series of systems to compose their situational awareness, allowing them to make tactical decisions during the combat, such as whether to fire a missile or not. Especially in BVR combat, the missile launches and the circumstances around these events are critical~\cite{aronsson2019supporting}, since these weapons are the main form to engage the opponent. Since BVR combat is rarely observable in practice, with low availability of historical data, much of the assessment of its possibilities must be done through simulation~\cite{stillion2015trends}. It is also true due to the high costs of flying, air space regulations, and limited availability of platforms representative of those used by opposing forces~\cite{kallstrom2020agent}. This work contributes by developing a decision support tool for pilots in BVR combat situations based on simulated data, with a particular focus on solving the problem of deciding when to engage a specific enemy aircraft, which is commonly based solely on pilot experience. There are several previous approaches that relate to this decision, mainly providing different forms of modeling pilot behavior. Many of them use game theory to model air combat~\cite{karelahti2006game,virtanen2006modeling,mukai2003sequential,ha2018stochastic}. Other approaches found in the literature are as follows: Bayesian Networks~\cite{poropudas2007analyzing,fu2021air,rao2011situation,du2010study}, fuzzy logic~\cite{akabari2005fuzzy,prabhu2014decision}, agent-based modeling~\cite{heinze1998thinking}, influence diagrams~\cite{lin2007sequential}, reinforcement learning~\cite{hu2021application,toubman2016rapid,piao2020beyond,weilin2018decision}, artificial neural networks~\cite{dantas2018,yao2021study}, evolutionary algorithms~\cite{li2020multi,yang2020evasive}, minimax method~\cite{kang2019beyond}, and behavior trees~\cite{yao2015adaptive}. \begin{comment} combat~\cite{karelahti2006game,virtanen2006modeling,mukai2003sequential,davidovitz1989two,ma2019cooperative,ha2018stochastic}. Other approaches found in the literature are as follows: Bayesian Networks~\cite{poropudas2007analyzing,fu2021air,rao2011situation,du2010study}, fuzzy logic~\cite{akabari2005fuzzy,tran2002adaptation,prabhu2014decision}, agent-based modeling~\cite{heinze1998thinking}, influence diagrams~\cite{lin2007sequential}, reinforcement learning~\cite{hu2021application,toubman2016rapid,piao2020beyond,weilin2018decision}, artificial neural networks~\cite{dantas2018,yao2021study}, evolutionary algorithms~\cite{li2020multi,yang2020evasive}, minimax method~\cite{kang2019beyond}, and behavior trees~\cite{yao2015adaptive}. \end{comment} Among all of these approaches, Ha \emph{et al.} (2018)~\cite{ha2018stochastic} is the one that more directly focuses on estimating the firing moment, which is done through a probabilistic function of the target's evasive maneuverability, the missile's speed on the final approach, and the accuracy of the target's information to guide the missile. However, as with many of the other cited methods, the methodology proposed in~\cite{ha2018stochastic} has not been tested in simulations with a higher degree of fidelity concerning an actual BVR air combat. As an alternative, our work uses supervised machine learning models based on decision trees, using the XGBoost library~\cite{chen2015xgboost}, to provide pilots with parameters that improve their situational awareness in air combat from data collected from simulations of operational scenarios, allowing them to better decide when to engage a target. Compared to most of the approaches, this study was conducted through higher fidelity simulations, providing systems and subsystems that resemble their natural counterparts through our simulation environment, such as 6 degrees of freedom (6DOF) multi-role combat aircraft, electronic warfare (EW) devices, datalink communications, and active radar-guided missiles. This study is, therefore, developed around four main subjects: i) determination of BVR air combat scenarios that will be analyzed, ii) carrying out simulations based on the chosen scenarios in the agents' configurations are varied, iii) collecting and analyzing the data generated in the simulations, and iv) using machine learning techniques on this data to improve the pilot's situational awareness by providing information about the analyzed air combat, fulfilling the role of a decision support system. The remainder of this paper is organized as follows. In section 2, the main characteristics of the aircraft in the BVR air combat are described. We also explain the Defensive Counter Air (DCA) index, the operational metric used to perform the engagement analysis. Besides, the sampling process of the simulation inputs is discussed. In section 3, we show the methodology used to create the solution approach. Section 4 investigates the results and analysis concerning the exploratory data analysis and model results. Finally, in section 5, we present the conclusions and future works. \section{PROPOSAL DESCRIPTION} This section shows the Fighter Agent model, describing the simulation agent's reasoning that we propose. Next, the DCA index, the operational metric that we created to evaluate the air combat engagements, is presented. Finally, we discuss our process of sampling simulation input parameters. \subsection{Fighter Agent} The Institute for Advanced Studies from the Brazilian Air Force develops the Aerospace Simulation Environment (\emph{Ambiente de Simulação Aeroespacial - ASA} in Portuguese) to provide a computational solution that enables the simulation of operational scenarios, allowing users to establish scenarios, parameters, and command decisions to support the development of tactics, techniques, and procedures. Since there is so much variability in the nature of military scenarios, it may be hard to define what the scenarios of interest are. Thus, the development of ASA is not limited to predefined layouts; instead, it poses itself as a flexible solution that may be tailored to the user's needs. Its modularity contributes to this flexibility since one can configure components (models) in diverse ways and combine them freely, which enables the creation of the most varied scenarios~\cite{costa2019master}. ASA is a custom-made, object-oriented (C++), and high-fidelity environment that generates the simulations and the data to analyze the problem. The simulation concept addressed in this context is one in which the scenario elements are represented as agents capable of making decisions based on artificial intelligence models or arbitrary rules previously stipulated. Simulations of this nature, termed constructive, can be used in the decision-making process, for example, to predict possible outcomes of engagements between opposing forces and assist in the definition of lines of action. The agent's actions are managed by a set of rules that describe a pilot's main tactical behaviors during a BVR combat. This set of rules is modeled as a Finite State Machine (FSM), or finite automaton, which is a mathematical computer model that, at any time, can be in only one state of a limited set of states~\cite{mamessier2014pilot}. Each state is one of the possible tactics that can be taken during a BVR combat. The following behaviors will be analyzed to better understand the presented problem: Combat Air Patrol (CAP), Commit, Abort, and Break. Fig.~\ref{fig1} shows the FSM that manages all the agent's tactics. \begin{figure} \centering \includegraphics[width=0.45\textwidth]{State.png} \caption{FSM of agent tactics.} \label{fig1} \end{figure} The CAP tactic consists of performing a flight pattern, describing an orbit, that can be any tactical maneuver, such as a circle or an oval, around a specific position called CAP point, with a defined heading and direction (clockwise or counterclockwise). The Commit tactic consists of the agent engaging a target detected by its radar or shared by data link by its allies. In the Abort tactic, the agent performs a defensive maneuver to move away from his priority threat, which is also the priority target in many situations. Finally, when the agent's sensors detect a missile threat fired in its direction, it performs the Break tactic. This tactic consists of a sudden defensive maneuver, describing a curve and a dive with great acceleration. At the engagement moment, the FSM assumes the Commit behavior and will keep performing offensive maneuvers until the time it is desirable within combat. The offense and vulnerability indices are essential variables that guide the change from one state to another within the FSM. Then, when the agent needs to do a defensive movement, it assumes Break or Abort. Therefore, the engagement time in a simulation is defined as the time between the first Commit carried by the agent and its first Break or Abort. We created an operational index that determines the quality of the actions taken by the agent in a BVR scenario, which was calculated during the engagement period and can be extended to any moment in the simulation. This metric is referred to as the DCA Index, which will be detailed in the following subsection. \subsection{DCA Index} We defined the index as a probability of success, ranging from 0\% to 100\%, for BVR combat on DCA missions whose objective is to establish a CAP. These missions have the goal of defending a point of interest, which is done by ensuring that the opposing aircraft are kept far away from it. In addition, it aims to do that while launching the least number of missiles possible, which is interesting both from economic and operational standpoints. Furthermore, from the doctrine perspective, one may consider it good practice for the defending aircraft to stay close to its CAP point since it is easier to employ tactics to defend the point of interest. From these considerations with respect to the DCA mission context, we defined three basic principles (depicted in Fig.~\ref{fig2}) for the elaboration of the DCA index: \begin{enumerate} \item Minimize the number of missile launched in the mission: ($m_{total}-m_{avail}$). \item Minimize the reference distance from its CAP point: $D(r,CAP)$. \item Maximize the distance of each enemy ($e_n$) to the CAP point: $D(e_{n},CAP)$. \end{enumerate} \begin{figure} \centering \includegraphics[width=0.4\textwidth]{Index.png} \caption{Representation of the factors that form the DCA index.} \label{fig2} \end{figure} Firstly, at the beginning of the engagement, each aircraft has a fixed number of missiles ($n_{total}$), which at that moment is also the number of missiles available ($n_{avail}$). When the aircraft launches a missile, $n_{avail}$ decreases to keep track of the currently available missiles. The ratio between $n_{avail}$ and $n_{total}$ is one of the factors of the DCA index, so that, when maximizing this ratio, $n_{total}-n_{avail}$ is minimized Secondly, regarding minimizing the distance between the reference aircraft and the CAP point, i.e., $D(r,CAP)$, we considered that the decay of this effect is not linear since, as the distance increases, its influence becomes much less relevant to fulfilling the mission goals. Therefore, we chose a sigmoid function to generate such decay to encompass this non-linearity. We defined the sigmoid limits, considering operational experience with respect to the maximum range of the available missile, as 8,000 meters ($x_{99\%, r}$) for the 99\% output value, which corresponds to $y_{99\%, r}\approx4,5951$, and as 12,000 ($x_{1\%, r}$) meters for the 1\% output value, which stands for $y_{1\%, r}\approx-4,5951$. These limits must be used in a linear interpolation~\eqref{eq1} to convert the current distance value ($D_r$) to be input ($d_{r}$) in the sigmoid equation~\eqref{eq2}. \begin{equation}\label{eq1} d_i = \frac{(y_{99\%, i}-y_{1\%, i})}{(x_{99\%, i}-x_{1\%, i})} \cdot [D(i,CAP)-x_{1\%, i}] + y_{1\%, i} \end{equation} \begin{conditions} i & $r$ (reference) or $e_n$ (enemy) \\ D_i & measured distance from the CAP point \\ d_i & interpolated distance for sigmoid input \\ \end{conditions} Lastly, when considering the opposing aircraft distances ($D(e_{n},CAP)$), for all $N$ enemies, we used a similar sigmoid function, but with opposite characteristics since the idea was to increase the enemies' influence when they were closer to the CAP point. Therefore, the sigmoid limits for this factor were instead 12,000 ($x_{99\%, e}$) meters for the 99\% output value, which corresponds to $y_{99\%, e}\approx4,5951$, and 8,000 ($x_{99\%, e}$) meters for the 1\% output value, which stands for $y_{1\%, e}\approx-4,5951$. Applying the enemy sigmoid limits in the interpolation equation \eqref{eq1}, we are able to convert the measured distance value $D(e_n,CAP)$ to be input ($d_{e_n}$) in \eqref{eq2} for each of the enemy aircraft. With the composition of the previously calculated factors, it is possible to obtain the DCA index's final calculation. The index factors have coefficients to allow prioritization of the three principles presented, as seen in~\eqref{eq2}. We defined the weights ($w_1=0.2$, $w_2=0.4$, and $w_3=0.4$) for each factor of the DCA index ($I_{DCA}$) based on the operational knowledge from subject matter experts. \begin{equation}\label{eq2} \begin{aligned} I_{DCA} = &\; w_1 \cdot \frac{m_{avail}}{m_{total}} + w_2 \cdot \frac{1}{1+\exp(-d_r)} \\ & + w_3 \cdot \frac{1}{N} \sum_{n=1}^N \frac{1}{1+\exp(-d_{e_n})} \end{aligned} \end{equation} \subsection{Sampling of Simulation Input Parameters} Latin Hypercube Sampling (LHS) is a method that can be used to produce, in a distributed way, the set of input values to be used in the simulations according to the desired intervals~\cite{wang2019formal}. This statistical method generates a random sample of parameter values from distribution in multiple dimensions. LHS consists of subdividing the sample universe into several disjoint subsets and extracting a representative element for each subsets, chosen at random. The generated and stored simulations used in the supervised learning model were carried out in packages (batches). Thus, for the same type of scenario, it was possible to vary some parameters at the beginning of the simulation, which may lead to different outcomes. The simulations parameters changed during the sampling were: (a) latitude and longitude, determining the initial positions of the agents around the CAP points (adopting fixed CAP positions), (b) the flight level blocks to determine their altitudes, (c) the commit distance (the minimum distance that an agent is from a possible target that allows it to leave the CAP tactic and commit), (d) the thresholds of the offense and vulnerability indices before and after firing a missile (represent the level of risk acceptance that the agent is willing to withstand), (e) the shot philosophy (orientation defined during mission planning, before the flight, referring to the moment when, within the Weapon Engagement Zone (WEZ), which is an estimation of the missile maximum launch range~\cite{dantasbracis2021}, the agent must launch a missile), (f) the shot distance (the minimum distance that an agent is from a possible target that allows, during an engagement, fire a missile, i.e., the WEZ), and (g) the presence or absence on the aircraft of a Radar Warning Receiver (RWR), an EW system that detects electromagnetic emissions from opposing radar systems. Using the LHS algorithm, 3,729 constructive simulations were generated in ASA, and a total of 10,316 engagements were observed. Each simulation corresponds to a 12-minute scenario executed three times faster than real-time, lasting approximately ten days in total. The scenario consists of two opposing formations with two aircraft each, which are initially approaching, disengaged, and outside the radar range of each other. Their main goal is to establish a CAP at the same CAP point, invariably leading to a confrontation. When they enter the limits of the opponents' radars, the engagement phase begins. In the modeling proposed in this work, each aircraft is equipped with four of the same type of medium-range missile, i.e., up to 40 nautical miles in range. \section{METHODOLOGY} After sampling the variables, respecting the intervals chosen for each one, we executed the simulations through ASA. The engagement events between the four agents are extracted with the data generated from these simulations. The average DCA index is calculated for all engagements extracted from the interval under analysis, generating the output variable that we intend to predict later for new samples. With the input data of the simulations and the output variable already defined, we build a supervised machine learning model based on eXtreme Gradient Boosting (XGBoost), predicting the average value of the agents' DCA index in future engagements. XGBoost represents a class of algorithms based on Decision Trees with Gradient Boosting~\cite{chen2016xgboost}. Its performance is analyzed with the test dataset after the model's training process is completed. This section discusses the input and output model variables, preprocessing procedures, hyperparameters tunning, evaluation metrics, and cross-validation processes. \begin{comment} \subsection{XGBoost} XGBoost (eXtreme Gradient Boosting) is one of the most used algorithms by data scientists, presenting superior results, mainly in forecasting problems involving structured/tabular data~\cite{chen2016xgboost}. It represents a class of algorithms based on Decision Trees with Gradient Boosting, which means that the method uses the Gradient Descent algorithm to minimize loss while new models are being added. Due to its characteristics, the process can deal efficiently (and robustly) with a wide variety of data types. Furthermore, XGBoost is very flexible since it has many hyperparameters that can be improved, allowing it to be properly adjusted to different scenarios and problems. In fact, since its inception, it was considered to be the state of the art supervised machine learning algorithm for dealing with structured data~\cite{chen2015xgboost}. We decided to use XGBoost to analyze the described data in the proposed problem because of its speed, performance, and parallelization provision. \end{comment} \subsection{Model Input and Target Variables} The main variables that coordinate the simulation of a BVR air combat were analyzed, and seventeen input variables were determined to be the most important to define the progress of the simulations based on the described scenarios. In addition, there are categorical and numerical variables with different ranges of coverage, and the definition of these sampling intervals was made based on the operational knowledge of BVR pilots and combat specialists. Next, in Table~\ref{tab2}, the description of each of the input variables of the simulations is carried out, presenting its unit when the variable is not dimensionless. \begin{comment} \begin{table*} \caption{Variables at the beginning of the engagement.}\label{tab2} \begin{tabularx}{\textwidth}{|c|c|X|} \hline \textbf{Parameter} & \textbf{Units} & \textbf{Description} \\ \hline distance & Meters & Distance between the reference and the target \\ \hline aspect & Degrees & Angle between the longitudinal axis of the target (projected rearward) and the line-of-sight to the reference \\ \hline delta\_heading & Degrees & Angle between the longitudinal axis of both aircraft \\ \hline delta\_altitude & Meters & Difference of altitude between the reference and the target \\ \hline delta\_velocity & Knots & Difference of absolute velocity between the reference and the target \\ \hline wez\_max\_own2trk & Meters & Maximum range of the reference's weapon (non-maneuverable target) \\ \hline wez\_nez\_own2trk & Meters & No-escape zone range of the reference's weapon (target performing high performance maneuver) \\ \hline wez\_max\_trk2own & Meters & Estimated maximum range of the target's weapon (non-maneuverable reference) \\ \hline wez\_nez\_trk2own & Meters & No-escape zone range of the target's weapon (reference performing high performance maneuver) \\ \hline vul\_thr\_bef\_shot & - & Level of risk acceptance before shooting \\ \hline vul\_thr\_aft\_shot & - & Level of risk acceptance after shooting \\ \hline shot\_point & - & Missile firing point between the maximum range and the no-escape zone range of the reference \\ \hline rwr\_aircraft\_warning & - & Boolean indicating whether the aircraft is equipped with an active RWR \\ \hline hp\_tgt\_ofensivity & - & High priority target offense index of the reference \\ \hline hp\_thr\_vulnerability & - & High priority threat vulnerability index of the aircraft that is threatening the reference \\ \hline own\_shot\_phi & - & Reference shot philosophy \\ \hline enemy\_shot\_phi & - & Estimated enemy's shot philosophy \\ \hline \end{tabularx} \end{table*} \end{comment} \begin{table} \caption{Variables at the beginning of the engagement.}\label{tab2} \begin{tabularx}{0.4875\textwidth}{| c| X|} \hline \textbf{Parameter} & \textbf{Description} \\ \hline distance [m] & Distance between the reference and the target \\ \hline aspect [deg] & Angle between the longitudinal axis of the target (projected rearward) and the line-of-sight to the reference \\ \hline delta\_head [deg] & Angle between the longitudinal axis of both aircraft \\ \hline delta\_alt [m] & Difference of altitude between the reference and the target \\ \hline delta\_vel [kn] & Difference of absolute velocity between the reference and the target \\ \hline wez\_max\_o2t [m] & Maximum range of the reference's weapon (non-maneuverable target) \\ \hline wez\_nez\_o2t [m] & No-escape zone range of the reference's weapon (target performing high performance maneuver) \\ \hline wez\_max\_t2o [m] & Estimated maximum range of the target's weapon (non-maneuverable reference) \\ \hline wez\_nez\_t2o [m] & No-escape zone range of the target's weapon (reference performing high performance maneuver) \\ \hline vul\_thr\_bef\_shot & Level of risk acceptance before shooting \\ \hline vul\_thr\_aft\_shot & Level of risk acceptance after shooting \\ \hline shot\_point & Missile firing point between the maximum range and the no-escape zone range of the reference \\ \hline rwr\_warning & Boolean indicating whether the aircraft is equipped with an active RWR \\ \hline hp\_tgt\_off & High priority target offense index of the reference \\ \hline hp\_thr\_vul & High priority threat vulnerability index of the aircraft that is threatening the reference \\ \hline own\_shot\_phi & Reference shot philosophy \\ \hline enemy\_shot\_phi & Estimated enemy's shot philosophy \\ \hline \end{tabularx} \end{table} Concerning the target parameter, the DCA index will be averaged between the start of the agent's Commit maneuver and the beginning of either Break or Abort maneuvers since both will make the agent disengage. Therefore, given a sequence of input parameters that define the agent's state, the model must predict the average value of the DCA index in that interval, improving the agent's situational awareness. \subsection{Data Preprocessing} Unlike what is done in artificial neural networks, there is no need to carry out data normalization procedures to employ the XGBoost algorithm since it is based on decision trees. Thus, using this type of learning method, the model benefits from one of the significant advantages of these trees in artificial intelligence problems related to the low amount of preprocessing required for it to be applied. It is necessary to transform the model's categorical variables into numerical ones to be appropriately processed. For this purpose, two preprocessing steps will be performed on the data: Label Encoding and One-Hot Encoding~\cite{cohen2013applied}. Also, feature engineering will be carried out to facilitate the training process of the proposed regression model. \subsection{Hyperparameters Tuning} GridSearch is a hyperparameter adjustment process to determine the ideal values for a given model, based on searching throughout a grid~\cite{putatunda2018comparative}. The performance of the entire model is based on the specified hyperparameter values. Some functions have been implemented, such as the GridSearchCV of the sklearn library, to automate finding the best of these values for the model. We performed an adjustment of the XGBoost model hyperparameters based on a variation of the library default values as observed in Table~\ref{tab3}. \begin{table}[h] \centering \caption{GridSearch parameters for the prediction model.} \label{tab3} \begin{tabular}{|c|c|} \hline \textbf{Parameters} & \textbf{Values} \\ \hline n\_estimators & {[}100, 1000, 5000{]} \\ learning\_rate & {[}2, 3, 6, 10, 15, 20{]} \\ max\_depth & {[}0.1, 0.01, 0.001{]} \\ gamma & {[}0.0, 0.1, 0.2, 0.3, 0.4, 0.5{]} \\ subsample & {[}0.6, 0.7, 0.8, 0.9{]} \\ colsample\_bytree & {[}0.6, 0.7, 0.8, 0.9{]} \\ reg\_alpha & {[}0.001, 0.01, 0.1, 1, 10, 100{]} \\ min\_child\_weight & {[}1,3,5,7,9,10,13,15{]} \\ \hline \end{tabular} \end{table} \subsection{Metrics} The Root-Mean-Square Error (RMSE) is used to measure the differences between the values predicted by a model or an estimator concerning the actual values, providing the average magnitude of the error. As the errors are squared, the RMSE places a relatively high weight on significant errors, which means that RMSE should be most useful when large errors are particularly undesirable. In addition, the advantage of using the RMSE is that it has the same magnitude as the target variable, which helps in the interpretation of the average of the model errors found. In the analysis of the predictive models carried out in this work, the coefficient of determination ($R^2$) will also be used to evaluate the best architectures of the supervised machine learning models for BVR combat modeling. The use of $R^2$ is well established in classical regression analysis and it generally describes how the model is adapted to reality when making predictions. \subsection{Cross-Validation} After performing a dataset train-validation-test split, allocating 80\% for the training and validation and 20\% for the testing, we propose to conduct cross-validation to evaluate the model's ability to predict new data that was not used in the estimate with the benefits of using the whole train dataset for training and validation and to highlight problems such as overfitting~\cite{hyndman2006another}. We employ 10-fold cross-validation to address this problem after considering the trade-off between processing time and the generalization of the model results. \section{RESULTS AND ANALYSIS} This section presents a whole dataset exploratory data analysis to provide an initial understanding of the variables in the model, followed by 10-fold cross-validation results. \subsection{Exploratory Data Analysis} Exploratory data analysis began with a check of the main descriptive statistics of the model's input and output data. The input variables of the model follow a uniform distribution since they were sampled using LHS. The model's output variable, the DCA index, is a probability, and in this case, it ranges from a minimum value of 0.21 to a maximum value of 0.99. with a mean of 0.53 and a standard deviation of 0.12. Moreover, the mean and the median are almost the same (0.53 and 0.51), indicating a low number of outliers for this variable at the top of the distribution. A histogram and a boxplot were generated to visualize the distribution, as shown in Fig.~\ref{fig3}. The data of the target variable follows an approximately normal distribution around the average value. Regarding the aspect and heading difference, these two angular variables are transformed into four numerical variables to calculate their respective sine and cosine values. Note that the variables referring to WEZ have minimum values of $-1$. These values are model adjustments for when it is not possible to estimate the WEZ. \begin{figure}[h] \centering \includegraphics[width=0.485\textwidth]{hist_and_box.eps} \caption{Histogram and boxplot of the target variable.} \label{fig3} \end{figure} \begin{comment} \begin{table} \centering \caption{Descriptive statistics of the numerical model's input and output variables.}\label{tb4} \begin{tabular}{|c|c|c|c|c|c|} \cline{2-6} \multicolumn{1}{c|}{} & \textbf{mean} & \textbf{std} & \textbf{min} & \textbf{median} & \textbf{max} \\ \hline distance [m] & 54,676.38 & 25,828.54 & 3,564.59 & 46,653.23 & 92,556.43 \\ aspect [deg] & 151.04 & 17.97 & 65.57 & 151.02 & 180.00 \\ delta\_head [deg] & 106.68 & 50.50 & 0.03 & 116.80 & 179.99 \\ delta\_alt [ft] & 62.33 & 1,428.17 & -3,231.94 & 7.12 & 3,583.40 \\ delta\_vel [kn] & 0.21 & 7.34 & -49.47 & 0.04 & 52.53 \\ wez\_max\_o2t [m] & 24.04 & 10.90 & -1.00 & 27.34 & 40.11 \\ wez\_nez\_o2t [m] & 8.22 & 1.45 & -1.00 & 8.36 & 12.44 \\ wez\_max\_t2o [NM] & 20.37 & 15.41 & -1.00 & 27.31 & 41.06 \\ wez\_nez\_t2o [NM] & 5.56 & 4.64 & -1.00 & 7.95 & 12.57 \\ vul\_thr\_bef\_shot & 0.49 & 0.32 & 0.00 & 0.48 & 1.00 \\ vul\_thr\_aft\_shot & 0.52 & 0.32 & 0.00 & 0.55 & 1.00 \\ shot\_point & 0.56 & 0.32 & 0.00 & 0.63 & 1.00 \\ hp\_tgt\_off & 0.15 & 0.30 & 0.00 & 0.01 & 1.00 \\ hp\_thr\_vul & 0.12 & 0.27 & 0.00 & 0.01 & 0.99 \\ dca\_index & 0.53 & 0.12 & 0.21 & 0.51 & 0.99 \\ \hline \end{tabular} \end{table} \end{comment} \subsection{Model Results} The means of all 10-fold metrics, namely RMSE and $R^{2}$, used to evaluate the best model at the end of the grid search training process after performing the cross-validation are, respectively, $0.0543$ and 0.8020, while their standard deviations are 0.0009 and 0.0077. The coefficient of determination is approximately 80\%, and an RMSE, which penalizes the effects of outliers, is close to 0.05. Considering that this is a regression problem and that we are trying to predict the DCA index, which indicates a probability of success in this type of mission, the results are satisfactory for this type of problem since they would be making predictions with errors in the range of 5\% with a practically instantaneous inference time, which is desirable for a real-time application. \begin{comment} \begin{table} \centering \caption{Mean and standard deviation of the metrics used to evaluate the XGBoost model.}\label{tb3} \begin{tabular}{|c|c|c|c|c|} \cline{2-5} \multicolumn{1}{c|}{} & \textbf{MAE} & \textbf{MSE} & \textbf{RMSE} & \textbf{Coefficient of Determination ($R^{2}$)} \\ \hline \textbf{mean} & 0.0400 & 0.0030 & 0.0543 & 0.0802 \\ \textbf{std} & 0.0006 & 0.0001 & 0.0009 & 0.0077 \\ \hline \end{tabular} \end{table} \end{comment} \begin{comment} \begin{table} \centering \caption{Mean and standard deviation of the metrics used to evaluate the XGBoost model.}\label{tb3} \begin{tabular}{|c|c|c|} \cline{2-3} \multicolumn{1}{c|}{} & \textbf{RMSE} & \bm{$R^{2}$} \\ \hline \textbf{mean} & 0.0543 & 0.8020 \\ \textbf{std} & 0.0009 & 0.0077 \\ \hline \end{tabular} \end{table} \end{comment} \section{Conclusions and Future Work} This work presented a supervised machine learning model through the XGBoost library to develop an engagement decision support tool for BVR air combat in DCA missions. The model represented some of the primary dynamics of the BVR combat, allowing the analyst to evaluate the parameters that influence this combat. Additionally, we analyze in advance the performance of an engagement made by a pilot in air combat through the agent's DCA index, predicting the outcome of this confrontation. This kind of prediction may be used as an innovative decision support system for the pilots in this air combat modality concerning whether to engage an opponent or not. Although the index does not inform which is the better action to take, it measures the performance of the actions taken by the agent through the proposed modelings. The modeling considered the characteristics of the aircraft and their armaments, along with the beliefs about the opposing aircraft. In addition, we also used the shot philosophy for the aircraft and the pilot's level of risk aversion. The model showed an $R^2$ of 0.802 and an RMSE of 0.054. Assuming the average values of the DCA index as 0.53 and standard deviation of 0.12, the results showed relatively consistent values and good predictive power of the DCA index. With this degree of confidence in the model, it is possible to predict future pilot's conditions, even with a few samples. The regression model could calculate the average values of the DCA index in each engagement in a coherent manner, providing quick answers to the results of this air combat phase that could provide the pilot with an improvement in his situational awareness in real-time. Thus, through simulation data, it is possible to improve the employment of the best operational tactics for each situation in the complex context of BVR air combat. Furthermore, it contributes by avoiding the incorrect and careless use of weapons, improving DCA mission effectiveness. Finally, since the pilot's survival is a determining factor, it could decrease the number of friendly aircraft lost in real-life BVR air combat. Future work should move towards using a more significant number of simulations since we only analyzed 10,316 engagement cases due to the substantial computational cost to generate them. In addition, the search for more variables to define the agent state at the beginning of the engagement, or to do a feature engineering to generate new variables from the existing ones, could improve the performance of the proposed model. Also, comparing the results of XGBoost with other regression algorithms would be interesting to understand which supervised learning method best suits this type of problem. Finally, the conception of other operational metrics, like the DCA index, or the combination of several of them, to assess the level of performance in an engagement could contribute to bringing more information to the model. \section*{Acknowledgments} This work was supported by Finep (Reference nº 2824/20). Takashi Yoneyama is partially funded by CNPq -- National Research Council of Brazil through the grant 304134/2-18-0. \bibliographystyle{IEEEtran}
{'timestamp': '2021-11-19T02:02:39', 'yymm': '2111', 'arxiv_id': '2111.03059', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03059'}
arxiv
\section{Result Visualisations} In Section \ref{sec:experiments}, we detailed a series of experiments to test the capabilities of our \texttt{NeatNet} method. In this section, we visualise a selection of arrangements generated in these experiments to complement the quantitative results and analysis provided earlier. \subsection{Can NeatNet Tidy a Known Scene?} This experiment tests the tidiness of \texttt{NeatNet}'s reconstructed arrangements for known scenes (Table \ref{tab:exp-known-scene}). The example arrangement provided by the user contains noise and imperfect alignment of objects, as shown in Figure \ref{fig:tidying-known-scene}. \texttt{NeatNet} is able to reduce the noise by leveraging prior knowledge from other users when it reconstructs the scene. \begin{figure}[h] \centerline{\includegraphics[width=0.99\textwidth]{appendices_graphics/tidying-dining-table.png}} \caption{Tidying a known scene. \textbf{Left:} example arrangement supplied by a user. \textbf{Right:} reconstructed arrangement generated by \texttt{NeatNet}.} \label{fig:tidying-known-scene} \end{figure} \subsection{Can NeatNet Generalise to Objects Unseen During Training?} Table \ref{tab:exp-unseen-obj} shows the results of an experiment to place an object never seen before during training. Sample arrangements produced are visualised in Figures \ref{fig:abstract-unseen-object} and \ref{fig:office-unseen-object}. In the office scene, the network has never seen any examples of how a laptop should be placed, but it does know how this test user placed a computer, monitor, keyboard and mouse in their example arrangement of the office scene. Since these objects share linguistic and semantic features with the laptop, \texttt{NeatNet} is able to predict a reasonable position. \begin{figure}[htp] \centerline{\includegraphics[width=0.7\textwidth]{appendices_graphics/abs-unseen-neatnet.png}} \caption{Placing a new abstract object (the largest blue box). Its size is outside the range seen by the network during training. The network is able to correctly place it on the right-hand side, since the user prefers to group objects by shape. It also correctly extrapolates the order-of-size pattern. This demonstrates an important spatial reasoning capability: for example, stacking plates or books in order of size would be a common scenario for a household robot.} \label{fig:abstract-unseen-object} \end{figure} \begin{figure}[htp] \centerline{\includegraphics[width=0.99\textwidth]{appendices_graphics/office-place-laptop-comparison.png}} \caption{Placing a new object (the laptop). \textbf{Left:} \texttt{Nearest-Neighbour} baseline method. \textbf{Right:} \texttt{NeatNet} method, predicting a satisfactory position for the new laptop.} \label{fig:office-unseen-object} \end{figure} \subsection{Can NeatNet Predict a Personalised Arrangement for a New Scene?} In this experiment (Table \ref{tab:exp-new-scene}) the network has not seen how this test user likes this new scene to be arranged. It predicts this based on this user's preferences, inferred from another scene, and prior knowledge from how similar training users arranged this new scene. Sample generated arrangements are shown in Figure \ref{fig:abstract-new-scene}. \begin{figure}[H] \centerline{\includegraphics[width=0.8\textwidth]{appendices_graphics/whole-new-scene-comparison.png}} \caption{Arranging a new scene. \textbf{Left:} \texttt{kNN-Scene-Projection} correctly groups objects by colour, but does not line them up neatly, with some objects clipping into each other. \textbf{Right:} arrangement generated by \texttt{NeatNet}, using learned prior knowledge from how these objects were arranged by training users to neatly arrange them into lines.} \label{fig:abstract-new-scene} \end{figure} \subsection{Can the User Latent Space be Interpreted?} The NeatNet encoder maps each user to a vector in the shared latent space of user preferences. We visualise a batch of users in this latent space to investigate its interpretability in Figure \ref{fig:user-space}. To aid visualisation, the user dimension hyperparameter was set to 2. A clear separation can be seen in the user latent space for the abstract scenes, where a cluster of users chose to group objects by colour, and another chose to do so by shape, showing that preferences which generalise across scenes can be discovered by the network. The user preference space for tidying the dining table can also be readily interpreted, with separate clusters emerging for left-handed and right-handed users. This shows that \texttt{NeatNet} can successfully learn high-level, interpretable preference characteristics such as handedness, which influence the placement of several objects in a scene. \begin{figure}[htp] \centerline{\includegraphics[width=0.99\textwidth]{appendices_graphics/combined-user-space.png}} \caption{User latent space visualisation. Each point represents one inferred user vector. \\ \textbf{Left:} abstract scene preferences. \textbf{Right:} dining scene preferences.} \label{fig:user-space} \end{figure} \section{Implementation Details} In this section, we highlight several key points of implementation detail for the reader's convenience. Further low-level detail can be found in the code and inline documentation. \subsection{Libraries Used} The network architecture was implemented with the PyTorch machine learning library \cite{pytorch}. Additionally, the PyTorch Geometric library \cite{pytorch-geometric} was used to implement Graph Neural Network components. \subsection{Optimisation: Batching Scenes \& Users} A user's preference vector is inferred from all the example scenes provided by that user, as described in Section \ref{sec:multiscene}. Therefore, all the examples scenes for a user must be passed through the encoder. A naive implementation would iterate through the scenes and pass each one through the encoder in sequence. However, this would perform $O(n)$ forward passes for $n$ example scenes per user, which would significantly degrade the speed of training and inference. Instead, we wish to pass all the example scenes for one user through the network in one forward pass. Therefore, we batch these scenes together by stacking them into a \textit{supergraph}: a graph containing all the example scenes as subgraphs. The node matrices are concatenated together, so that the new supergraph contains all the nodes of the individual scene subgraphs. The edge structure is preserved so that each scene subgraph is fully connected but there are no edges between scene subgraphs. This is because each scene is arranged separately by the user, so remains separate in the supergraph structure. This approach allows multiple scenes arranged by the same user to be processed by the network in one forward pass. A similar technique is applied to combine the graphs of several users into a single supergraph representing a batch of users, using the batch data loader from PyTorch Geometric \cite{pytorch-geometric}. This allows us to control the batch size as a hyperparameter, balancing regularisation with the stability of the training process. \subsection{Hyperparameter Settings} The optimiser used to update \texttt{NeatNet}'s parameters is the PyTorch Stochastic Gradient Descent implementation with momentum (based on validation performance, this was chosen over Adam \cite{adam} for this specific task). Additionally, we use a PyTorch learning rate scheduler which reduces the learning rate when performance plateaus, to fine-tune the model towards the end of the training process. The network is trained for 2000 epochs, with an initial learning rate of 0.10 for abstract scenes and 0.08 for real scenes. We use a batch size of 4, to introduce sufficient regularisation. The graph encoding dimension is set to 20 for abstract scenes and 24 for real scenes. The encoder's Graph Attention \cite{gatconv} layer with a hidden dimension of 24 is followed by a fully-connected linear layer applied nodewise and 2 further fully-connected layers for the user preference extractor. The position predictor also uses a Graph Attention layer but with a hidden dimension of 32, followed by 2 fully-connected linear layers applied nodewise to predict positions for each node. Experiments on abstract scenes use a VAE $\beta$ value \cite{beta-vae} of 0.08, whereas 0.01 is used for real scenes to allow for further tailoring to individual preferences. The semantic embeddings for abstract objects are vectors which describe their size, RGB colour, and shape. Semantic embeddings for real objects are inferred from the word embeddings of their name. A negative slope of 0.2 is used for LeakyReLU activations \cite{leaky-relu}. The scheduler reduces the learning rate by a factor of 0.5, with a patience of 100 epochs (monitoring whether the loss is stagnating), and a cooldown period of an additional 80 epochs after the last halving. However, these vary slightly based on the specific task: further details can be found in the code. Data augmentation is applied to improve generalisation. Position encodings are normalised by subtracting the mean position across the training examples and downscaling the coordinates based on the maximum distance from the center found in the training dataset. This stabilises the training process. In order to prevent overfitting, Gaussian noise is added to object positions, with a standard deviation of 0.02 for the dining scene and 0.05 for the office scene. For experiments where the task is to predict the positions of missing objects, node masking (with a rate of 0.1) is applied during the training process, so that the network can learn to predict the positions of an object based on other objects. The initial learning rate is increased to 0.12, since the loss is otherwise more likely to stagnate in local optima, and the batch size is increased to 6 to stabilise the learning process. Similarly, a scene masking rate of 0.2 is applied to train the network to predict how a user would arrange a new scene based on their preferences inferred from another scene. \section{Pose Graph Baseline} One of our core contributions is the use of spatial preferences to tidy in a personalised way. To demonstrate that personalization improves user ratings, we include comparisons against strong baseline methods which can produce neat but not personalised arrangements. We developed a baseline method referred to in results tables as ``\texttt{Pose-Graph}''. It constructs a probabilistic pose graph to model general tidying preferences (not specific to any individual). The parameters of this model are learned from the same example arrangements that \texttt{NeatNet} trains on. This model can be used as a tidiness cost function. A sampling \& scoring graph optimisation technique is used to find the optimum of this cost function, outputting a tidy arrangement. \subsection{Modelling Arrangements as Pose Graphs} Each node represents an object, including its position. The edge between two nodes represents a probability distribution over possible displacements between those two objects. This distribution can be multi-modal, as shown in Figure \ref{fig:edge-distrib}, and so each edge stores the parameters of a Gaussian Mixture Model. \begin{figure}[htp] \centerline{\includegraphics[width=0.60\textwidth]{appendices_graphics/edge-distrib.png}} \caption{Example pose graph with two nodes and one edge, showing the most likely displacements from the plate to the cup. The Gaussian Mixture Model has two peaks: these positions for the cup as considered tidiest.} \label{fig:edge-distrib} \end{figure} \subsection{Learning Model Parameters} We now outline an algorithm for learning the parameters of this model from example scenes, so that the model will represent general tidying preferences. The output is a probabilistic pose graph, where each node is an object and each edge holds the parameters of a distribution over the displacements between those two objects. \IncMargin{1em} \begin{algorithm}[h]\label{alg-learning-cost-func} \caption{Learning the Cost Function} \SetAlgoLined \LinesNumbered \SetKwInOut{Input}{input} \SetKwInOut{Output}{output} \SetKwData{Disps}{displacements} \SetKwData{Distrib}{distributions} \Input{List of training scenes, each a list of $n$ objects} \Output{$n \times n$ matrix, where entry $(i, j)$ is a distribution over displacements from $i$ to $j$} \Distrib $\leftarrow$ EmptyMatrix($n$, $n$) \For{each pair of objects i, j}{ \Disps $\leftarrow$ $[ \ ]$ \For {each scene in scenes}{ \Disps $\leftarrow$ \Disps $++$ (scene$[j]$ $-$ scene$[i]$) } \tcp{Calls a density estimation algorithm, like EM-GMM.} \Distrib$[i][j]$ $\leftarrow$ FitDistribution(\Disps) } \end{algorithm} \DecMargin{1em} To fit the distribution in each edge, we apply the Expectation-Maximisation algorithm (using the sckit-learn library \cite{scikit-learn}), which outputs the parameters of a Gaussian Mixture Model. \subsection{Using the Model as a Cost Function}\label{s:cost-function} Here we describe how the probabilistic pose graph can be used as a cost function for tidiness. The input to this function will be an arrangement $(x_1, \ldots, x_n)$, i.e. a position $x_i$ for each object node $i$. The output will be some scalar tidiness cost, so that tidy arrangements have a low cost and untidy arrangements have a high cost. Consider the local cost function $c_{ij}(x_i, x_j)$ for an edge between two objects $i$ and $j$. Suppose that the displacement between them is $z_{ij} = x_j - x_i$. In a tidy arrangement, that displacement is a very likely one, i.e. $p_{ij}(z_{ij})$ is high. Therefore, we set the cost function of this edge to be the negative log-likelihood of the displacement between those two objects: \begin{equation} c_{ij}(x_i, x_j) \triangleq - \log p_{ij}(z_{ij}) \end{equation} The global cost function is an aggregation of edge likelihoods, summing over each pair of objects: \begin{equation}\label{eq:global-cost-func} C(x_i,\ldots ,x_n) \triangleq - \sum_{i=1}^{n-1} \sum_{j=i + 1}^n \log p_{ij}(z_{ij}) \end{equation} This aggregation is similar to the global error function in graph-based SLAM literature, which is also the sum of the errors in each edge \cite{slam-tutorial}. This means that arrangements where the distance between each object is likely are considered tidy, and arrangements where the distances between each object are implausible will have a high cost. \subsection{Finding the Optimum of the Cost Function} At this point, we know how we can use a probabilistic pose graph as a cost function, and we know how to learn the parameters of this cost function so that it models human tidying preferences. Given an arrangement of objects, this cost function will tell us whether one arrangement is more or less tidy than another. Now, we want to find the tidiest possible arrangement, i.e. one which corresponds to the optimum of the cost function. Once we have this optimal arrangement, then the robot will know where each object should be placed to tidy a scene. \subsubsection{Objective Definition} The optimisation objective is to find the tidiest possible arrangement, i.e. we need to find a position for each object such that the overall cost function defined in Equation \ref{eq:global-cost-func} is minimised. The tidiest arrangement which we are trying to find is therefore given by: \begin{equation} x_1^*, \ldots, x_n^* = \argmin_{x_1, \ldots, x_n} C(x_i,\ldots ,x_n) \end{equation} Intuitively, this means we need to find a position for each node such that each edge in the pose graph is as ``likely'' as possible. An analogy often used in SLAM literature goes as follows: imagine that each edge is an elastic spring attached between nodes. Shifting one node may loosen some springs attached to it but tighten some others instead, which are pulling in a different direction. We want to minimise the strain on the system, i.e. arrange the nodes so that as many of the springs are as loose as possible. This means we need to simultaneously optimise many relative constraints. Therefore, we can apply techniques inspired by SLAM literature to optimise this pose graph, and find a solution with a low cost. \subsubsection{Sampling \& Scoring Algorithm} We now detail an algorithm for placing the objects into the scene in a way which simultaneously optimises the edges between all the object nodes. This is based on SLAM techniques for handling multi-modal distributions \cite{multimodal-slam}. The intuitive idea is as follows. We start with a set of candidate arrangements, each containing just an origin node. Then, we add one object at a time. To add the next object, we sample from the distribution in the graph edge which connects it to its parent in the tree. This distribution returns a displacement, allowing us to place this new object into the arrangement based on the position of its parent (already placed). We place this object into every candidate arrangement. Then, we evaluate each candidate, by aggregating the likelihood of all the edges in that arrangement (using the cost functions defined in Section \ref{s:cost-function}). Once all the objects have been placed, the candidate with the highest likelihood is the tidied solution. If at any stage we have too many candidates with low scores, we can re-sample: candidates with higher weights are more likely to survive, and unlikely arrangements will be eliminated. However, since our graphs are fully connected, re-sampling is often not necessary because the trees are rarely very deep, and so error does not accumulate as much as it would when performing SLAM along a long corridor. This sampling \& scoring algorithm is illustrated in Figure \ref{fig:slam-weights-illustration}. \newpage \begin{figure}[ht] \centerline{\includegraphics[width=0.6\textwidth]{appendices_graphics/slam-particle-illustration.png}} \caption{Illustration of our sampling-based method. Each candidate is assigned one colour and represents one full arrangement of the Table, Bowl and Cup. The Table is chosen as the origin node in this example. The green poses represent one possible arrangement, which has the greatest circles and the largest weight. This is because the relative displacements between the green pose estimates are closest to the ground truth optimal relative displacements in this experiment, marked by the dashed lines. The slightly smaller blue poses represent another candidate, slightly less likely but still reasonably highly weighted (note that the relative displacement between the Bowl and Cup is similar to the optimal). The red circles are the smallest because the arrangement is highly improbable.} \label{fig:slam-weights-illustration} \end{figure} The order in which we add objects into the scene is determined by a spanning tree of the pose graph: this is passed into this algorithm. Since all edges are used to score arrangements, the algorithm will run correctly regardless of which tree is chosen, but we can improve performance by selecting edges according to some heuristics. We found that prioritising edges with the lowest Bayesian Information Criterion \cite{bic-criterion} improved performance. Intuitively, if the graph contains a ``strict'' edge between two objects (e.g. between the fork and the knife), then that edge is likely to be prioritised, and this quickly eliminates untidy arrangements. An example tree is shown in Figure \ref{fig:bic-tree}. \begin{figure}[htp] \centerline{\includegraphics[width=0.6\textwidth]{appendices_graphics/pose-graph-tree.pdf}} \caption{The tree selected for the office scene using BIC. Arrows represent edges in the tree. The notepad is chosen as the parent of both the lamp and the pencil, meaning that the positions of those objects are closely related, as would be expected semantically.} \label{fig:bic-tree} \end{figure} \newpage The full algorithm for sampling and scoring arrangements is given below. The output is a list of candidate arrangements, from which we can pick the tidiest (the one with the highest score). This produces an arrangement which is near the optimum of the learned cost function for tidiness. \IncMargin{1em} \begin{algorithm}[H] \caption{Sampling \& Scoring: Minimising the Cost Function} \SetAlgoLined \LinesNumbered \SetKwInOut{Input}{input} \SetKwInOut{Output}{output} \SetKwData{Distribs}{distributions} \SetKwData{Edges}{edges} \SetKwData{Scores}{scores} \SetKwData{Arrs}{arrangements} \SetKwData{Pop}{pop\_size} \SetKwData{Displ}{displacement} \Input{Matrix of relative \Distribs} \Input{A list of \Edges defining a minimum spanning tree in the \Distribs graph} \Input{Number of solutions, \Pop , defaulting to 1000} \Output{A list of \Scores} \Output{A list of \Arrs, each a list of object positions} Initialise each score to 1 / \Pop \Arrs $\leftarrow$ [ ] \For{each edge in \Edges}{ (start, end) $\leftarrow$ edge \For{$i$ in $0$..\Pop}{ \tcp{Sample a position for the new node.} \tcp{Displacement may need to be flipped to match edge direction.} \Displ $\leftarrow$ \Distribs[start][end].sample() start\_pos $\leftarrow$ \Arrs[i][start] end\_pos $\leftarrow$ start\_pos + \Displ \Arrs[i][end] $\leftarrow$ end\_pos \BlankLine \tcp{Score arrangement based on total likelihood of all edges so far.} likelihood $\leftarrow$ ScoreArrangement(\Distribs, \Arrs[i]) score $\leftarrow$ 1 / \Pop + likelihood } Normalise scores: divide by total score. If too many arrangements have a low score, can resample here. } Sort \Arrs so that highest scores are first. \end{algorithm} \DecMargin{1em} We have shown how these algorithms allow the \texttt{Pose-Graph} baseline method to generate arrangements which are generally tidy, but not tailored to any specific user. \section{Introduction} Rearranging objects in unstructured environments is a fundamental task in robotics. For example, a domestic robot could be required to set a dinner table, tidy a messy desk, and find a home for a newly-bought object. Given goal states stipulating where each object should go, many approaches exist for planning a sequence of actions to manipulate objects into the desired arrangement \cite{embodied-ai,planning-tamp,planning-automated}. But how does a robot know what these goal states should be, for a rearrangement to be considered successful, tidy, and aesthetically pleasing? The ability of a robot to understand human preferences, especially regarding the handling of personal objects, is a key priority for users \cite{user-preferences-important}. Several factors involved in spatial preferences are shared across many users: symmetry and usefulness are preferable to chaos. Stacking plates neatly inside a cupboard rather than scattering them randomly across a sofa is common sense. However, many of the factors involved are inherently personal, as is their relative prioritisation. For example, is the person left or right-handed? Do they want their favourite book tidied away neatly on a shelf, or placed on the table nearby for convenience? How high is their risk tolerance --- do they deliberately keep fragile glasses further from the edge of the shelf, even if it makes them harder to reach? Do they order food in the fridge with the tallest objects at the back and the shortest at the front? Or do they keep the most frequently used items at the front and easily reachable? In this case, how does the robot know which items are most frequently used and ought to be placed near the front? This in itself depends on personal preference. It is clear that spatial preferences are a complex, multi-faceted, and subjective concept. In this paper, we propose an object rearrangement strategy which models these preferences with a latent user vector representation, inferred by directly observing how a user organises their home environment. The network is trained on arrangements made by a set of training users. For a test user, the robot will observe how they have arranged their home. This can be achieved by a robot using existing techniques for localisation, object identification and pose estimation \cite{slam-fusionpp,yolo,densefusion}. By passing these example scenes through the Variational Autoencoder, the network will extract this test user's preference vector. This can then be used by a robot to tidy up these scenes, and also predict personalised arrangements for new objects and new scenes based on how training users with ``similar'' preferences to this test user arranged them. These predicted arrangements can then be used as target states for planning and manipulation algorithms \cite{embodied-ai}. \begin{figure}[H] \centerline{\includegraphics[width=0.9\textwidth]{graphics/neatnet-intro-summary.pdf}} \caption{NeatNet infers a user preference vector, and can then predict personalised arrangements.} \label{fig:intro-summary} \end{figure} \vspace{-0.4cm} We make the following contributions, adding a layer of personalisation to robotic rearrangement: \textbf{Novel Graph VAE Architecture}. We present NeatNet: an architecture for learning spatial preferences. Users are encoded through representation learning with Variational Autoencoders. Graph Neural Network (GNN) layers are used to learn from scenes arranged by users. \textbf{Word Embeddings for Object Generalisation}. Our network extracts semantic features for an object from the word embedding of its name, enabling generalisation to objects unseen during training. \textbf{User-Driven Evaluation}. We develop TidySim: a 3D simulator web app for users to arrange scenes. With rearrangement data from 75 users, we demonstrate empirically that our method can learn spatial preferences, and predict personalised arrangements which users rate highly. Visualisations of predicted arrangements are available in the appendices and on our project page, together with our code and a summary video: \href{https://www.robot-learning.uk/my-house-my-rules}{www.robot-learning.uk/my-house-my-rules}. \section{Related Work}\label{sec:related-work} A crucial challenge in the field of robotic rearrangement is predicting a position for each object in order to form a tidy arrangement. Prior approaches discretise the problem by semantically grouping objects into containers \cite{abdo-shelves, organisational-principles-classification}, learn Dirichlet Process models of common object locations \cite{taniguchi-spatial-concepts, jiang-human-context}, or optimise a cost function based on one user's examples \cite{kang-simulated-annealing}. We now discuss these three approaches, and then briefly reference existing neural methods for learning non-spatial user preferences. \textbf{Grouping semantically related objects.} Collaborative filtering \citep{abdo-shelves} can predict how a user would categorise an object based on how similar users categorised it. Data is mined from object taxonomies such as shopping websites to generalise to new objects: preferences about known objects nearby in the hierarchy are used to select a shelf for the new object. Object taxonomies can also be used to place an object into the correct cupboard, viewed as a classification task \citep{organisational-principles-classification}. While these approaches are effective in grouping objects into boxes or cupboards, our method addresses the general case of learning continuous spatial relations, like how to set a dining table or tidy an office desk. \textbf{Dirichlet Process models}. Recent work \citep{taniguchi-spatial-concepts} learns \textit{spatial concepts}: i.e. the relationship between an object, its tidied location, and a name to describe that location (useful for voice commands). Model parameters are learned with Gibbs Sampling. Another approach with Dirichlet Process modelling uses context from sampled human poses \citep{jiang-human-context} to position objects conveniently. Density function parameters are shared across objects of the same type. This approach is evaluated on a training dataset of arrangements made by 3-5 users, with a further 2 users scoring arrangements. While these methods predict generally tidy arrangements, it is not shown whether they can tailor them to individual preferences. We develop a tidying simulator to gather data on a larger scale, demonstrating that our neural encoder makes personalised predictions on a dataset of 75 users. Furthermore, our method uses word embeddings to predict positions for objects unseen during training, and learns transferable representations of tidying preferences which can be applied to arrange new scenes. \textbf{Example-driven tidiness loss function.} Another approach is to ask each user to provide several tidy arrangements for a scene, to serve as positive examples \citep{kang-simulated-annealing}. To tidy a scene, the robot computes a target tidy layout using a cost function which encourages altering the object-object distances in the untidy scene to match those in the ``closest'' tidy positive example. Simulated re-annealing is used to optimise this cost function efficiently. We add value firstly because our method generalises to unseen objects without requiring users to arrange them manually, and secondly because our method combines knowledge about the current user's preferences with prior knowledge about ``similar'' training users, correcting errors in individual examples and allowing for stronger generalisation. \textbf{Neural recommender systems.} Neural networks have been used for making recommendations based on user preferences \cite{neural-collaborative-filtering}. The YouTube neural recommender system \citep{youtube-recommender} predicts a user's expected watch time for a future video based on past videos watched and searches made. However, these methods do not address the challenges of learning spatial relations by observing scenes and predicting tidy arrangements for any set of objects. We apply GNN components to solve this. \section{Method} We introduce NeatNet: a novel architecture for learning spatial preferences. First, we describe a Variational Autoencoder for learning latent representations of a user's preferences (Section \ref{sec:vae}). Then we introduce the GNN layers which allow NeatNet to learn from scenes arranged by users, modelled as graphs of objects (Section \ref{sec:gnns}). Next, we adapt the architecture to learn from multiple example scenes per user (Section \ref{sec:multiscene}). Finally, we illustrate how object semantic embeddings are inferred from word embeddings, for generalisation to unseen objects (Section \ref{sec:semantic-embeddings}). \subsection{Encoding User Preferences with VAEs}\label{sec:vae} Our objective is to learn a user encoder function $\mathcal{E}_\phi$, represented by a neural network with learned parameters $\phi$. Its output is a user's preference vector $u$. Its input is a representation of a scene arrangement made by that user. Each scene is defined by the terms $s$ (the semantic identities of the objects in the scene, further explained in Section \ref{sec:semantic-embeddings}), and $p$ (the position encodings for those objects, e.g. coordinates). These are not passed into the VAE directly: scenes are first encoded using GNN layers (Section \ref{sec:gnns}), since scenes can have a variable number of objects. We also train a position predictor function $\mathcal{D}_\theta$. Given a set of objects identified by $s$, and a user preference vector $u$, this predicts a position for each object which reflects those spatial preferences. \begin{figure}[h] \centerline{\includegraphics[width=0.8\textwidth]{graphics/mapping-to-user-space.pdf}} \caption{Two users being mapped to points in the user latent space based on how they arrange a dining scene. Users close together in this latent vector space share similar spatial preferences.} \label{fig:mapping-to-user-space} \end{figure} These networks are trained end-to-end as a Variational Autoencoder \citep{vae}. A scene represented by $s$ and $p$ is passed into the encoder $\mathcal{E}_\phi$. The output user preference vector $u$, along with the semantic embeddings of the objects $s$, is passed into the position predictor $\mathcal{D}_\theta$, which acts as a decoder by reconstructing the original scene. Since the user preference vector is a low-dimensional bottleneck, this encourages the network to learn important spatial preferences like left/right-handedness which are useful for predicting the positions of many objects at once. For variational inference, the encoder $\mathcal{E}_\phi$ predicts a Gaussian distribution over the possible user vectors $u$ which could explain the input scene. At training time, we sample from this distribution to obtain $u$, and we take the mean at inference time. The VAE objective is thus $\phi^*, \theta^* \triangleq \argmin_{\phi, \theta} L(\phi, \theta)$. \begin{gather} L(\phi, \theta) \triangleq \mathbb{E}_{p_{data}(s, p)} \bigl[ \| \mathcal{D}_\theta(\underbrace{\mathcal{E}_\phi(s, p)}_{= u}, s) - p \|_2^2 + \beta KL \left[ q_\phi(u|s, p) \| p(u) \right] \bigr] \end{gather}\label{eq:vae-loss} Here, $p_{data}$ represents the training data distribution. $p(u)$ is a prior over the user preference vectors: a standard Gaussian, with zero mean and unit variance. KL represents the Kullback–Leibler divergence (standard in VAEs \citep{vae}) which encourages the estimated $u$ distributions to stay close to the $p(u)$ Gaussian prior over the user space, and the hyperparameter $\beta$ scales this prior term to make the latent space less sparse and encourage disentanglement \citep{beta-vae}. \subsection{Encoding Scenes with GNN Layers}\label{sec:gnns} We will now encode scenes as vectors so that they can be passed through the VAE. To do this, we use Graph Neural Network (GNN) layers. GNNs can operate on scenes with a variable number of arbitrary nodes, which is critical since the robot cannot foresee all the objects it will ever encounter. Each node represents an object in the scene. Node $i$ has feature vector $x_i$ formed by concatenating the semantic embedding for that object $s_i$ with its position encoding $p_i$. The scene graph is fully connected, to avoid making assumptions about which object-object relations are relevant or not. \begin{figure}[H] \centerline{\includegraphics[width=0.7\textwidth]{graphics/neatgraph-encoder.pdf}} \caption{The encoder network, all together representing the function $\mathcal{E}_\phi$ defined in Section \ref{sec:vae}. The input is a node feature matrix with a row for each node's feature vector $x_i \triangleq s_i ~ || ~ p_i$. The graph encoder consists of GAT layers (described later) separated by ELU non-linearities \citep{elu}. Then we pass the final feature vector of each node through a network of fully-connected layers, which has the same output size as the graph encoding vector. To aggregate the output node vectors into a single graph encoding vector, we apply a global add-pooling layer. This graph encoding vector is passed through a user preference extractor: a series of fully-connected layers separated by LeakyReLU activations \citep{leaky-relu}. The output is a mean and variance for the user preference vector distribution, from which we sample to obtain $u$. This is a latent vector which may not always be interpretable, but it might capture features such as whether the user prefers convenience over aesthetics.} \label{fig:gnn-encoder} \end{figure} \begin{figure}[H] \centerline{\includegraphics[width=0.65\textwidth]{graphics/neatgraph-decoder.pdf}} \caption{The position predictor, which acts as the decoder $\mathcal{D}_\theta$. The input now consists of a set of objects for which we wish to predict positions, according to a user preference vector $u$. We set the node feature vectors to be $x_i \triangleq p_i \| u$. This time, the output is a position vector for each node. Our experiments focus on positions, but the position vector can be extended to include orientation information. Similarly to the graph encoder, the position predictor consists of a sequence of GAT layers, after which each node is passed through a series of fully-connected layers, the final output of which is the predicted position vector for that node.} \label{fig:gnn-decoder} \end{figure} Both the graph encoder (Figure \ref{fig:gnn-encoder}) and position predictor (Figure \ref{fig:gnn-decoder}) use GNN layers. As is standard for GNN layers, we need to compute the hidden feature vector $h_i$ for each node $i$, based on its current feature vector $x_i$ as well as the node feature vectors $x_j$ of its neighbours. To compute $h_i$, we choose the Graph Attention (GAT) layer \citep{gatconv}. $h_i$ is computed as a weighted sum of the node feature vectors $x_j$ in the current node's neighbourhood, where the weights $\alpha_{ij}$ are generated by the soft attention mechanism. Since our graph is fully connected, we calculate attention weights for all the other objects in the scene: therefore the attention mechanism allows the network to autonomously decide which object-to-object relations are the most important for predicting correct arrangements. In order to further increase the power of the graph network, we can add a second GAT layer which takes as input the $h_i$ features produced by the first layer. A GAT layer computes $h_i$ as follows, where $\|$ represents concatenation, and the learned parameters are the weights \textbf{W} and $a$: \begin{align} h_i &\triangleq \sum_{j \in \mathcal{N}_i} \alpha_{ij} \textbf{W} x_j & \alpha_{ij} &\triangleq \frac{\exp\left(\text{LeakyReLU}\left(a^T\left[\textbf{W}x_i \| \textbf{W}x_j\right]\right)\right)}{\sum_{k \in \mathcal{N}_i} \exp\left(\text{LeakyReLU}\left(a^T\left[\textbf{W}x_i \| \textbf{W}x_k\right]\right)\right)} \end{align} \subsection{Generalising Across Scenes}\label{sec:multiscene} Many spatial preferences, such as left/right-handedness, will be exhibited by the user consistently across scenes. We now extend NeatNet to learn from multiple scenes arranged by the same user, as shown in Figure \ref{fig:multiscene-neatnet}. Every example scene arranged by the current user is passed through the single-scene encoder network $\mathcal{E}_\phi$ in Figure \ref{fig:gnn-encoder}. Each scene may produce a subtly different estimate of the user's preferences, so they are aggregated through a global pooling layer to produce an average user preference vector $u$. On the decoding side, we use the same $u$ vector as the input to the position predictor to reconstruct \textit{all} the scenes created by this user. Since $u$ is the architecture's bottleneck, this encourages the network to learn important preference features which generalise across scenes, such as left/right handedness or a preference for arranging objects compactly rather than spaciously. \begin{figure}[h] \centerline{\includegraphics[width=0.99\textwidth]{graphics/multiscene-neatnet.pdf}} \caption{Learning one generalised user preference vector across multiple example scenes per user.} \label{fig:multiscene-neatnet} \end{figure} \subsection{Semantic Embeddings}\label{sec:semantic-embeddings} Each object's identity is represented by its semantic embedding vector. One-hot encoding is a straightforward approach. A limitation of this method is that it does not generalise readily to new objects. An alternative is feature vectors: example entries include the height of an object, or RGB values describing its colour palette. However, this may not capture all features necessary for tidying. We also develop a method using word embeddings. Objects which appear in similar linguistic contexts are used for similar activities, and so are often arranged in a related way: for example ``pen'' and ``pencil'', or ``salt'' and ``pepper''. We load word embeddings from a FastText model \citep{fasttext}, pre-trained on the Common Crawl dataset of over 600 billion tokens. Names of objects are provided to NeatNet either by the simulator or by an object detection system if deployed physically. These names are converted to word embeddings and passed through the semantic embedding extractor (Figure \ref{fig:word-embeddings}), yielding the semantic embeddings referred to in Figure \ref{fig:gnn-encoder}. This allows the robot to predict positions for new objects never seen before in any tidy arrangement during training. \begin{figure}[ht] \centerline{\includegraphics[width=0.9\textwidth]{graphics/combined-word-embeddings.pdf}} \caption{\textbf{Left:} Word embedding space. Object names which appear in similar linguistic contexts will be close together in this latent space. \textbf{Right:} the semantic embedding extractor outputs an object's semantic embedding vector, using fully-connected layers. This is trained end-to-end with NeatNet, to extract the object features which are most relevant for our spatial arrangement task.} \label{fig:word-embeddings} \end{figure} \section{Experiments}\label{sec:experiments} \subsection{Collecting Rearrangement Data from Users} Gathering data from human users at scale is a significant challenge for robotics experiments. We developed TidySim: a 3D object rearrangement simulator deployed as a web app, allowing users to arrange a series of scenes through an intuitive interface. Features include: moving the camera, clicking and dragging objects to move or rotate them, and an inventory for unplaced objects. \begin{figure}[h] \centerline{\includegraphics[width=0.99\textwidth]{graphics/neatnet-evaluation-scenes.pdf}} \caption{Scenes arranged by users. From left: (1-2) are abstract scenes, where users must split the objects into two lines, either by shape or by colour, (3) is a dining room, and (4) is an office desk.} \label{fig:experiment-scenes} \end{figure} \vspace{-0.4cm} \subsection{Experimental Procedure}\label{sec:experimental-procedure} We designed the scenes in Figure \ref{fig:experiment-scenes} to maximise experimental value while keeping the user workload low ($\sim$ 5 minutes total per user). Rearrangement data from 75 users was gathered by distributing the experiment link on social media. Each user submits a tidy arrangement for a number of scenes. We set aside a group of 8 test users, male and female, and majority non-roboticists. The training dataset was formed from the 67 remaining users. NeatNet was trained by passing training users through the Graph VAE and updating parameters with a neural network optimiser according to the loss function in Equation \ref{eq:vae-loss}. For each test user, we passed their example scenes through NeatNet to extract their spatial preferences, and predict a personalised arrangement for the test scene (varies by experiment). Arrangements were also produced by the baseline methods in Section \ref{sec:baselines}. The test user was then asked to score the arrangements produced by each method based on how tidy they were according to their preferences, on a scale from 0 (completely untidy) to 10 (perfectly tidy). \subsection{Baselines}\label{sec:baselines} In Section \ref{sec:related-work}, we qualitatively compare with existing methods to show where we add new capabilities. For a fair quantitative evaluation of our method on this dataset, we test against a variety of baseline methods depending on the specific rearrangement task. \texttt{\textbf{Positive-Example}}: to tidy a known scene, this baseline copies the example arrangement which was supplied by the test user (which the \texttt{NeatNet} method uses to extract this user's tidying preferences). This baseline ignores priors from other users and is unavailable when generalising to new objects or scenes. \textbf{\texttt{Random-Position}} sets the missing object's predicted position randomly, while \textbf{\texttt{Mean-Position}} uses the object's mean position across all the example arrangements from training users. \textbf{\texttt{NeatNet-No-Prefs}} is an ablation baseline: the test user's preference vector is replaced with the zero vector (representing a neutral preference, which test users might not find tidy). The \textbf{\texttt{Pose-Graph}} method produces an arrangement which some users will find tidy, but is still not personalised to the current user's preferences. It learns a probabilistic pose graph of relative object positions from the training example arrangements, and solves it using Monte Carlo sampling and scoring to find the most likely arrangement. When placing an unseen object, \textbf{\texttt{Mean-With-Offset}} uses the mean position of the other objects in the scene, and adds a small random offset to minimise collisions with other objects. \textbf{\texttt{Nearest-Neighbour}} finds the object already placed by the user which has the closest word embedding vector to the unseen object, and places the new object next to it, i.e. it would place the salt next to the pepper. \textbf{\texttt{Weighted-kNN-Regression}} uses the $k = 3$ nearest neighbours, weighted by word distance, to compute an average position. For the task of arranging a new scene, the \textbf{\texttt{Random-User}} baseline copies how a random training user arranged that scene, without personalisation. \texttt{kNN-Scene-Projection} projects the user's preferences from the example scene onto the new scene, by placing each object in the new scene based on how the user placed the $k = 3$ most similar objects in the example scene, similar to the \texttt{Weighted-kNN-Regression} algorithm. \subsection{Experiment Results} We designed a series of experiments to test our method's capabilities. Visualisations of predicted arrangements are available in the appendices and on our project page:\newline \href{https://www.robot-learning.uk/my-house-my-rules}{www.robot-learning.uk/my-house-my-rules}. \textbf{Can NeatNet Tidy a Known Scene?} (Table \ref{tab:exp-known-scene}) Suppose that the robot has seen the user tidy a room. After the room becomes untidy, the robot must tidy up each object. This tests how well the network can reconstruct the scene based on the user preference vector and its prior knowledge. For each scene separately, we trained NeatNet as described in Section \ref{sec:experimental-procedure}. Then for each test user we pass their scene through the VAE and ask them to rate the reconstructed scene. \begin{table}[h] \centerline{ \begin{tabular}{|c|c|c|c|c|c|} \hline Tidying Method & Abstract 1 & Abstract 2 & Dining Table & Office Desk & Average \\ \hline \texttt{Mean-Position} & 3.25 \stddev{2.04} & 3.00 \stddev{1.94} & 2.34 \stddev{1.17} & 2.22 \stddev{1.48} & 2.70 \stddev{1.50} \\ \hline \texttt{NeatNet-No-Prefs} & 4.50 \stddev{1.73} & 3.75 \stddev{1.31} & 2.58 \stddev{1.06} & 3.70 \stddev{1.10} & 3.63 \stddev{1.38} \\ \hline \texttt{Pose-Graph} & --- & --- & 6.98 \stddev{1.53} & 7.82 \stddev{0.86} & 7.40 \stddev{1.22} \\ \hline \texttt{Positive-Example} & \textbf{8.75} \stddev{1.26} & 7.50 \stddev{0.55} & 8.60 \stddev{0.58} & \textbf{9.18} \stddev{0.81} & 8.51 \stddev{0.98} \\ \hline \texttt{NeatNet} & \textbf{8.75} \stddev{1.46} & \textbf{8.25} \stddev{1.45} & \textbf{9.12} \stddev{0.49} & 8.90 \stddev{0.40} & \textbf{8.76} \stddev{1.17} \\ \hline \end{tabular}} \vspace{0.2cm} \caption{Tidying a known scene. Rows are tidying methods and columns are scenes. The mean and standard deviation of tidiness scores given by test users are shown, along with a cross-scene average.} \label{tab:exp-known-scene} \end{table} \texttt{NeatNet} can reconstruct personalised tidy arrangements from a user preference vector, out-performing baselines and approaching the user's handmade \texttt{Positive-Example}. In a direct comparison, all test users ranked \texttt{NeatNet} over \texttt{Pose-Graph}. Surprisingly, users sometimes even prefer the reconstructed tidy scene \textit{over their own example}. This is because in each individual user-created arrangement, there is noise in how they placed each object (realistically this would also include error from localisation/pose estimation). Our method uses prior knowledge from other users to correct for noise in individual examples (analogous to VAE image denoising \cite{vae-denoising}). \textbf{Can NeatNet Find a Home for a New Object?} (Table \ref{tab:exp-new-object}) If a user brings a new object (e.g. a cup) into the scene, the robot should predict a tidy position for it. NeatNet is trained as before, but with the positions of random nodes masked out from input examples to encourage generalisation. At test time, we mask out the new object's position from the test user's example arrangement, but the position predictor must still place it. This is analogous to the use of generative models for ``inpainting'' missing or obstructed regions of input images \cite{inpainting}. This experiment is repeated for each object. \texttt{NeatNet} outperforms the baselines by successfully combining what it knows about the current user's preferences with prior knowledge of how similar users placed the new object. \begin{table}[H] \centering \begin{tabular}{|c|r|r|r|r|r|} \hline Prediction Method & \multicolumn{1}{|c|}{Cup} & \multicolumn{1}{|c|}{Fork} & \multicolumn{1}{|c|}{Knife} & \multicolumn{1}{|c|}{Plate} & \multicolumn{1}{|c|}{Average} \\ \hline \texttt{Random-Position} & 26.70 \stddev{9.07} & 15.76 \stddev{5.51} & 15.96 \stddev{8.03} & 7.10 \stddev{4.49} & 16.38 \stddev{8.19} \\ \hline \texttt{NeatNet-No-Prefs} & 13.20 \stddev{6.52} & 14.98 \stddev{5.01} & 13.38 \stddev{5.77} & 2.88 \stddev{1.02} & 11.12 \stddev{6.23} \\ \hline \texttt{Mean-Position} & 11.42 \stddev{5.19} & 15.06 \stddev{5.50} & 13.48 \stddev{6.27} & \textbf{1.64} \stddev{0.65} & 10.40 \stddev{6.14} \\ \hline \texttt{NeatNet} & \textbf{5.72} \stddev{1.46} & \textbf{1.18} \stddev{0.76} & \textbf{1.44} \stddev{1.15} & 1.96 \stddev{0.67} & \textbf{2.58} \stddev{1.34} \\ \hline \end{tabular} \vspace{0.2cm} \caption{Placing a new object into the scene. Figures show the mean and standard deviation of the absolute error between the predicted and true, unmasked positions of each object (in centimetres).} \label{tab:exp-new-object} \end{table} \vspace{-0.4cm} \textbf{Can NeatNet Generalise to Objects Unseen During Training?} (Table \ref{tab:exp-unseen-obj}) The network must place a new blue box into an abstract scene, and a laptop into the office scene, though it has never seen a laptop during training. The training process is similar to the previous experiment. \texttt{NeatNet}'s placement of the new objects (box and laptop) is satisfactory to users. To place the laptop, \texttt{NeatNet} considers how the user placed several semantically similar objects: the computer, laptop and keyboard. The \texttt{Nearest-Neighbour} baseline places the laptop based solely on how the user placed their desktop computer, thus misplacing it under the desk. \texttt{Weighted-kNN-Regression} performs well, but \texttt{NeatNet} was still ranked higher by every user because it can extract the semantic information from the word vectors which is most useful for tidying, since the network is trained end-to-end. Furthermore, \texttt{NeatNet} is able to learn and extrapolate the order-of-size pattern in the abstract scene. \begin{table}[h] \centering \begin{tabular}{|c|c|c|c|} \hline Tidying Method & Abstract Scene & Office Desk & Average \\ \hline \texttt{Mean-With-Offset} & 2.58 \stddev{1.35} & 4.68 \stddev{1.31} & 3.63 \\ \hline \texttt{Nearest-Neighbour} & 5.78 \stddev{1.32} & 1.70 \stddev{0.67} & 3.74 \\ \hline \texttt{Weighted-kNN-Regression} & 4.22 \stddev{0.83} & 7.80 \stddev{1.64} & 6.01 \\ \hline \texttt{NeatNet} & \textbf{8.10} \stddev{1.24} & \textbf{9.16} \stddev{1.28} & \textbf{8.63} \\ \hline \end{tabular} \vspace{0.2cm} \caption{Placing an object unseen during training, with user scores for tidiness shown.} \label{tab:exp-unseen-obj} \end{table} \vspace{-0.2cm} \textbf{Can NeatNet Predict a Personalised Arrangement for a New Scene?} (Table \ref{tab:exp-new-scene}) At training time, the network is shown how the user has arranged both abstract scenes, with random scene masking applied to encourage generalisation. At test time, the network is shown one abstract scene and asked to predict how the test user would arrange the other. \texttt{kNN-Scene-Projection} produces personalised arrangements, but \texttt{NeatNet} lines up objects more neatly because it combines personalisation with learned prior knowledge about these objects from training users. The \texttt{Random-User} baseline performs moderately well, especially when by luck the random training user which was chosen has similar preferences to the test user. However, when those preferences differ, the neural network method out-performs it. This shows the importance of accounting for preferences, and demonstrates that the network can learn preferences which enable generalisation across scenes. \begin{table}[H] \centering \begin{tabular}{|c|c|c|c|} \hline Tidying Method & Abstract 1 & Abstract 2 & Average \\ \hline \texttt{Mean-Position} & 2.04 \stddev{1.05} & 2.30 \stddev{0.97} & 2.17 \\ \hline \texttt{Random-User} & 5.52 \stddev{1.12} & 6.24 \stddev{1.67} & 5.88 \\ \hline \texttt{kNN-Scene-Projection} & 6.56 \stddev{0.96} & 7.32 \stddev{1.48} & 6.94 \\ \hline \texttt{NeatNet} & \textbf{9.58} \stddev{0.53} & \textbf{9.72} \stddev{0.44} & \textbf{9.65} \\ \hline \end{tabular} \vspace{0.2cm} \caption{User scores for predicted arrangements of a new scene.} \label{tab:exp-new-scene} \end{table} \vspace{-0.5cm} \section{Conclusions} \textbf{Findings.} Our NeatNet architecture learned latent representations of user spatial preferences by training as a Variational Autoencoder. Graph Neural Network components allowed it to learn directly from user-arranged scenes, represented as graphs, and word embeddings enabled predictions for unseen objects. NeatNet's ability to generalise and make personalised predictions was demonstrated through experiments with real users, adding new capabilities to existing methods. ~~~~~~~~~~~~~~~~~~~\textbf{Future work.} Rather than using the word embedding of the object's name, convolutional layers can be used to generate a semantic embedding for an object based on its visual appearance (e.g. teacups look similar to mugs and are placed similarly). Furthermore, we can combine our approach with model-based priors from existing methods, e.g. using human pose context \cite{jiang-human-context} as part of our loss function to ensure objects are placed conveniently, while also tailoring to individual preferences. \clearpage \acknowledgments{This work was supported by the Royal Academy of Engineering under the Research Fellowship scheme.}
{'timestamp': '2021-11-08T02:02:37', 'yymm': '2111', 'arxiv_id': '2111.03112', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03112'}
arxiv
\section{Introduction} Knowledge Graph Embeddings (KGE) are the state-of-art models for relational learning on large scale Knowledge Graphs (KG). They drive enterprise products ranging from search engines to social networks to e-commerce \citep{noy2019knowledgegraphs}. However, the analysis of their security vulnerabilities has received little attention. Identifying these vulnerabilities is especially important for high-stake domains like healthcare and finance that employ KGE models to make critical decisions \citep{hogan2020knowledgegraphs, bendsten2019astrazeneca}. We study the security vulnerabilities of KGE models through data poisoning attacks \citep{biggio2018wild,joseph_nelson_rubinstein_tygar_2019} that aim to degrade the predictive performance of learned KGE models by adding or removing triples to the input training graph. \captionsetup[figure]{font=small} \begin{figure}[] \centering \begin{subfigure}[htb]{1\columnwidth} \includegraphics[width=1\columnwidth]{AdversarialDiagram.pdf} \end{subfigure} \caption{Adversarial attacks against KGE models for fraud detection. The knowledge graph consists of two types of entities - Person and BankAccount. The missing target triple to predict is $(Sam, \mathtt{allied\_with}, Joe)$. Original KGE model predicts this triple as True. But a malicious attacker uses the instance attribution methods to either (a) delete an adversarial triple or (b) add an adversarial triple. Now, the KGE model predicts the missing target triple as False. } \label{fig:example} \end{figure} Designing data poisoning attacks against KGE models poses two main challenges. First, to select adversarial deletions or additions, we need to measure the impact of a candidate perturbation on the model's predictions. But the naive approach of re-training a new KGE model for each candidate perturbation is computationally prohibitive. Second, while the search space for adversarial \emph{deletions} is limited to existing triples in the KG, it is computationally intractable to enumerate through all candidate adversarial \emph{additions}. Furthermore, attack strategies proposed against models for other graph modalities \citep{xu2020advgraphsurvey} do not scale to KGE models; as they would require gradients with respect to a dense adjacency tensor of the KG. In this work, we propose to use the model-agnostic \emph{instance attribution methods} from Interpretable Machine Learning \citep{molnar2019interpretablemlbook} to select adversarial deletions and additions against KGE models. Instance attribution methods identify the training instances that are \emph{influential} to model predictions, that is, deleting the instances from the training data would considerably change the model parameters or predictions. These methods are widely used to generate post-hoc example-based explanations for deep neural networks on images \citep{koh2017understanding, hanawa2021evaluationsimilaritymetrics, charpiat2019inputsimilarity} and text \citep{han2020influencenlp, han2020influenceveiledtoxicity, pezeshkpour2021instanceattribution}. Since the KGE models have relatively shallow neural architectures and the instance attribution metrics are independent of the black-box models and the input domain, they are a promising approach to estimate the influence of training triples on the KGE model predictions. Yet, despite their promise, they have not been used on KGE models so far. We use the instance attribution methods to address the challenge of measuring the impact of a candidate adversarial deletion on the model predictions. We focus on the adversarial goal of \emph{degrading} the KGE model prediction on a given \emph{target triple}. To achieve this goal, we use three types of instance attribution methods - Instance Similarity that compares the feature representations of target and training triples \citep{hanawa2021evaluationsimilaritymetrics, charpiat2019inputsimilarity}; Gradient Similarity that compares the gradients of model's loss function due to target and training triples \citep{hanawa2021evaluationsimilaritymetrics,charpiat2019inputsimilarity}; and Influence Function \citep{koh2017understanding} which is a principled approach from the robust statistics to estimate the effect of removing a training triple on the KGE model's predictions. Using these metrics, we select the most influential training triple for adversarial deletion. Using the influential triple, we further select adversarial addition by replacing one of the two entities of the influential triple with the most dissimilar entity in the embedding space. The intuition behind this step is to add a triple that would reduce the influence of the influential triple. This solution also overcomes the scalability challenge for adversarial additions by comparing only the entity embeddings to select the replacement. Figure \ref{fig:example} shows an example of the proposed adversarial deletions and additions against KGE models for fraud detection. We evaluate the proposed attacks for four KGE models - DistMult, ComplEx, ConvE and TransE on two benchmark datasets - WN18RR and FB15k-237. Our results show that instance attribution metrics achieve significantly better performance than \emph{all} state-of-art attacks for both adversarial additions and deletions on three out of four models; and better or equivalent performance on one model. We find that even simple metrics based on instance similarity outperform the state-of-the-art poisoning attacks and are as effective as the computationally expensive Influence Function. Thus, the main contribution of our research is a collection of effective adversarial deletion and addition strategies based on instance attribution methods against KGE models. \section{Knowledge Graph Embeddings} A Knowledge Graph (KG), is a set of triples \( \mathcal{T} \subseteq \mathcal{E} \times \mathcal{R} \times \mathcal{E} \) where each triple encodes the relationship $\mathtt{r}$ as a typed link between the subject entity $s$ and the object entity $o$, i.e. \( \mathcal{T} \coloneqq \{t \coloneqq (s,\mathtt{r},o) \, |\, s,o \in \mathcal{E} \, and \, \mathtt{r} \in \mathcal{R} \} \). Here, \( \mathcal{E} \) is the set of entities and \( \mathcal{R} \) is the set of relations in the knowledge graph. Large scale KGs are often curated automatically from the user content or from the Web and thus are incomplete in practice. To predict the missing links in a KG, the state-of-art method is to learn low dimensional feature vectors for entities and relations in the graph and use them to score the links. These feature vectors are called Knowledge Graph Embeddings (KGE) and denoted as \( \ensuremath{ \bm{ \theta }} \coloneqq \{ \mat{E}, \mat{R}\} \) where \( \mat{E} \in \mathbb{R}^{k}\) is the embedding matrix for entities, \( \mat{R} \in \mathbb{R}^{k}\) is the embedding matrix for relations and $k$ is the embedding dimension. \paragraph{Scoring Functions:} KGE models differ from each other by their scoring functions \(f : \mathcal{T} \rightarrow \mathbb{R} \) which combine the subject, relation and object embeddings to assign a score to the triple, i.e. \(f_{t} \coloneqq f(\vec{e}_s, \vec{e}_\mathtt{r}, \vec{e}_o) \) where \(\vec{e}_s, \vec{e}_o \in \mat{E}\) and \(\vec{e}_\mathtt{r} \in \mat{R}\). Table \ref{tab:scoring_functions} shows the different scoring functions of KGE models used in this research. These scoring functions are used to categorize the models as additive or multiplicative \cite{chandrahas2018towards}. \emph{Additive} models apply relation-specific translation from the subject embedding to the object embedding. The scoring function for such models is expressed as $f_{t} = -\norm{\mat{M}_{\mathtt{r}}^1(\vec{e}_s) + \vec{e}_\mathtt{r} - \mat{M}_{\mathtt{r}}^2(\vec{e}_o)}$ where $\mat{M}_\mathtt{r} \in \mathbb{R}^{k \times k}$ is a projection matrix from entity space to relation space. An example of additive models is TransE where $\mat{M}_{\mathtt{r}}^1 = \mat{M}_{\mathtt{r}}^2 = \mat{I}$. On the other hand, \emph{multiplicative} models score triples through multiplicative interactions between the subject, relation and object embeddings. The scoring function for these models is expressed as $f_{t} = \vec{e}_{\mathtt{r}}^\top \mathcal{F}(\vec{e}_s, \vec{e}_o)$ where the function $\mathcal{F}$ measures the compatibility between the subject and object embeddings and varies across different models within this family. DistMult, ComplEx and ConvE are examples of multiplicative models. \begin{table}[] \centering \small \begin{tabular}{c c c} \toprule \textbf{Model} & \multicolumn{1}{p{2.5cm}}{\centering \bf Scoring Function} & \multicolumn{1}{p{2.5cm}}{\centering \bf Feature Vectors} \\ \midrule DistMult & $ \tdot{\vec{e}_s}{\vec{e}_{\mathtt{r}}}{\vec{e}_o}$ & $ \vec{e}_s \circ \vec{e}_{\mathtt{r}} \circ \vec{e}_o$ \\ [2pt] ComplEx & $ \Re(\tdot{\vec{e}_s}{\vec{e}_{\mathtt{r}}}{\overline{\vec{e}_o}})$ & $ \Re(\vec{e}_s \circ \vec{e}_{\mathtt{r}} \circ \overline{\vec{e}_o})$ \\ [2pt] ConvE & $ \langle (\vec{e}_s * \vec{e}_{\mathtt{r}}), \vec{e}_o \rangle$ & $ (\vec{e}_s * \vec{e}_{\mathtt{r}}) \circ \vec{e}_o $ \\ [2pt] TransE & $- \norm{\vec{e}_s + \vec{e}_{\mathtt{r}} - \vec{e}_o}_p$ & $- (\vec{e}_s + \vec{e}_{\mathtt{r}} - \vec{e}_o)$ \\ [2pt] \bottomrule \end{tabular} \caption{Scoring functions \(f_{s\mathtt{r}o}\) and the proposed Triple Feature Vectors \(\vec{f}_{s\mathtt{r}o}\) of the KGE models used in this research. For ComplEx, $\vec{e}_s, \vec{e}_\mathtt{r}, \vec{e}_o \in \mathbb{C}^k$; for the remaining models $\vec{e}_s, \vec{e}_\mathtt{r}, \vec{e}_o \in \mathbb{R}^k$. Here, $\langle \cdot \rangle$ denotes the tri-linear dot product; $\circ$ denotes the element-wise Hadamard product; $\overline{\ \cdot\ }$ denotes conjugate for complex vectors; $\norm{\cdot}_p$ denotes l-p norm; $*$ is the neural architecture in ConvE, i.e. \(\vec{e}_s * \vec{e}_\mathtt{r} \coloneqq \sigma(\mathrm{vec}(\sigma([ \overline{\vec{e}_\mathtt{r}}, \overline{\vec{e}_s}] \ast \boldsymbol{\Omega})) \mat{W})\) where $\sigma$ denotes sigmoid activation, $\ast$ denotes 2D convolution; $\overline{\ \cdot\ }$ denotes 2D reshaping of real vectors.} \label{tab:scoring_functions} \end{table} \paragraph{Training:} Since the KGs only contain positive triples; to train the KGE model, synthetic negative samples \(t' \in \mathcal{T}'\) are generated by replacing the subject or object in the positive triples with other entities in $\mathcal{E}$. That is, for each positive triple $t \coloneqq (s,\mathtt{r},o)$, the set of negative samples is $ t' \coloneqq \{(s',\mathtt{r},o) \cup (s,\mathtt{r},o')\}$. The training objective is to learn the embeddings that score positive triples existing in the KG higher than the negative triples generated synthetically. To achieve this, a triple-wise loss function \( \mathcal{L}(t,\ensuremath{ \bm{ \theta }}) \coloneqq \ell(t,\ensuremath{ \bm{ \theta }}) + \sum_{t' \in \mathcal{T}'} \ell(t', \ensuremath{ \bm{ \theta }}) \) is minimized. Thus, the optimal parameters \(\widehat \ensuremath{ \bm{ \theta }}\) learned by the model are defined by \( \widehat{\ensuremath{ \bm{ \theta }}} \coloneqq \argmin_{\ensuremath{ \bm{ \theta }}} \sum_{t \in \mathcal{T}} \mathcal{L}(t, \ensuremath{ \bm{ \theta }}) \). Further details on KGE loss functions and negative sampling strategies are available in \citet{ruffinelli2020olddognewtricks}. \paragraph{Missing Link Prediction: } Given the learned embeddings \(\ensuremath{ \bm{ \theta }}\), missing triples in the knowledge graph are predicted by an entity ranking evaluation protocol. Similar to the training process, subject-side negatives $t_s'={(s',\mathtt{r},o)}$ and object-side negatives $t_o'={(s,\mathtt{r},o')}$ are sampled for each test triple $t=(s,\mathtt{r},o)$ to be predicted. Of these negatives, the triples already existing in the training, validation or test set are filtered out \citep{bordes2013transe}. The test triple is then ranked against the remaining negatives based on the scores predicted by the KGE model. The state-of-art evaluation metrics reported over the entire set are (i) \emph{MR}: mean of the ranks, (ii) \emph{MRR}: mean of the reciprocals of ranks and (iii) \emph{Hits@n}: number of triples ranked in top-n. \section{Poisoning Knowledge Graph Embeddings via Instance Attribution} \label{sec:poisoning} We consider an adversarial attacker that aims to degrade the KGE model's predictive performance on a set of missing triples that have been ranked highly plausible by the model. We denote these \emph{target triples} as \(\mathcal{Z} \coloneqq \{z \coloneqq (z_s, z_\mathtt{r}, z_o)\}\). Since the predicted ranks are based on the predicted scores; to reduce the predicted rank of a target triple, we craft perturbations to the training data that aim to reduce the predicted score of the target triple. \paragraph{Threat Model:}We use the same threat model as the state-of-art poisoning attacks on KGE models \citep{pezeshkpour2019criage, zhang2019kgeattack}. We focus on the white-box attack setting where the attacker has full knowledge of the victim model architecture and access to the learned embeddings. However, they cannot perturb the architecture or the embeddings directly; but only through perturbations in the training data. We study both \emph{adversarial additions} and \emph{adversarial deletions}. In both settings, the attacker is restricted to making only one edit in the neighbourhood of the target triple. The neighbourhood of the target triple $z \coloneqq (z_s,z_\mathtt{r},z_o)$ is the set of triples that have the same subject or the same object as the target triple, i.e. $\mathcal{X}:= \{x \coloneqq (x_s, x_\mathtt{r}, x_o)\, |\, x_s \in \{z_s, z_o\} \vee x_o \in \{z_s, z_o\}\}$. \subsection{Instance Attribution Methods} For adversarial deletions, we want to identify the training triples that have influenced the KGE model's prediction on the target triple. Deleting these influential triples from the training set will likely degrade the prediction on the target triple. Thus, we define an \emph{influence score} \(\phi (z,x) : \mathcal{T} \times \mathcal{T} \rightarrow \mathbb{R} \) for the pairs of triples \((z,x) \in \mathcal{T} \times \mathcal{T}\) which indicates the influence of training triple $x$ on the prediction of target triple $z$. Larger values of the influence score \(\phi (z,x)\) indicate that removing $x$ from the training data would cause larger reduction in the predicted score on $z$. Trivially, we can compute the influence score for a training triple by removing the triple and re-training the KGE model. However, this is a prohibitively expensive step that requires re-training a new KGE model for every candidate influential triple. Thus, we use the following instance-attribution methods from Interpretable Machine Learning \citep{molnar2019interpretablemlbook} to estimate the influence score \(\phi (z,x)\) without re-training the model. \subsubsection{Instance Similarity} We estimate the influence of training triple $x$ on the prediction of target triple $z$ based on the similarity of their feature representations. The intuition behind these metrics is to identify the training triples that a KGE model has learnt to be similar to the target triple and thus (might) have influenced the model's prediction on the target triple. Computing this similarity between triples requires feature vector representations for the triples. We note that while the standard KGE scoring functions assign a scalar score to the triples, this scalar value is obtained by reducing over the embedding dimension. For example, in the tri-linear dot product for DistMult, the embeddings of subject, relation and object are multiplied element-wise and then the scalar score for the triple is obtained by summing over the embedding dimension, i.e. $f_t \coloneqq \langle \vec{e}_s, \vec{e}_\mathtt{r}, \vec{e}_o\rangle \coloneqq \sum_{i=1}^k \vec{e}_{s_i} \vec{e}_{\mathtt{r}_i} \vec{e}_{o_i}$ where $k$ is the embedding dimension. Thus, to obtain feature vector representations for the triples \(\vec{f}_t : \mathcal{E} \times \mathcal{R} \times \mathcal{E} \rightarrow \mathbb{R}^k \), we use the state-of-art KGE scoring functions without reduction over the embedding dimension. For the DistMult model, the triple feature vector is \(\vec{f} \coloneqq \vec{e}_s \circ \vec{e}_\mathtt{r} \circ \vec{e}_o\) where $\circ$ is the Hadamard (element-wise) product. Table \ref{tab:scoring_functions} shows the feature vector scores for different KGE models used in this research. Given the feature vectors for target triples $\vec{f}(z)$ and training triples $\vec{f}(x)$, we follow \citet{hanawa2021evaluationsimilaritymetrics} and define the following metrics. \textbf{Dot Metric:} This metric computes the similarity between target and training instances as the dot product of their feature vectors. That is, \( \phi_{dot} (z,x) \coloneqq \langle \vec{f}(z), \vec{f}(x) \rangle \) \textbf{$\bm{\ell_2}$ Metric: } This metric computes similarity as the negative Euclidean distance between the feature vectors of target instance and test instance. That is, \( \phi_{\ell_2} (z,x) \coloneqq - \norm{\vec{f}(z) - \vec{f}(x)}_2 \) \textbf{Cosine Metric:} This metric computes similarity as the dot product between $\bm{\ell_2}$ normalized feature vectors of target and test instance, i.e. it ignores the magnitude of the vectors and only relies on the angle between them. That is, \break \( \phi_{cos} (z,x) \coloneqq \cos{(\vec{f}(z), \vec{f}(x))} \) Here, we denote the dot product for two vectors $\vec{a}$ and $\vec{b}$ as $\langle \vec{a}, \vec{b} \rangle \coloneqq \sum_{i=1}^p a_i b_i$; the $\bm{\ell_2}$ norm of a vector as $\norm{\vec{a}}_2 \coloneqq \sqrt{\langle \vec{a}, \vec{a} \rangle}$; and the cos similarity between vectors $\vec{a}$ and $\vec{b}$ as \break $\cos(\vec{a}, \vec{b}) \coloneqq \nicefrac{\langle \vec{a}, \vec{b} \rangle}{\norm{\vec{a}}_2 \norm{\vec{b}}_2}$. \subsubsection{Gradient Similarity} We represent the gradient of the loss for triple $z$ w.r.t. model parameters as \(\vec{g}(z, \widehat{\ensuremath{ \bm{ \theta }}}) := \nabla_{\ensuremath{ \bm{ \theta }}}{\mathcal{L} (z,\widehat{\ensuremath{ \bm{ \theta }})}} \). Gradient similarity metrics compute similarity between the gradients due to target triple $z$ and the gradients due to training triple $x$. The intuition is to assign higher influence to training triples that have similar effect on the model's parameters as the target triple; and are therefore likely to impact the prediction on target triple \citep{charpiat2019inputsimilarity}. Thus, using the same similarity functions as Instance Similarity metrics, we define the following three metrics for gradient similarity - Gradient Dot (GD), Gradient $\bm{\ell_2}$ (GL) and Gradient Cosine (GC). \paragraph{GD(dot): } \(\phi_{\mathrm{GD}} (z,x) \coloneqq \langle \, \vec{g}(z, \widehat{\ensuremath{ \bm{ \theta }}})\, , \, \vec{g}(x, \widehat{\ensuremath{ \bm{ \theta }}}) \, \rangle \) \paragraph{GL ($\bm{\ell_2}$):} \(\phi_{\mathrm{GL}} (z,x) \coloneqq - \norm{\vec{g}(z, \widehat{\ensuremath{ \bm{ \theta }}}) - \vec{g}(x, \widehat{\ensuremath{ \bm{ \theta }}})}_2 \) \paragraph{GC(cos):} \(\phi_{\mathrm{GC}} (z,x) \coloneqq \cos{( \, \vec{g}(z, \widehat{\ensuremath{ \bm{ \theta }}}) \, , \, \vec{g}(x, \widehat{\ensuremath{ \bm{ \theta }}}) \, )} \) \subsubsection{Influence Functions} Influence Functions (IF) is a classic technique from robust statistics and was introduced to explain the predictions of black-box models in \citet{koh2017understanding}. To estimate the effect of a training point on a model's predictions, it first approximates the effect of removing the training point on the learned model parameters. To do this, it performs a first order Taylor expansion around the learned parameters $\widehat{\ensuremath{ \bm{ \theta }}}$ at the optimality conditions. Following the derivation in \citet{koh2017understanding}, the the effect of removing the training triple $x$ on $\widehat{\ensuremath{ \bm{ \theta }}}$ is given by \( \nicefrac{d\widehat{\ensuremath{ \bm{ \theta }}}}{d\epsilon_i} = \mat{H}_{\widehat{\ensuremath{ \bm{ \theta }}}}^{-1} \ \vec{g}(x, \widehat{\ensuremath{ \bm{ \theta }}}) \). Here, $\mat{H}_{\widehat{\ensuremath{ \bm{ \theta }}}}$ denotes the Hessian of the loss function \( \mat{H}_{\widehat{\ensuremath{ \bm{ \theta }}}} \coloneqq \nicefrac{1}{n} \sum_{t \in \mathcal{T}} \nabla_{\ensuremath{ \bm{ \theta }}}^{2}{\mathcal{L} (t, \widehat{\ensuremath{ \bm{ \theta }}})} \). Using the chain rule then, we approximate the influence of removing $x$ on the model's prediction at $z$ as $\langle \vec{g} (z,\widehat{\ensuremath{ \bm{ \theta }}}) \ , \nicefrac{d\widehat{\ensuremath{ \bm{ \theta }}}}{d\epsilon_i} \rangle$. Thus, the influence score using IF is defined as: \textbf{IF: } \, \(\phi_{\mathrm{IF}} (z,x) := \langle \, \vec{g}(z, \widehat{\ensuremath{ \bm{ \theta }}}) \, , \, \mat{H}_{\widehat{\ensuremath{ \bm{ \theta }}}}^{-1} \vec{g}(x, \widehat{\ensuremath{ \bm{ \theta }}}) \, \rangle \) Computing the IF for KGE models poses two challenges - (i) storing and inverting the Hessian matrix is computationally too expensive for a large number of parameters; (ii) the Hessian is not guaranteed to be positive definite and thus, invertible because KGE models are non-convex models. To address both these challenges, we follow the guidelines in \citet{koh2017understanding}. Instead of computing the exact Hessian matrix, we estimate the Hessian-vector product (HVP) with target triple's gradient. That is, for every target triple $z$, we pre-compute the value \( \mat{H}_{\widehat{\ensuremath{ \bm{ \theta }}}}^{-1} \ \vec{g} (z, \widehat{\ensuremath{ \bm{ \theta }}}) \). Then, for each neighbourhood triple $x$ in the training set, we compute $\phi_{\mathrm{IF}} (z,x)$ using the pre-computed HVP. Furthermore, we use the stochastic estimator LiSSA \citep{agarwal2017lissa} that computes the HVP in linear time using samples from training data. For the second issue of non-convexity, we add a "damping" term to the Hessian so that it is positive definite and invertible. This term is a hyperparameter that is tuned to ensure that all eigenvalues of the Hessian matrix are positive, i.e. the Hessian matrix is positive definite. Further discussion on the validity of Influence Functions for non-convex settings is available in \citet{koh2017understanding}. \subsection{Adversarial Additions} In this attack setting, the adversarial attacker can only \emph{add} triples to the neighbourhood of target triple. Using the Instance Attribution metrics above, we select the training triple $x := (x_s, x_\mathtt{r}, x_o)$ in the neighbourhood of the target triple $z := (z_s, z_\mathtt{r}, z_o)$ that is most influential to the prediction of $z$. For brevity, lets assume $x_s = z_s$, i.e. the influential and target triples have the same subject. To generate adversarial addition using the influential triple, we propose to replace $x_o$ with the most dissimilar entity $x_{o'}$. Since the adversarial triple $x' := (x_s, x_\mathtt{r}, x_{o'})$ has the same subject and relation as the influential triple but a different object, it should reduce the influence of the influential triple on the target triple's prediction. This in turn should degrade the model prediction on target triple. For multiplicative models, we select the dissimilar entity $x_{o'}$ using the cosine similarity between $x_o$ and the entities $\mathcal{E}$. For additive models, we use the $\bm{\ell_2}$ similarity between $x_o$ and the entities $\mathcal{E}$. \section{Evaluation} \label{sec:evaluation} We evaluate the effectiveness of the proposed attack strategies in degrading the KGE model's predictions on target triples at test time. We follow the state-of-art protocol to evaluate poisoning attacks \citep{xu2020advgraphsurvey} - we train a victim KGE model on the original dataset; generate adversarial deletions or additions using one of the attacks; perturb the original dataset; and train a new KGE model on the perturbed dataset. The hyperparameters for victim and poisoned KGE models are same. We evaluate our attacks on four state-of-art KGE models - DistMult, ComplEx, ConvE and TransE on two publicly available\footnote{https://github.com/TimDettmers/ConvE} benchmark datasets - WN18RR and FB15k-237. To be able to evaluate the effectiveness of attacks in \emph{degrading} the predictive performance, we select a subset of the benchmark test triples that has been ranked \emph{highest} (ranks=1) by the victim KGE model. From this subset, we randomly sample 100 triples as the \emph{target triples}. This is to avoid the expensive Hessian inverse estimation in the IF metric for a large number of target triples (for each target triple, this estimation requires one training epoch). The source code implementation of our experiments is available at \url{https://github.com/PeruBhardwaj/AttributionAttack}. \paragraph{Baselines: } We evaluate our attacks against baseline methods based on random edits and the state-of-art poisoning attacks. \emph{Random\_n} adds or removes a random triple from the neighbourhood of the target triple. \emph{Random\_g} adds or removes a random triple globally and is not restricted to the target's neighbourhood. \emph{Direct-Del} and \emph{Direct-Add} are the adversarial deletion and addition attacks proposed in \citet{zhang2019kgeattack}. \emph{CRIAGE} is the poisoning attack from \citet{pezeshkpour2019criage} and is a baseline for both deletions and additions. \emph{GR} (Gradient Rollback) \citep{lawrence2021gradientrollback} uses influence estimation to provide post-hoc explanations for KGE models and can also be used to generate adversarial deletions. Thus, we include this method as a baseline for adversarial deletions. The attack evaluations in \citet{zhang2019kgeattack, pezeshkpour2019criage, lawrence2021gradientrollback} differ with respect to the definition of their \emph{neighbourhood}. Thus, to ensure fair evaluation, we implement all methods with the same neighbourhood - triples that are linked to the subject or object of the target triple (Section \ref{sec:poisoning}). We use the publicly available implementations for CRIAGE\footnote{https://github.com/pouyapez/criage} and Gradient Rollback\footnote{https://github.com/carolinlawrence/gradient-rollback} and implement Direct-Del and Direct-Add ourselves. Further details on datasets, implementation of KGE models, baselines and computing resources is available in Appendix \ref{apx:dataset_details} and \ref{apx:training_details}. \begin{table*} \centering \footnotesize \setlength{\tabcolsep}{3.5pt} \begin{tabular}{c l ll ll ll ll } \toprule & & \multicolumn{2}{c}{\textbf{DistMult}} & \multicolumn{2}{c}{\textbf{ComplEx}} & \multicolumn{2}{c}{\textbf{ConvE}} & \multicolumn{2}{c}{\textbf{TransE}} \\ \cmidrule(lr){3-4} \cmidrule(lr){5-6} \cmidrule(lr){7-8} \cmidrule(lr){9-10} & & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} \\ \midrule \textbf{Original} & & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 \\ \midrule \multirow{6}{*}{\shortstack[l]{\textbf{Baseline} \\ \textbf{Attacks}}} & Random\_n & 0.87 (-13\%) & 0.82 & 0.85 (-15\%) & 0.80 & 0.82 (-18\%) & 0.79 & 0.82 (-18\%) & 0.70 \\ & Random\_g & 0.97 & 0.95 & 0.96 & 0.93 & 0.99 & 0.98 & 0.93 & 0.87 \\ \cline{2-10} \\[-7pt] & Direct-Del & 0.88 & 0.77 & 0.86 (-14\%) & 0.77 & 0.71 (-29\%) & 0.64 & 0.54 \textbf{(-46\%)} & 0.37 \\ & CRIAGE & 0.73 (-27\%) & 0.66 & - & - & Er & Er & - & - \\ & GR & 0.95 & 0.90 & 0.93 & 0.86 & 0.95 & 0.91 & 0.84 & 0.77 \\ \midrule \multirow{9}{*}{\shortstack[l]{\textbf{Proposed} \\ \textbf{Attacks}}} & Dot Metric & 0.89 & 0.82 & 0.85 & 0.79 & 0.84 (-16\%) & 0.80 & 0.77 & 0.60 \\ & $\bm{\ell_2}$ Metric & \textbf{0.25 (-75\%)} & 0.16 & 0.29 (-71\%) & 0.20 & 0.88 & 0.78 & 0.62 & 0.50 \\ & Cos Metric & \textbf{0.25 (-75\%)} & 0.16 & 0.29 (-71\%) & 0.20 & 0.87 & 0.76 & 0.56 (-44\%) & 0.40 \\ \cline{2-10} \\[-7pt] & GD (dot) & 0.28 (-72\%) & 0.19 & 0.29 & 0.21 & 0.25 & 0.21 & 0.71 (-29\%) & 0.57 \\ & GL ($\bm{\ell_2}$) & 0.30 & 0.20 & 0.28 \textbf{(-72\%)} & 0.19 & 0.17 \textbf{(-83\%)} & 0.12 & 0.72 & 0.60 \\ & GC (cos) & 0.29 & 0.19 & 0.29 & 0.21 & 0.20 & 0.16 & 0.71 (-29\%) & 0.57 \\ \cline{2-10} \\[-7pt] & IF & 0.28 (-72\%) & 0.19 & 0.29 (-71\%) & 0.20 & 0.22 (-78\%) & 0.17 & 0.71 (-29\%) & 0.57 \\ \bottomrule \end{tabular} \caption{\small Reduction in MRR and Hits@1 due to \textbf{adversarial deletions on target triples in WN18RR}. Lower values indicate better results; best results for each model are in bold. First block of rows are the baseline attacks with random edits; second block is state-of-art attacks; remaining are the proposed attacks. For each block, we report the \emph{best} reduction in percentage relative to the original MRR; computed as $(poisoned - original)/original*100$. } \label{tab:deletion_WN18RR} \end{table*} \paragraph{Results:} For WN18RR and FB15k-237 respectively, Tables \ref{tab:deletion_WN18RR} and \ref{tab:deletion_FB15k-237} show the degradation in MRR and Hits@1 due to adversarial deletions; and Tables \ref{tab:addition_WN18RR} and \ref{tab:addition_FB15k-237} due to adversarial additions for state-of-art KGE models. Below we discuss different patterns in these results. We also discuss runtime efficiency of the attack methods in Appendix \ref{apx:runtime_analysis}. \subsection{Comparison with Baselines} \label{sec:eval_baseline} We observe that the proposed strategies for adversarial deletions and adversarial additions successfully degrade the predictive performance of KGE models. On the other hand, the state-of-art attacks are ineffective or only partially effective. Adversarial deletions from Gradient Rollback perform similar to random baselines; likely because this method estimates the influence of a training triple as the sum of its gradients over the training process. In this way, it does not account for the target triple in the influence estimation. The method is also likely to be effective only for a KGE model that is trained with a batch size of 1 because it needs to track the gradient updates for each triple. The CRIAGE baseline is only applicable to DistMult and ConvE. But we found that the method ran into \texttt{\small numpy.linalg.LinAlgError: Singular matrix} error for ConvE; because the Hessian matrix computed from the victim model embeddings was non-invertible\footnote{This issue might be resolved by changing the hyperparameters of the victim KGE model so that the Hessian matrix from the victim embeddings is invertible. But there is no strategic way to make such changes.}. For adversarial deletions on DistMult, the baseline works better than random edits but not the proposed attacks \footnote{Since the influence estimation in CRIAGE uses BCE loss, we also compare for DistMult trained with BCE in Appendix \ref{apx:criage_bce}, but the results are similar.}. It is also ineffective against adversarial additions. We see that Direct-Del is effective on TransE, but not on multiplicative models. This is likely because it estimates the influence of a candidate triple as the \emph{difference} in the triple's score when the neighbour entity embedding is perturbed. The additive nature of this influence score might make it more suitable for additive models. We also see that Direct-Add works similar to random additions, likely because it uses random down-sampling. The proposed attacks based on instance attribution methods consistently outperform random baselines for adversarial additions and deletions. One exception to this pattern are adversarial additions against TransE on WN18RR. In this case, no influence metric performs better than random neighbourhood edits, though they are all effective for adversarial deletions. One possible reason is that the TransE model is designed to learn hierarchical relations like $\mathtt{\_has\_part}$. We found that the target triples ranked highest by the model have such hierarchical relations; and the influential triple for them has the same relation. That is, the triple $(s_1, \mathtt{\_has\_part}, s)$ is the influential triple for $(s, \mathtt{\_has\_part}, o)$. Removing this influential triple breaks the hierarchical link between $s_1$ and $s$; and degrades TransE predictions on the target. But adding the triple $(s_2, \mathtt{\_has\_part}, s)$ still preserves the hierarchical structure which TransE can use to score the target correctly. We provide more examples of such relations in Appendix \ref{apx:wn18rr_transe}. \subsection{Comparison across Influence Metrics } \label{sec:eval_if} We see that the IF and Gradient Similarity metrics show similar degradation in predictive performance. This indicates that the computationally expensive Hessian inverse in the IF can be avoided and simpler metrics can identify influential triples with comparable effectiveness. Furthermore, cos and $\bm{\ell_2}$ based Instance Similarity metrics outperform all other methods for adversarial deletions on DistMult, ComplEx and TransE. This effectiveness of naive metrics indicates the high vulnerability of shallow KGE architectures to data poisoning attacks in practice. In contrast to this, the Input Similarity metrics are less effective in poisoning ConvE, especially significantly on WN18RR. This is likely because the triple feature vectors for ConvE are based on the output from a deeper neural architecture than the Embedding layer alone. Within Instance Similarity metrics, we see that the dot metric is not as effective as others. This could be because the dot product does not normalize the triple feature vectors. Thus, training triples with large norms are prioritized over relevant influential triples \citep{hanawa2021evaluationsimilaritymetrics}. \subsection{Comparison of datasets} \label{sec:eval_data} We note that the degradation in predictive performance is more significant on WN18RR than on FB15k-237. This is likely due to the sparser graph structure of WN18RR, i.e. there are fewer neighbours per target triple in WN18RR than in FB15k-237 (Appendix \ref{apx:neighbourhood_sparsity}). Thus, the model learns its predictions from few influential triples in WN18RR; and removing only one neighbour significantly degrades the model's predictions on the target triple. On the other hand, because of more neighbours in FB15k-237, the model predictions are likely influenced by a \emph{group} of training triples. Such group effect of training instances on model parameters has been studied in \citet{koh2019groupinfluence, basu2020groupinfluence}. We will investigate these methods for \emph{KGE models} on FB15k-237 in the future. \begin{table*} \centering \footnotesize \setlength{\tabcolsep}{3.5pt} \begin{tabular}{c l ll ll ll ll } \toprule & & \multicolumn{2}{c}{\textbf{DistMult}} & \multicolumn{2}{c}{\textbf{ComplEx}} & \multicolumn{2}{c}{\textbf{ConvE}} & \multicolumn{2}{c}{\textbf{TransE}} \\ \cmidrule(lr){3-4} \cmidrule(lr){5-6} \cmidrule(lr){7-8} \cmidrule(lr){9-10} & & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} \\ \midrule \textbf{Original} & & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 \\ \midrule \multirow{6}{*}{\shortstack[l]{\textbf{Baseline} \\ \textbf{Attacks}}} & Random\_n & 0.66 (-34\%) & 0.52 & 0.65 (-35\%) & 0.51 & 0.62 (-38\%) & 0.46 & 0.71 (-29\%) & 0.56 \\ & Random\_g & 0.68 & 0.53 & 0.65 (-35\%) & 0.51 & 0.63 & 0.50 & 0.75 & 0.61 \\ \cline{2-10} \\[-7pt] & Direct-Del & 0.59 (-41\%) & 0.42 & 0.62 (-38\%) & 0.47 & 0.57 (-43\%) & 0.41 & 0.62 \textbf{(-38\%)} & 0.45 \\ & CRIAGE & 0.62 & 0.47 & - & - & Er & Er & - & - \\ & GR & 0.68 & 0.55 & 0.66 & 0.51 & 0.62 & 0.45 & 0.68 & 0.53 \\ \midrule \multirow{9}{*}{\shortstack[l]{\textbf{Proposed} \\ \textbf{Attacks}}} & Dot Metric & 0.63 & 0.47 & 0.64 & 0.49 & 0.60 & 0.44 & 0.74 & 0.62 \\ & $\bm{\ell_2}$ Metric & 0.58 & 0.41 & 0.56 \textbf{(-44\%)} & 0.40 & 0.53 \textbf{(-47\%)} & 0.35 & 0.63 (-37\%) & 0.46 \\ & Cos Metric & 0.56 \textbf{(-44\%)} & 0.39 & 0.57 & 0.40 & 0.55 & 0.38 & 0.63 (-37\%) & 0.45 \\ \cline{2-10} \\[-7pt] & GD (dot) & 0.60 & 0.44 & 0.60 & 0.45 & 0.55 (-45\%) & 0.37 & 0.65 & 0.49 \\ & GL ($\bm{\ell_2}$) & 0.62 & 0.45 & 0.60 & 0.45 & 0.56 & 0.41 & 0.70 & 0.58 \\ & GC (cos) & 0.58 (-42\%) & 0.42 & 0.57 (-43\%) & 0.39 & 0.57 & 0.40 & 0.64 (-36\%) & 0.48 \\ \cline{2-10} \\[-7pt] & IF & 0.60 (-40\%) & 0.44 & 0.60 (-40\%) & 0.45 & 0.58 (-42\%) & 0.43 & 0.66 (-34\%) & 0.52 \\ \bottomrule \end{tabular} \caption{\small Reduction in MRR and Hits@1 due to \textbf{adversarial deletions on target triples in FB15k-237}. Lower values indicate better results. First block of rows are the baseline attacks with random edits; second block is state-of-art attacks; remaining are the proposed attacks. For each block, we report the \emph{best} reduction in percentage relative to the original MRR.} \label{tab:deletion_FB15k-237} \end{table*} \begin{table*} \centering \footnotesize \setlength{\tabcolsep}{3.5pt} \begin{tabular}{c l ll ll ll ll } \toprule & & \multicolumn{2}{c}{\textbf{DistMult}} & \multicolumn{2}{c}{\textbf{ComplEx}} & \multicolumn{2}{c}{\textbf{ConvE}} & \multicolumn{2}{c}{\textbf{TransE}} \\ \cmidrule(lr){3-4} \cmidrule(lr){5-6} \cmidrule(lr){7-8} \cmidrule(lr){9-10} & & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} \\ \midrule \textbf{Original} & & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 \\ \midrule \multirow{5}{*}{\shortstack[l]{\textbf{Baseline} \\ \textbf{Attacks}}} & Random\_n & 0.99 (-1\%) & 0.98 & 0.97 (-3\%) & 0.94 & 0.99 (-1\%) & 0.98 & 0.76 \textbf{(-24\%)} & 0.57 \\ & Random\_g & 0.99 (-1\%) & 0.97 & 0.97 (-3\%) & 0.95 & 0.99 (-1\%) & 0.98 & 0.93 & 0.87 \\ \cline{2-10} \\[-7pt] & Direct-Add & 0.98 (-2\%) & 0.96 & 0.95 (-5\%) & 0.92 & 0.99 (-1\%) & 0.98 & 0.81 (-19\%) & 0.67 \\ & CRIAGE & 0.98 (-2\%) & 0.97 & - & - & Er & Er & - & - \\ \midrule \multirow{9}{*}{\shortstack[l]{\textbf{Proposed} \\ \textbf{Attacks}}} & Dot Metric & 0.97 & 0.93 & 0.95 & 0.90 & 0.95 (-5\%) & 0.91 & 0.95 & 0.90 \\ & $\bm{\ell_2}$ Metric & 0.89 \textbf{(-11\%)} & 0.78 & 0.88 & 0.77 & 0.98 & 0.96 & 0.87 (-13\%) & 0.83 \\ & Cos Metric & 0.89 \textbf{(-11\%)} & 0.78 & 0.87 (-13\%) & 0.77 & 0.99 & 0.98 & 0.87 (-13\%) & 0.83 \\ \cline{2-10} \\[-7pt] & GD (dot) & 0.90 & 0.79 & 0.89 & 0.79 & 0.92 & 0.85 & 0.80 (-20\%) & 0.73 \\ & GL ($\bm{\ell_2}$) & 0.89 \textbf{(-11\%)} & 0.79 & 0.86 \textbf{(-14\%)} & 0.73 & 0.88 \textbf{(-12\%)} & 0.77 & 0.89 & 0.83 \\ & GC (cos) & 0.90 & 0.80 & 0.87 & 0.76 & 0.91 & 0.82 & 0.80 (-20\%) & 0.73 \\ \cline{2-10} \\[-7pt] & IF & 0.90 (-10\%) & 0.79 & 0.89 (-11\%) & 0.79 & 0.91 (-8.9\%) & 0.82 & 0.77 (-23\%) & 0.67 \\ \bottomrule \end{tabular} \caption{\small Reduction in MRR and Hits@1 due to \textbf{adversarial additions on target triples in WN18RR}. Lower values indicate better results. First block of rows are the baseline attacks with random edits; second block is state-of-art attacks; remaining are the proposed attacks. For each block, we report the \emph{best} reduction in percentage relative to the original MRR.} \label{tab:addition_WN18RR} \end{table*} \begin{table*} \centering \footnotesize \setlength{\tabcolsep}{3.5pt} \begin{tabular}{c l ll ll ll ll } \toprule & & \multicolumn{2}{c}{\textbf{DistMult}} & \multicolumn{2}{c}{\textbf{ComplEx}} & \multicolumn{2}{c}{\textbf{ConvE}} & \multicolumn{2}{c}{\textbf{TransE}} \\ \cmidrule(lr){3-4} \cmidrule(lr){5-6} \cmidrule(lr){7-8} \cmidrule(lr){9-10} & & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} & \textbf{MRR} & \textbf{Hits@1} \\ \midrule \textbf{Original} & & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 & 1.00 \\ \midrule \multirow{5}{*}{\shortstack[l]{\textbf{Baseline} \\ \textbf{Attacks}}} & Random\_n & 0.65 (-34\%) & 0.50 & 0.69 & 0.57 & 0.61 (-39\%) & 0.46 & 0.74 & 0.62 \\ & Random\_g & 0.66 & 0.52 & 0.66 (-34\%) & 0.52 & 0.63 & 0.50 & 0.73 (-27\%) & 0.61 \\ \cline{2-10} \\[-7pt] & Direct-Add & 0.64 (-36\%) & 0.48 & 0.66 (-34\%) & 0.52 & 0.60 (-40\%) & 0.45 & 0.72 (-28\%) & 0.59 \\ & CRIAGE & 0.66 & 0.50 & - & - & Er & Er & - & - \\ \midrule \multirow{9}{*}{\shortstack[l]{\textbf{Proposed} \\ \textbf{Attacks}}} & Dot Metric & 0.67 & 0.54 & 0.65 & 0.50 & 0.61 & 0.46 & 0.74 (-26\%) & 0.62 \\ & $\bm{\ell_2}$ Metric & 0.64 & 0.50 & 0.66 & 0.52 & 0.59 (-41\%) & 0.43 & 0.74 (-26\%) & 0.62 \\ & Cos Metric & 0.63 (-37\%) & 0.49 & 0.63 (-37\%) & 0.47 & 0.60 & 0.43 & 0.74 (-26\%) & 0.61 \\ \cline{2-10} \\[-7pt] & GD (dot) & 0.61 \textbf{(-39\%)} & 0.45 & 0.65 & 0.50 & 0.62 & 0.46 & 0.71 \textbf{(-29\%)} & 0.58 \\ & GL ($\ell_2$) & 0.63 & 0.48 & 0.67 & 0.53 & 0.61 (-39\%) & 0.45 & 0.74 & 0.60 \\ & GC (cos) & 0.62 & 0.46 & 0.64 \textbf{(-36\%)} & 0.49 & 0.61 (-39\%) & 0.45 & 0.71 \textbf{(-29\%)} & 0.56 \\ \cline{2-10} \\[-7pt] & IF & 0.61 \textbf{(-39\%)} & 0.45 & 0.65 (-35\%) & 0.50 & 0.58 \textbf{(-42\%)} & 0.42 & 0.71 \textbf{(-29\%)} & 0.58 \\ \bottomrule \end{tabular} \caption{\small Reduction in MRR and Hits@1 due to \textbf{adversarial additions on target triples in FB15k-237}. Lower values indicate better results; best results for each model are in bold. First block of rows are the baseline attacks with random edits; second block is state-of-art attacks; remaining are the proposed attacks. For each block, we report the \emph{best} reduction in percentage relative to the original MRR; computed as $(poisoned - original)/original*100$.} \label{tab:addition_FB15k-237} \end{table*} \section{Related Work} \citet{cai2018comprehensive} and \citet{nickel2015review} provide a comprehensive survey of KGE models. We use the most popular models DistMult \citep{yang2015distmult}, ComplEx \citep{trouillon2016complex}, ConvE \citep{dettmers2018conve} and TransE \citep{bordes2013transe}. Our work is most closely related to CRIAGE \citep{pezeshkpour2019criage} and Direct Attack \citep{zhang2019kgeattack}, that study both adversarial additions and deletions against KGE models. But CRIAGE is only applicable to multiplicative models and our experiments (Section \ref{sec:evaluation}) show that Direct Attack is effective (with respect to random baselines) on additive models only. On the other hand, our instance attribution methods work for all KGE models. Recently, \citet{lawrence2021gradientrollback} propose Gradient Rollback to estimate the influence of training triples on the KGE model predictions. The original study uses the influential triples for post-hoc explanations, but they can also be used for adversarial deletions. However, the attack stores the model parameter updates for \emph{all} training triples which are in the order of millions for benchmark datasets; and our experiments (Section \ref{sec:evaluation}) show that it performs similar to random deletions. Whereas, our influence estimation methods do not require additional storage and are consistently better than random baselines on all KGE models. We also study data poisoning attacks against KGE models in \citet{bhardwaj2021relationinferencepatterns}. Here, we exploit the inductive abilities of KGE models to select adversarial additions that improve the predictive performance of the model on a set of decoy triples; which in turn degrades the performance on target triples. These inference patterns based attacks cannot be used for adversarial deletions, but we will perform detailed comparison for adversarial additions in future. In parallel work, \citet{banerjee2021stealthypoisoningKGE} study risk aware adversarial attacks with the aim of reducing the exposure risk of an adversarial attack instead of improving the attack effectiveness. Also, previous studies by \citet{minervini2017adversarialsets} and \citet{cai2018kbgan} use adversarial regularization on the training loss of KGE models to improve predictive performance. But these adversarial samples are not in the input domain and aim to improve instead of degrade model performance. Poisoning attacks have also been studied against models for undirected and single relational graph data ~\citep{zugner2018nettack, dai2018adversarialgcn,xu2020advgraphsurvey}. But they cannot be applied directly to KGE models because they require gradients of a dense adjacency matrix. Other related work towards understanding KGE models are \citet{zhang2019interaction} and \citet{nandwani2020oxkbc} that generate post-hoc explanations in the form of sub-graphs. Also, \citet{trouillon2019inductive} study the inductive abilities of KGE models as binary relation properties for controlled inference tasks with synthetic datasets. Recently, \citet{allen2021interpreting} interpret the structure of KGE by drawing comparison with word embeddings. The instance attribution methods we use are also used for post-hoc example-based explanations of black-box models \citep{molnar2019interpretablemlbook}. \citet{hanawa2021evaluationsimilaritymetrics, charpiat2019inputsimilarity, pruthi2020trackin} use Instance or Gradient Similarity on image data. Similar to us, \citet{han2020influencenlp, han2020influenceveiledtoxicity, pezeshkpour2021instanceattribution} use different instance attribution methods, but to provide post-hoc explanations on natural language. \section{Conclusion} We propose data poisoning attacks against KGE models using instance attribution methods and demonstrate that the proposed attacks outperform the state-of-art attacks. We observe that the attacks are particularly effective when the KGE model relies on few training instances to make predictions, i.e. when the input graph is sparse. We also observe that shallow neural architectures like DistMult, ComplEx and TransE are vulnerable to naive attacks based on Instance Similarity. These models have shown competitive predictive performance by proper hyperparameter tuning \citep{ruffinelli2020olddognewtricks, kadlec2017kgebaselines}, making them promising candidates for use in production pipelines. But our research shows that these performance gains can be brittle. This calls for improved KGE model evaluation that accounts for adversarial robustness in addition to predictive performance. Additionally, as in \citet{bhardwaj2020towardsrobustKGE, bhardwaj2021relationinferencepatterns}, we call for future proposals to defend against the security vulnerabilities of KGE models. Some promising directions might be to use adversarial training techniques or train ensembles of models over subsets of training data to prevent the model predictions being influenced by a few triples only. Specification of the model failure modes through adversarial robustness certificates will also improve the usability of KGE models in high-stake domains like healthcare and finance. \section*{Acknowledgements} This research was conducted with the financial support of Accenture Labs and Science Foundation Ireland (SFI) at the ADAPT SFI Research Centre at Trinity College Dublin. The ADAPT SFI Centre for Digital Content Technology is funded by Science Foundation Ireland through the SFI Research Centres Programme and is co-funded under the European Regional Development Fund (ERDF) through Grant No. 13/RC/2106\_P2. \section*{Broader Impact} We study the problem of generating data poisoning attacks against KGE models. These models drive many enterprise products ranging from search engines (Google, Microsoft) to social networks (Facebook) to e-commerce (eBay) \citep{noy2019knowledgegraphs}, and are increasingly used in domains with high stakes like healthcare and finance \citep{hogan2020knowledgegraphs, bendsten2019astrazeneca}. Thus, it is important to identify the security vulnerabilities of these models that might be exploited by malicious actors to manipulate the predictions of the model and cause system failure. By highlighting these security vulnerabilities of KGE models, we provide an opportunity to fix them and protect stakeholders from harm. This honours the ACM Code of Ethics to contribute to societal well-being and avoid harm due to computing systems. Furthermore, to study data poisoning attacks against KGE models, we use the Instance Attribution Methods from Interpretable Machine Learning. These methods can also be used to provide post-hoc explanations for KGE models and thus, improve our understanding of the predictions made by the models. In addition to understanding model predictions, instance based attribution methods can help guide design decisions during KGE model training. There are a vast number of KGE model architectures, training strategies and loss functions, and empirically quantifying the impact of the design choices is often challenging \citep{ruffinelli2020olddognewtricks}. Thus, we would encourage further research on exploring the use of instance attribution methods to understand the impact of these choices on the KGE model predictions. By tracing back the model predictions to the input knowledge graph, we can gain a better understanding of the success or failure of different design choices.
{'timestamp': '2021-11-08T02:03:11', 'yymm': '2111', 'arxiv_id': '2111.03120', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03120'}
arxiv
\section{Introduction} In the unsupervised contrastive representation learning problem, we are given pairs of samples that are \textit{similar} to each other, e.g., an image and its augmentation, together with a set of dissimilar examples for each pair. One sample in a pair of similar samples is referred to as the \textit{anchor} and the other as the corresponding \textit{positive sample}. The dissimilar samples are referred to as the \textit{negative samples}. The goal is to learn a (typically) low-dimensional \textit{representation map} that amplifies the similarities and dissimilarities in the representation space by optimizing a suitable \textit{contrastive loss function}. The utility of learning this representation appears in a downstream task, where one can simplify both the model complexity, e.g., use a linear classifier, as well as reduce the number of training examples needed to achieve a desired classification error. A good set of representative papers in this context for contrastive representation learning are \citep{oord2018representation, hassani2020contrastive, zhu2020deep}. There are several useful choices of contrastive loss function to choose from, e.g., \citep{oord2018representation, wang2020understanding}, and often the set of similar examples are determined using the \textit{domain knowledge}, e.g., SimCLR \citep{chen2020simple} uses augmented views of the same images as positive pairs for image data, \citep{perozzi2014deepwalk} use random walks on the graph to generate positive pairs for graph data, Word2Vec \citep{goldberg2014word2vec} and Quick thought \citep{logeswaran2018efficient} define the neighborhood of words and sentences as positive for text data. On the other hand the choice of negative samples, possibly conditioned on the given similar pair, remains an open design choice. It is well-known that this choice can theoretically \citep{arora2019theoretical, chuang2020debiased} as well as empirically \citep{tschannen2019mutual, jin2018unsupervised} affect the performance of contrastive learning. The main focus of this paper is to offer a novel theoretical and algorithmic perspective on the design on negative sampling for unsupervised contrastive learning. \subsection{Related work} Several recent papers \citep{robinson2020contrastive, kalantidis2020hard, ho2020contrastive, cherian2020representation} have revisited the design of negative sampling distributions and, in particular, ``hard'' negative and/or adversarially designed negative samples, an idea that originates in a related problem of metric learning \citep{weinberger2009distance, sohn2016improved}. Hard negative samples are samples that provide the ``most'' contrast to a given set of similar samples for a given representation map, while possibly trading off inadvertent \textit{hard class collisions in a downstream classification task} that are inevitable due to the unsupervised nature of the problem. In a similar vein, \citep{wu2020conditional} propose to use neither ``too hard'' nor ``too easy'' negative samples via predefined percentiles and \citep{zheng2021contrastive} make use of ``learnable'' conditional distributions according to how informative the samples are to the anchor. The present work is most closely related to and motivated by the work of \citep{robinson2020contrastive}. They proposed a simple exponential-form hard negative sampling distribution with a scalar exponential tilting parameter $\beta$ and developed a practical, low-complexity importance sampling strategy that accounts for the lack of true dissimilarity information. Under an oracle assumption that the support of the hard negative sampling distribution is disjoint from samples with the same class as the anchor (which is impossible to guarantee in an unsupervised setting where we have no knowledge of downstream decision-making tasks), they establish certain desirable worst-case generalization properties of their sampling strategy in the asymptotic limit $\beta \rightarrow \infty$. They also empirically demonstrate the performance improvements offered by their proposed sampling method in downstream tasks through extensive experiments on on image, graph and text data. In contrast to the heuristically motivated exponential form of the hard negative sampling distribution in \citep{robinson2020contrastive}, we develop a principled minimax framework for hard negative sampling based on regularized Optimal Transport (OT) couplings. The regularization can be systematically relaxed to effect a smooth control over the degree of hardness of negative samples. \subsection{Main contributions} This paper makes the following key contributions. \begin{itemize} \setlength \itemsep{-4pt} \item In contrast to the current literature where the form of the negative sampling distribution is often heuristically motivated, albeit backed with good intuition and insight, we start with a principled (and novel) min-max perspective for sampling hard negatives. This formulation features negative sampling as an optimal (worst-case) coupling (a joint distribution subject to marginal constraints) between the anchor, positive, and negative samples. \item We show that for a large class of contrastive loss functions, the resulting min-max formulation contains degenerate solutions. We believe this provides the first theoretical justification in the unsupervised setting (to the best of our knowledge) that selecting worst-case negative sampling distributions can produce degenerate solutions motivating the needs for some type of regularization. \item Taking a cue from the theory of Optimal Transport (OT) we propose to regularize the coupling in various ways and recover the parametric choice of the negative sampling distribution proposed in \citep{robinson2020contrastive} as a special case of entropy-regularized OT coupling. \item We conduct several experiments using our entropy-regularized OT negative sampling framework to empirically corroborate the results of \citep{robinson2020contrastive}. \end{itemize} \section{Unsupervised Contrastive Learning}\label{sec:contrastive_learning} Unsupervised contrastive representation learning aims to learn a mapping $f$ from a sample space $\ensuremath{{\mathcal{X}}}$ to a representation space $\ensuremath{{\mathcal{F}}}$ such that similar sample pairs stay close to each other in $\ensuremath{{\mathcal{F}}}$ while dissimilar ones are far apart. We assume that the representation space is a subset of the Euclidean space ($\ensuremath{{\mathcal{F}}} \subseteq \ensuremath{{\mathbb{R}}}^{d}$) of low dimension and is normalized to have unit norm ($\ensuremath{{\mathcal{F}}} = \ensuremath{{\mathbb{S}}}^{d-1}$, the unit sphere in $\ensuremath{{\mathbb{R}}}^d$). Our focus is on the setting in which the learner has access to IID $(m+2)$-tuples, where each tuple $\tuple$ consists of an anchor sample $x$ and, associated with it, a positive sample $x^+$ and $m$ negative samples $x^-_1, \ldots, x^-_m$. For each given anchor-positive pair $(x,x^+)$, the corresponding $m$ negative samples are conditionally IID with distribution $\ensuremath{{P_{\mathrm{neg}}}}(x^-|x,x^+)$.\footnote{For simplicity of exposition, we assume that all distributions are densities unless otherwise noted.} Thus, the joint distribution of of the $(m+2)$-tuple is of the form: \begin{equation*} P\tuple = \ensuremath{{P_{\mathrm{sim}}}}(x,x^+) \prod_{i=1}^m \ensuremath{{P_{\mathrm{neg}}}}(x^-_i|x,x^+). \end{equation*} The distribution $\ensuremath{{P_{\mathrm{sim}}}}(x,x^+)$ for generating anchor-positive pairs can capture a variety of situations. These include word-context pairs in NLP data, with words as anchors and their context-words as positive samples, or image-augmentation pairs in visual data, with images as anchors and their augmentations, e.g., rotation, cropping, resizing, etc., as positive samples. \\ Implicit to many applications is the assumption that the anchor, positive, and negative samples have the same marginal distribution $\ensuremath{{P_{\mathrm{mar}}}}$. This property also holds for the recently proposed latent ``class'' modeling framework of \citep{arora2019theoretical} for contrastive unsupervised representation learning which has been adopted by several works, e.g., \citep{robinson2020contrastive}. Let $\ensuremath{{\mathcal{P}}}(\ensuremath{{P_{\mathrm{mar}}}})$ denote the set of joint distributions $P$ having the form shown above with a common marginal distribution $\ensuremath{{P_{\mathrm{mar}}}}$ for the anchor, positive, and negative samples. The representation $f$ is learned by minimizing the expected value of a loss function $\ell(f(x),f(x^+),f(x^-_1),\ldots,f(x^-_m))$ over all $f \in \mathcal{F}$. Some of the most widely used and successful loss functions are the triplet and logistic loss functions: \noindent \textbf{Triplet-loss} \citep{schroff2015facenet} \begin{flalign*} \ell_{\mathrm{triplet}}(x,x^+,x^-,f) &= \max(0,||f(x)-f(x^+)||^2 - ||f(x)-f(x^-)||^2 + \eta)\\ &= \max(0,2\,v + \eta) \end{flalign*} where $v := f^\top(x)\,f(x^-) - f^\top(x)\,f(x^+)$, $m=1$, and $\eta > 0$ is a margin hyper-parameter. The second equality above holds because $\mathcal{F} = \ensuremath{{\mathbb{S}}}^{d-1}$. \noindent \textbf{Logistic-loss} \citep{gutmann2010noise} also referred to as the $m$-pair multiclass logistic loss or sometimes loosely as the Noise Contrastive Estimation (NCE) loss {\small \begin{flalign} \!\!\!\ell_{NCE}(x,x^+,\{x^-_i\},\,f) &= \log\left(1 + \frac{q}{m} \sum_{i=1}^m \frac{e^{f^\top(x)f(x^-_i)}}{e^{f^\top(x)f(x^+)}}\right) \nonumber \\ &= \log\left(1 + \frac{q}{m} \sum_{i=1}^m e^{v_i}\right) \label{eq:NCE} \end{flalign}} where $v_i := f^\top(x)\,f(x^-_i) - f^\top(x)\,f(x^+)$ and $q > 0$ is a weighting hyper-parameter. The second equality above holds because $\mathcal{F} = \ensuremath{{\mathbb{S}}}^{d-1}$. \noindent \textbf{General convex non-decreasing loss}: We consider a general class of loss functions of the following form which includes the triplet and logistic loss functions: \begin{flalign*} \ell(x,x^+,\{x^-_i\},\,&f) = \psi\left(v_1,\ldots,v_m\right) \end{flalign*} where $v_i := f^\top(x)\,f(x^-_i) - f^\top(x)\,f(x^+)$ and $\psi(\cdot)$ is a convex function of $(v_1,\ldots,v_m)$ which is coordinate-wise non-decreasing, i.e., non-decreasing with respect to $v_i$ for each $i$ for any $(v_1,\ldots,v_m)$. The optimal representation map is the $f^* \in \ensuremath{{\mathcal{F}}}$ which minimizes the expected loss: \begin{flalign*} f^* = \arg\min_{f \in \ensuremath{{\mathcal{F}}}} \ensuremath{{\mathbb{E}}}_{P}[\psi(v_1,\ldots,v_m)] \end{flalign*} where the expectation is taken with respect to the joint distribution $P \in \ensuremath{{\mathcal{P}}}(\ensuremath{{P_{\mathrm{mar}}}})$ of $\tuple$. In practice, the expectation is replaced by an empirical average over IID training tuples with each tuple consisting of an anchor, a positive sample, and $m$ negative samples. \section{Min-max contrastive learning} \label{sec:minimax_representation} How does one design the negative sampling distribution $\ensuremath{{P_{\mathrm{neg}}}}$? This is a key question in unsupervised contrastive representation learning. In early works \citep{oord2018representation, chen2020simple}, the negative samples were generated \textit{independently} of the anchor and positive samples according to the marginal distribution $\ensuremath{{P_{\mathrm{mar}}}}$, i.e., $\ensuremath{{P_{\mathrm{neg}}}}(x^-|x,x^+) = \ensuremath{{P_{\mathrm{mar}}}}(x^-)$. Today we regard this as a baseline method for negative sampling. In later works \citep{robinson2020contrastive,wu2020conditional,zheng2021contrastive}, researchers have noted that ``hard'' or ``semi-hard'' negative samples, i.e., samples that are near the anchor in representation space far from it (i.e., dissimilar) in sample space could guide learning algorithms to correct ``mistakes'' in downstream supervised tasks more quickly \citep{daghaghi2021tale,kalantidis2020hard}. A variety of strategies for sampling hard negatives have been devised in the metric learning literature \citep{cai2020all,xiong2020approximate}. They, essentially, aim to select samples that are difficult to discriminate based on the current representation, often leveraging ideas from importance sampling \citep{robinson2020contrastive}. In contrast, we propose to generate hard negatives by designing a worst-case $\ensuremath{{P_{\mathrm{neg}}}}$ distribution subject to suitable regularity constraints. We capture these constraints via $\Omega$, a family of $\ensuremath{{P_{\mathrm{neg}}}}$ that satisfy the regularity constraints. For a given $\ensuremath{{P_{\mathrm{sim}}}}$ and $\Omega$, a robust representation $\ensuremath{{f_{\mathrm{rob}}}}$ is one which minimizes the maximum, i.e., worst-case, loss over $\Omega$: \begin{flalign*} \ensuremath{{f_{\mathrm{rob}}}}(\Omega) = \arg\min_{f \in \ensuremath{{\mathcal{F}}}} \max_{\ensuremath{{P_{\mathrm{neg}}}} \in \Omega} \ensuremath{{\mathbb{E}}}_P[\ell(x,x^+,\{x^-_i\})]. \end{flalign*} A natural first candidate for $\Omega$ that may come to mind is the set of all $\ensuremath{{P_{\mathrm{neg}}}}$ that are marginally consistent with $\ensuremath{{P_{\mathrm{mar}}}}$, i.e., \[ \ensuremath{{\Omega_{\mathrm{mar}}}} := \{\ensuremath{{P_{\mathrm{neg}}}}: \ensuremath{{P_{\mathrm{sim}}}} \otimes_{i=1}^m \ensuremath{{P_{\mathrm{neg}}}} \in \ensuremath{{\mathcal{P}}}(\ensuremath{{P_{\mathrm{mar}}}})\}. \] Note that since the anchor and positive sample are assumed to have the same marginal, $\ensuremath{{P_{\mathrm{mar}}}}$ is completely specified by $\ensuremath{{P_{\mathrm{sim}}}}$. Unfortunately, it turns out that $\ensuremath{{f_{\mathrm{rob}}}}(\ensuremath{{\Omega_{\mathrm{mar}}}})$ contains degenerate solutions, i.e., solutions such that with probability one, $\ensuremath{{f_{\mathrm{rob}}}}(\ensuremath{{\Omega_{\mathrm{mar}}}})(\ensuremath{{\mathbf{x}}}) = \ensuremath{{\mathbf{c}}}$ a constant vector in $\ensuremath{{\mathbb{S}}}^{d-1}$. We state this negative result as a theorem below. \begin{theorem}\label{thm:degenerate} For the general convex coordinate-wise non-decreasing loss described in Sec.~\ref{sec:contrastive_learning}, the min-max optimum representation for the family of marginally consistent negative sampling distributions contains degenerate solutions with probability one, i.e., solutions such that \[ w.p.1, \quad \ensuremath{{f_{\mathrm{rob}}}}(\ensuremath{{\Omega_{\mathrm{mar}}}})(\ensuremath{{\mathbf{x}}}) = \ensuremath{{\mathbf{c}}} \] a constant vector in $\ensuremath{{\mathbb{S}}}^{d-1}$. \end{theorem} To prove Theorem~\ref{thm:degenerate} we will make use of the following lemma: \begin{lemma}\label{lem:degenerate} For any given $\ensuremath{{P_{\mathrm{sim}}}}$, \[ \min_{f\in\ensuremath{{\mathcal{F}}}}\max_{\ensuremath{{P_{\mathrm{neg}}}}\in \ensuremath{{\Omega_{\mathrm{mar}}}}} \ensuremath{{\mathbb{E}}}_{P}[f^\top(x)\,f(x^-) - f^\top(x)\,f(x^+)] = 0 \] and equality can be attained for all $\ensuremath{{P_{\mathrm{sim}}}}$ by a degenerate $f$, i.e., a constant representation map. \end{lemma} \begin{proof} For each $f \in \ensuremath{{\mathcal{F}}}$, \begin{flalign*} \ensuremath{{\mathbb{E}}}_{P}[f^\top(x)\,f(x^-)] &\leq \sqrt{\ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{mar}}}}}||f(x)||^2\,\ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{mar}}}}}||f(x^-)||^2} \\ &= 1 \end{flalign*} by the Cauchy-Schwartz inequality because $\ensuremath{{\mathcal{F}}} = \ensuremath{{\mathbb{S}}}^{d-1}$. Equality can be attained if, and only if, $f(x) = f(x^-)$ with probability one. One choice of $\ensuremath{{P_{\mathrm{neg}}}}$ which ensures this is $x^- = x$ with probability one, independent of $x^+$. If $f$ is not injective, this is not the only choice. More generally, if the conditional distribution of $x^-$ given $x$ is equal to the conditional distribution of $x$ given its representation $f(x)$, then $x^-$ will have the same marginal distribution as $x$, i.e., $\ensuremath{{P_{\mathrm{mar}}}}$ since its generation is distributionally indistinguishable from the generation of $x$ in two steps: first generate a representation $f(x)$ and then sample $x$ from the pre-image of $f(x)$ in $\ensuremath{{\mathcal{X}}}$. Moreover, by construction, given $x$, $f(x^-) = f(x)$ with probability one. Thus, \begin{align*} &\max_{\ensuremath{{P_{\mathrm{neg}}}}\in \ensuremath{{\Omega_{\mathrm{mar}}}}} \ensuremath{{\mathbb{E}}}_{P}[f^\top(x)\,f(x^-) - f^\top(x)\,f(x^+)] \nonumber \\ &= \max_{\ensuremath{{P_{\mathrm{neg}}}}\in \ensuremath{{\Omega_{\mathrm{mar}}}}} \ensuremath{{\mathbb{E}}}_{P}[f^\top(x)\,f(x^-)] - \ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{sim}}}}}[f^\top(x)\,f(x^+)] \nonumber \\ &= 1 - \ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{sim}}}}}[f^\top(x)\,f(x^+)] \label{eq:maxoverPneg} \end{align*} An application of the Cauchy-Schwartz inequality a second time gives us \begin{align*} \ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{sim}}}}}[f^\top(x)\,f(x^+)] &\leq \sqrt{\ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{mar}}}}}||f(x)||^2\,\ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{mar}}}}}||f(x^+)||^2} \\ &= 1 \end{align*} and equality can be attained in the inequality simultaneously for all $\ensuremath{{P_{\mathrm{sim}}}}$ if $f$ is a constant representation map. From this and Eq.~(\ref{eq:maxoverPneg}) it follows that \begin{align*} &\min_{f\in\ensuremath{{\mathcal{F}}}}\max_{\ensuremath{{P_{\mathrm{neg}}}}\in \ensuremath{{\Omega_{\mathrm{mar}}}}} \ensuremath{{\mathbb{E}}}_{P}[f^\top(x)\,f(x^-) - f^\top(x)\,f(x^+)] \\ &= 1 - \max_{f\in\ensuremath{{\mathcal{F}}}}\ensuremath{{\mathbb{E}}}_{\ensuremath{{P_{\mathrm{sim}}}}}[f^\top(x)\,f(x^+)] \\ &\geq 1 - 1 \\ &=0 \end{align*} and equality can be attained in the inequality for all $\ensuremath{{P_{\mathrm{sim}}}}$ if $f$ is a constant representation map. \end{proof} The proof of Theorem~\ref{thm:degenerate} now follows from the convexity and coordinate-wise non-decreasing properties of the loss function. By Jensen's inequality for convex functions we have, \begin{align*} &\ensuremath{{\mathbb{E}}}_P[\psi(v_1,\ldots,v_m)] \geq \psi(\ensuremath{{\mathbb{E}}}_P[v_1],\ldots,\ensuremath{{\mathbb{E}}}_P[v_m]) \\ &= \psi(\ensuremath{{\mathbb{E}}}_P[v],\ldots,\ensuremath{{\mathbb{E}}}_P[v]) \end{align*} where $v(x,x^+,x^-) := f^\top(x)\,f(x^-) - f^\top(x)\,f(x^+)$. This is because all negative samples are IID conditioned on $x,x^+$. From Lemma~\ref{lem:degenerate}, we have \[ \min_{f\in\ensuremath{{\mathcal{F}}}} \max_{\ensuremath{{P_{\mathrm{neg}}}}\in\ensuremath{{\Omega_{\mathrm{mar}}}}} v(x,x^+,x^-) = 0. \] Since $\psi(v_1,\ldots,v_m)$ is coordinate-wise non-decreasing, it follows that \begin{align*} &\min_{f\in\ensuremath{{\mathcal{F}}}} \max_{\ensuremath{{P_{\mathrm{neg}}}}\in\ensuremath{{\Omega_{\mathrm{mar}}}}}\ensuremath{{\mathbb{E}}}_P[\psi(v_1,\ldots,v_m)] \\ &\geq \psi(\min_{f\in\ensuremath{{\mathcal{F}}}} \max_{\ensuremath{{P_{\mathrm{neg}}}}\in\ensuremath{{\Omega_{\mathrm{mar}}}}}\ensuremath{{\mathbb{E}}}_P[v],\ldots,\min_{f\in\ensuremath{{\mathcal{F}}}} \max_{\ensuremath{{P_{\mathrm{neg}}}}\in\ensuremath{{\Omega_{\mathrm{mar}}}}}\ensuremath{{\mathbb{E}}}_P[v]\ensuremath{{\mathbb{E}}}_P[v]) \\ &= \psi(0,\ldots,0). \end{align*} and equality can be attained by a degenerate representation which maps all samples to a constant vector in $\ensuremath{{\mathbb{S}}}^{d-1}$. This concludes the proof of Theorem~\ref{thm:degenerate}. The negative result of Theorem~\ref{thm:degenerate} motivates the need to incorporate other regularization constraints into $\Omega$ in order to preclude degenerate solutions. To develop this, in the next section we will interpret the min-max loss using the lens of Optimal Transport and then utilize regularized transport couplings to design an optimal $\ensuremath{{P_{\mathrm{neg}}}}$. \section{An Optimal Transport Perspective} We begin with the necessary background on optimal transport (OT). Given two probability distributions $P(x)$ and $P(y)$ over $\mathbb{R}^d$, let $\Pi$ denote the set of joint distributions or couplings $P(x,y)$ with marginals $P(x)$ and $P(y)$. The problem of optimal transport (OT) \citep{santambrogio2015optimal} is to seek the optimal coupling that solves \begin{align} \mathsf{OT}(P(x), P(y), c)= \min_{P(x,y) \in \Pi} \mathbb{E}_{P(x,y)}[c(x,y)], \end{align} where $c(x,y)$ is referred to as the ground-cost, as the cost of \textit{transporting} $x$ to $y$. Existence of the solutions to this problem is guaranteed under fairly general assumptions on the ground-cost \citep{villani2021topics}. To see how the OT set-up arises in the problem at hand, it is useful to focus and reduce to the case where we have a triplet $x,x^+,x^-$ and revisit the core Lemma \ref{lem:degenerate} and manipulate the objective like so {\small \setlength{\abovedisplayskip}{3pt} \setlength{\belowdisplayskip}{\abovedisplayskip} \setlength{\abovedisplayshortskip}{0pt} \setlength{\belowdisplayshortskip}{3pt} \begin{align} & \min_{f\in\ensuremath{{\mathcal{F}}}}\max_{\ensuremath{{P_{\mathrm{neg}}}}\in \ensuremath{{\Omega_{\mathrm{mar}}}}} \ensuremath{{\mathbb{E}}}_{P}[f^\top(x)\,f(x^-) - f^\top(x)\,f(x^+)] \notag\\ = & \min_{f \in \ensuremath{{\mathcal{F}}}} \max_{P(x,x^-)\in \Pi} \mb{E}_{P(x,x^-)}[f^\top(x)\,f(x^-)] - \mb{E}_{P_{sim} }[f(x)^\top f(x^+)], \notag \end{align}} where $\Pi$ is the set of couplings between $x,x^-$ with marginals $P_{mar}$. Under this constraint and completing the square, we have that, \begin{align} & \max_{P(x,x^-) \in \Pi} \mb{E}[f(x)^\top f(x^-)] \notag \\ & = -0.5 \min_{P(x,x^-) \in \Pi} \mb{E}[\|f(x) - f(x^-)\|_2^2] + \mb{E}\|f(x)\|_2^2. \notag \end{align} Noting that, $\min_{P(x,x^-) \in \Pi} \mb{E}[\|f(x) - f(x^-)\|_2^2] = \mathsf{OT}(P(f(x)), P(f(x^-)), c)$ with $c(x,x^-) = 0.5 \|f(x) - f(x^-) \|_2^2$. Now since $x,x^-$ have the same marginals, it implies that $f(x)$ and $f(x^-)$ will have the same distributions, which implies $\mathsf{OT}(P(f(x)), P(f(x^-)), c) = 0$. Hence, the min-max problem boils down to \begin{align} \min_{f \in \mc{F}} \mb{E}\|f(x)\|_2^2 - \mb{E}_{P_{sim}}[f(x)^\top f(x^+)], \end{align} which by Cauchy-Schwarz results in a degenerate solution with $f$ being a constant mapping and the optimal value being $=0$. In order to avoid this degeneracy, that implicitly arises due to the OT coupling, let us impose a set of meaningful and useful constraints to avoid it. \begin{enumerate} \setlength \itemsep{-3pt} \item \textbf{Avoid self-coupling}, i.e. For any triplet $x, x^-,x^+$, $x^- \neq x$ and $x^- \neq x^+$. \item \textbf{Regularize the coupling} - Under the default negative sampling, the usual coupling is $P(x,x^-) = P_{mar}(x) P_{mar}(x^-)$, which amounts to no hard-negatives. Therefore, we want to regularize the optimal coupling $P(x,x^-) \in \Pi$ penalizing the closeness to the default coupling, such that the degree of closeness inversely controls the degree of hardness of negative sampling. \item \textbf{Better than the default coupling} - Also it is desirable that $P(x,x^-)$ satisfies, \begin{align} \mathop{\mb{E}}_{ P_{mar} (x) P_{mar}(x^-)} [f(x)^\top f(x^-)] \leq \mathop{\mb{E}}_{P(x,x^-) } [f(x)^\top f(x^-)].\notag \end{align} \end{enumerate} In the next section we will show that these constraints and properties can be formally applied within the framework of regularized OT. \subsection{Regularized OT for negative sampling} We consider the following regularized version of optimal transport \citep{genevay_thesis, peyre2019computational} with ground-cost $c(x,x^-) = 0.5 \| f(x) - f(x^-)\|^2$ if $x^- \neq x$ or $x^- \neq x^+$ and $\infty$ otherwise to avoid self-coupling. {\small \setlength{\abovedisplayskip}{3pt} \setlength{\belowdisplayskip}{\abovedisplayskip} \setlength{\abovedisplayshortskip}{0pt} \setlength{\belowdisplayshortskip}{3pt} \begin{align} & P^*(x,x^-) = \notag \arg\min_{P(x,x^-) \in \Pi} \mb{E}[c(x,x^-)] + \epsilon\, \varphi\left(\frac{P(x,x^-)}{P_{mar}(x)P_{mar}(x^-)}\right) \label{Entrop_ot} \end{align}} where $\varphi$ is a convex function with non-negative reals as its domain. A particular choice of $\varphi = \mathsf{KL}(\cdot)$, where $\mathsf{KL}$ denotes the Kullback-Liebler divergence is defined below, \begin{align} & \mathsf{KL}(P(x,x^-)|| P_{mar}(x)P_{mar}(x^-)) \notag\\ = & \int_x \int_{x^-} \log \frac{P(x,x^-)}{P_{mar}(x)P_{mar}(x^-)} P(x,x^-) dxdx^-, \end{align} leads to what is referred to as the entropy regularized optimal transport, which comes with the computational efficiency of the Sinkhorn algorithm \citep{peyre2019computational}. The parameter $\epsilon$ is referred to as entropic regularization parameter. For this choice we note the following properties: \begin{enumerate} \setlength \itemsep{-3pt} \item The larger the $\epsilon$ less hard are the negative examples. So it allows for a continuous control of hardness of negative sampling. \item We know that when the distribution are the same, the entropy regularized OT cost is not zero. This avoids the degeneracy. \item Since $\mathsf{KL} \geq 0$ with equality iff $P(x,x^-) = P_{mar}(x)P_{mar}(x^-)$, for the case at hand it is easy to see that, {\small \setlength{\abovedisplayskip}{3pt} \setlength{\belowdisplayskip}{\abovedisplayskip} \setlength{\abovedisplayshortskip}{0pt} \setlength{\belowdisplayshortskip}{3pt} \begin{align} \mathop{\mb{E}}_{ P_{mar} (x) P_{mar}(x^-)} [f(x)^\top f(x^-)] \leq \mathop{\mb{E}}_{P^*(x,x^-) } [f(x)^\top f(x^-)] \notag \end{align}} \end{enumerate} \textbf{Connection to \citep{robinson2020contrastive}} - We now show how the optimal plan implied via the entropy regularized OT justifies the empirical choice made in \citep{robinson2020contrastive}. To this end, we note the following result. \begin{lemma} \citep{genevay_thesis} \label{connection} There exist continuous functions $u(x), v(x^-)$ such that the optimal entropy regularized coupling is given by,\\ {\small \setlength{\abovedisplayskip}{3pt} \setlength{\belowdisplayskip}{\abovedisplayskip} \setlength{\abovedisplayshortskip}{0pt} \setlength{\belowdisplayshortskip}{3pt} \begin{align} P^*(x,x^-) \notag = \exp \left( \frac{u(x) + v(x^-) - c(x,x^-)}{\epsilon}\right) P_{mar}(x)P_{mar}(x^-) \notag \end{align}} \end{lemma} Specializing this result to our case we note that {\small \setlength{\abovedisplayskip}{3pt} \setlength{\belowdisplayskip}{\abovedisplayskip} \setlength{\abovedisplayshortskip}{0pt} \setlength{\belowdisplayshortskip}{3pt} \begin{align} P^*(x,x^-) = \notag \exp \left( \frac{u(x) + v(x^-) + f(x)^\top f(x^-) - 1}{\epsilon}\right) P_{mar}(x)P_{mar}(x^-) \notag, \end{align}} which implies that, \begin{align} & P^*(x^-|x) \propto \exp(\frac{ f(x)^\top f(x^-)}{\epsilon}) P_{mar}(x^-) \label{eq:opt_ent_reg_coupling} \end{align} We now recall that in \citep{robinson2020contrastive}, the authors chose $P(x^-|x) \propto e^{\beta f(x)^\top f(x^-)} P_{mar}(x^-)$ for design of hard-negatives which is of the same exponential form as $ P^*(x^-|x)$ given by Equation~\eqref{eq:opt_ent_reg_coupling}. \section{Experimental Corroboration} \begin{table*}[h] \scriptsize \centering \begin{tabular}{||c c c c||} \hline Loss function & SimCLR \citep{chen2020simple}& \citep{robinson2020contrastive} & Entropic OT \\ \hline\hline Upper &None&83.0&82.8\\ \hline NCE &80.2&84.4&85.0\\ \hline Debiased NCE &84.3&87.4&87.5\\ \hline \end{tabular} \vspace{-1mm} \caption{\label{tbl:STL10} The best linear readout accuracy attained by different methods on the STL10 dataset.} \vspace{-1mm} \end{table*} \begin{table*}[h] \scriptsize \centering \begin{tabular}{||c c c c||} \hline Loss function & SimCLR \citep{chen2020simple}& \citep{robinson2020contrastive} & Entropic OT \\ \hline\hline Upper &None&90.2&90.8\\ \hline NCE &91.0&91.4&91.2\\ \hline Debiased NCE &91.2&92.1&91.8\\ \hline \end{tabular} \vspace{-1mm} \caption{\label{tbl:CIFAR10} The best linear readout accuracy attained by different methods on the CIFAR10 dataset.} \vspace{-1mm} \end{table*} \begin{table*}[h!] \scriptsize \centering \begin{tabular}{||c c c c||} \hline Loss function & SimCLR \citep{chen2020simple}& \citep{robinson2020contrastive} & Entropic OT \\ \hline\hline Upper &None&64.8&67.3\\ \hline NCE &66.6&69.2&69.1\\ \hline Debiased NCE &67.5 &69.3 &69.5\\ \hline \end{tabular} \vspace{-1mm} \caption{\label{tbl:CIFAR100} The best linear readout accuracy attained by different methods on the CIFAR100 dataset.} \vspace{-1mm} \end{table*} In the previous section we have shown that our entropy-regularized OT solution recovers the exponential form hard negative sampling distribution of \citep{robinson2020contrastive}. In this section we present experiments on three image and five graph datasets to empirically demonstrate that our proposed method for negative sampling can indeed match (and sometimes slightly exceed) the state-of-the-art performance results reported in \citep{robinson2020contrastive}. For these experiments we adopt the same simulation set-up borrowing the code implementation from \citep{robinson2020contrastive}, where we only replace their negative coupling with our negative coupling obtained by solving for Eq. \eqref{Entrop_ot} with $\varphi = \mathsf{KL}$. For entropy regularized OT, we use the POT package \citep{flamary2021pot} that implements the numerically stable version of the entropy regularized OT algorithm described in \citep{cuturi2013sinkhorn}. \subsection{Image datasets} The three image datasets that we work with are STL10 \citep{coates2011analysis}, CIFAR10, and CIFAR100 \citep{krizhevsky2009learning}, which contain images with 10, 10, and 100 classes, respectively. We use SimCLR\citep{chen2020simple} as a baseline and compare our method to the algorithm proposed in \citep{robinson2020contrastive} for three choices of loss functions to learn the mapping $f$ using the negative samples, namely, the large-$m$ asymptotic form of the NCE loss ($m\rightarrow \infty$), the debiased NCE loss \citep{chuang2020debiased}, and the upper bound loss that corresponds to the objective of Lemma~\ref{lem:degenerate}. In our experiments, we approximate all expectations that appear in the loss functions via empirical averages over a batch of $B$ training samples. \textbf{Training Procedure:} There are two hyperparameters to tune namely, $\epsilon$ for our method, and $\tau$ that appears as a hyper-parameter in the debaised loss \citep{chuang2020debiased}. For these we perform a grid search over the sets $\{0.1,0.3,0.5,0.7,1\}$ for $\epsilon$ and $\{0.01, 0.05, 0.1, 0.5\}$ for $\tau$. All models are trained for $E = 400$ epochs with batch size $B = 512$. We use the Adam optimizer with learning rate $0.001$ and weight decay $10^{-6}$. We use NVIDIA A100 32 GB GPU for our computations and it takes about 20 hours to train one model (400 epochs) for each dataset. \textbf{Results:} Tables~\ref{tbl:STL10}, \ref{tbl:CIFAR10}, and \ref{tbl:CIFAR100} compare the best accuracies of different methods attained for three different loss function on three image datasets. Our proposed method clearly improves over the baseline. For the NCE loss, we observe absolute improvements of $4.8$ and $2.5$ percentage points over SimCLR on the STL10 and CIFAR100 datasets, respectively. For Debiased NCE loss, the absolute improvements over SimCLR are $3.2$ and $2.0$ percentage points on the STL10 and CIFAR100 datasets, respectively. The performance of our method is very similar to that of \citep{robinson2020contrastive}. This is consistent with our theoretical analysis and insights from Lemma \ref{connection} which shows that our entropy-regularized hard negative sampling distribution has the same exponential form as the distribution proposed in \citep{robinson2020contrastive}. \subsection{Graph dataset} We also apply our method to learn graph representations on five graph datasets: MUTAG, ENZYMES, PTC, IMDB-BINARY, IMDB-MULTI by \citep{morris2020tudataset}. We employ InfoGraph \citep{sun2019infograph} as a baseline method. \begin{table*}[h!] \scriptsize \centering \begin{tabular}{||c c c c c c c||} \hline Method & MUTAG & ENZYMES & PTC &IMDB-BINARY & IMDB-MULTI& \\ \hline\hline InfoGraph \citep{sun2019infograph} &86.8& 50.4 &55.3 & 72.2 & 49.6&\\ \hline \citep{robinson2020contrastive} best &87.2& 50.4 &$\bold{57.3}$ & 72.8 & 49.6&\\ \hline $\epsilon=0.05$ &87.2&$\bold{51.3}$&56.8 & $\bold{73.0}$& 49.8&\\ \hline $\epsilon=0.1$ &$\bold{88.2}$&50.6&56.1 & 72.7& 49.8&\\ \hline $\epsilon=0.5$ &87.5 &50.9 &55.8&72.1& $\bold{50.0}$&\\ \hline $\epsilon=1$ &87.6 &50.3 &55.4 &72.5& $\bold{50.0}$&\\ \hline \end{tabular} \vspace{-1mm} \caption{\label{a-guide} Accuracy on graph dataset with different $\epsilon$}\label{graph} \vspace{-1mm} \end{table*} \textbf{Training Procedure:} Similar to the experiments with image datasets, we only replace the negative distribution in code implementation from \citep{robinson2020contrastive} with ours. The dimension of the node embedding is set to $96$. For the hyper-parameters $\epsilon$ and $\tau$, we search over the $\{0.05,0.1,0.5,1\}$ and $\{0.1, 0.5\}$ respectively. We report the accuracy for all these choices of $\epsilon$ and for $\tau=0.5$ in Table 4. All model are trained for 200 epochs. The optimizer we use is the Adam optimizer with learning rate $0.01$. Then we use SVM to make classification with fixed graph-level embedding. Each model is trained 10 times with 10-fold cross validation. We report the average accuracy in Table \ref{graph}. We use NVIDIA K80 12 GB GPU for computation. \textbf{Results:} We report the performance accuracy of the different methods in Table 4 with boldface numbers indicating the best performance. We observe that our method is consistently better than the baseline \citep{sun2019infograph} in all datasets improving the accuracy by $1.4$ and $1.3$ percentage points on the MUTAG and PTC datasets, respectively, and is competitive with the state-of-the-art method in \citep{robinson2020contrastive}. \subsection{Discussion} In this section, we mainly discuss the result from the image dataset. To figure out how our method works, we plot the top ten similar images to the anchor, i.e., the images with the highest inner product in representation space with the anchor image, before training in Figure \ref{10_sim} and after training in Figure \ref{10_sim_2} separately. The left larger image is the anchor and to its right are ten images from the same batch. We observe that before training only one of these ten images comes from the same class as the anchor. However, after training for 400 epochs, seven out of ten images come from the same class. This indicates that more images with the same labels are becoming closer to each other in the representation space which is how we would expect a contrastive representation learning method to behave. \begin{figure}[h!] \centerline{\includegraphics[width=8cm, height=3cm]{ours.png}} \vspace{-3mm} \caption{Top-10 similar images before training}\label{10_sim} \vspace{-1mm} \end{figure} \begin{figure}[h!] \centerline{\includegraphics[width=8cm, height=3cm]{ours_2.png}} \vspace{-3mm} \caption{Top-10 similar image with our method after training}\label{10_sim_2} \vspace{-1mm} \end{figure} We show the negative images with the highest $P^*(x^-|x)$ generated by our method in Figure \ref{10_neg} and the negative images uniformly chosen from one batch in Figure \ref{10_random}. We observe that uniformly sampled negative images are irrelevant to the anchor (only 4 out of 10 negative images are of animals). But the negative images sampled from our designed ${P}^*(x^-|x)$ shares more similar characteristics with the anchor such as color, background, and 7 out of 10 negative images are of animals. \\ \begin{figure}[h!] \centerline{\includegraphics[width=8cm, height=2.5cm]{trans.png}} \vspace{-3mm} \caption{Negative images with Top-10 $ {P*}_{x^-|x}$ generated by our method}\label{10_neg} \vspace{-1mm} \end{figure} \begin{figure}[h!] \centerline{\includegraphics[width=8cm, height=3cm]{trans_rando.png}} \vspace{-3mm} \caption{Uniformly sampled negative images.}\label{10_random} \vspace{-1mm} \end{figure} We plot $P^*(x^-|x)$ and compare it with $e^{2f(x)^{\top}f(x^-)}$ in Figure \ref{trans_inner}. In this figure, the x-axis is reordered from the left to the right by decreasing values of $f(x)^{\top}f(x^-)$. The figure shows that the negative sample $x^-$ with larger $f(x)^{\top}f(x^-)$ is likely to have a higher $ {P}^*(x^-|x)$. From Figure~\ref{10_sim_2}, we see that as we are training the model, samples with the same label will become closer in the representation space (i.e., more similar). This means that after training for a certain number of epochs the samples coming from the same class at the anchor are more likely to be selected as the negative samples. \begin{figure*}[h!] \begin{center} {\includegraphics[width=18cm, height=3.5cm]{trans_inner_3.png}} \end{center} \vspace{-3mm} \caption{Comparison between $f(x)^{\top}f(x^-)$ and $ {P}(x^-|x)$ calculated by our method on epoch 0, 100, 400}\label{trans_inner} \vspace{-1mm} \end{figure*} \begin{figure*}[h!] \begin{center} \includegraphics[width=18.1cm, height=3.25cm]{distribution_2.png} \end{center} \vspace{-3mm} \caption{Plot of the number of times the true label of the anchor is the same as the true label of the negative examples (in the same batch over different epochs) that are arranged in decreasing order of similarity along the x-axis.} \label{distribution} \vspace{-1mm} \end{figure*} Now in order to get more insights In Figure \ref{distribution} we plot the number of times the anchor has the same label as the negative sample, which are arranged in order of increasing distance from anchor along the x-axis. The figure shows not only more samples are getting closer to the anchor but also more samples with the same label are getting further. This highlights the tradeoffs in design of hard negatives using the proposed method that forces the anchor to contrast more with images that are closer in the representation domain, that are likely to come from the same class. We plot part of the most similar and dissimilar images with the same label from one batch in Figure \ref{same_class}. \begin{figure}[H] \centerline{\includegraphics[width=8cm, height=3cm]{same_class.png}} \vspace{-3mm} \caption{Upper row: Top-5 most similar images to the anchor image (ranked 1, 2, 3, 4, and 6 by similarity in representation space) that have the same label (namely `bird') as the anchor. Lower row: Top-5 most dissimilar images to the anchor image (ranked 254, 253, 244, 228, and 225 by similarity in representation space) that have the same label `bird' as the anchor.}\label{same_class} \vspace{-1mm} \end{figure} We can see that the bird in the anchor image and the birds in the most similar images share some yellow-colored plumage. However, the colors of birds in the most dissimilar images are very different from that of the bird in the anchor image. Thus, our model seems to have learned some irrelevant characteristic such as color and discarded higher-level features shared by the entire object class 'birds' (the label of the anchor). This pushes some other birds image far away from the anchor in the representation space. \section{Conclusion and Future Work} In this paper we proposed and analyzed a novel min-max setting for hard negative sampling for unsupervised contrastive learning. We show that without further regularization, the optimal representation can become degenerate for a large class of contrastive loss functions. We show that reframing the problem in terms of regularized optimal transport (OT) offers a systematic approach to design negative sampling distributions to learn good non degenerate representations that can improve the performance of downstream classification tasks. Our work also provides a theoretical justification for a recently proposed state-of-the-art negative sampling method. \citep{robinson2020contrastive}. The OT perspective on the design of hard-negatives that is put forth in this paper opens up the possibility for employing and investigating the effect of regularizations other than the entropic regularization of the optimal transport couplings, different marginal constraints, and the ground-costs, for potentially improved design of negative samples. \section{Codes and Implementation} Our code can be found at https://github.com/rjiang03/Hard-Negative-Sampling-via-Regularized-Optimal-Transport-for-Contrastive-Representation-Learning \newpage \bibliographystyle{abbrvnat}
{'timestamp': '2021-11-08T02:05:20', 'yymm': '2111', 'arxiv_id': '2111.03169', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03169'}
arxiv
\section{Conclusion} Many works which rely on multiple EEG channels have successfully produced automated vigilance state classifiers; however, the hardware required to obtain such signals produces undesirable disadvantages. Here we evaluate various machine learning techniques in vigilance state classification based on a single EEG channel. Random Forests and Artificial Neural Networks produced remarkable accuracies of approximately 96\% and 93\%. In evaluation of these classification techniques against human scoring as ground truth, we note that humans may make misclassifications. In fact, due to the rigidly patterned nature of the data and the power of these statistical models, it would be appropriate to reevaluate human scores based on model classifications. Future research will have a domain expert label polysomnograms from the additional 147 hours of unscored data aided by the model from this work. Additionally, future research will have a domain expert reevaluate classification pairs that confused the models in this work. Here we achieved two accurate and reliable models that can be used immediately in an automated vigilance state classifier and may be reinforced in future work. \section{Introduction} Nearly 70 million Americans are afflicted by chronic sleep disorders or intermittent sleep disturbances that negatively impact health and substantially burden our health system. Sleep is essential for optimal health. Sleep is one of the most critical and ubiquitous biological processes, next to eating and drinking. It has been shown that there is no clear evidence of the existence of an animal species that does not sleep \cite{a1}. Sleep constitutes about 30\% of the human lifespan. Assessment of sleep quality is multifactorial and is composed of adequate duration, good quality, appropriate timing and regularity, and the absence of sleep disturbances or disorders. Sleep duration is used as a metric to describe the standard of healthy sleep. The American Academy of Sleep Medicine (AASM) and Sleep Research Society (SRS) issued a consensus statement recommending ``adults should sleep 7 or more hours per night on a regular basis to promote optimal health"\cite{a2}. However, sufficient sleep is severely undervalued as a necessary biological process for maintaining proper mental health. A recent survey from the Center for Disease Control and Prevention (CDC) found that only 65\% of adults reported a healthy duration of sleep \cite{a3}. From a translational perspective, animal studies are imperative to recapitulate phenotypes associated with sleep loss (hyperarousal, cognitive impairment, slowed psychomotor vigilance, behavioral despair) and uncover mechanisms contributing to psychopathology, with the added benefit of homogeneity within rodent subjects \cite{b1,b2}. Sleep studies are readily conducted in small animals by implanting electrodes to obtain electroencephalogram (EEG) and electromyogram (EMG). Sleep is categorized into two major classes, non-rapid eye movement (NREM) and rapid eye movement (REM) sleep, and arousal is classified as wake. Most often, investigators manually classify the polysomnography into vigilance states, and this practice is time-consuming and also greatly limits the size of a study’s data set. To accurately classify vigilance states, investigators undergo extensive training, yet the subjective nature of classifying limits inter-scorer reliability. Several automated vigilance state classifiers have been established, and nearly all of these algorithms rely on multi-channel EEG data and local field potential (LFP) signaling oscillations within the brain \cite{b3,b4,b5,b6,b7,b8,b9}. The advantages of multi-channel systems are outweighed by the disadvantage of tethering small animals to transmit signals via wired connections to computer programs. Tethered animals are combating confounds including limited mobility within recording cages and potential impacts on natural sleep states \cite{b10,b11,b12}. For these reasons, it is advantageous to automate vigilance state classification with telemetric battery devices that are surgically implanted to open a single EEG and EMG from each small animal. Consistent with the principles of Information Theory, data collected from a single EEG channel significantly increases the complexity of sleep-state identification for humans and automated approaches. Therefore, the goal of this research has been to produce an open access and automated classifier that can reliably predict vigilance state based on a single cortical EEG from rodents. To that end, we have evaluated several of the commonly used Machine Learning techniques for suitability and success in this task. Our investigations include Decision Trees, Naive Bayes Classifiers, Random Forests, and Artificial Neural Networks. An Artificial Neural Network (ANN) has been developed to examine and ascertain the sleep state of each animal. \section{Methodology} \subsection{Sleep EEG/EMG Data Collection} Adult Wistar rats (n=8) were used in experiments in a facility fully accredited by the American Association for the Accreditation of Laboratory Animal Care. Animals were kept on a 12/12 h light-dark cycle. All protocols were approved by the Institutional Animal Care and Use Committee at the University of South Carolina and were in accordance with the National Institutes of Health Guide for the Care and Use of Laboratory Animals. Rats were implanted with EEG/EMG telemetry devices (PhysioTel HD-S02, Data Science International, St. Paul, MN), as previously described \cite{b12,b13,b14,b15}. Briefly, under isoflurane anesthesia, animals were placed in a stereotaxic frame. The transmitter device was intraperitoneally implanted through a dorsal incision of the abdominal region. After an incision at the midline of the head was made, EEG leads were secured to two surgical screws inserted into 0.5-mm burr holes at 2.0 mm anterior/1.5 mm lateral and 7.0 mm posterior/-1.5 mm lateral to bregma. Two EMG leads were inserted into the dorsal cervical neck muscle about 1.0 mm apart and sutured into place. The skin was sutured, and animals were recovered for a minimum of 7 days prior to experimentation. Sleep data were acquired in a quiet, designated room where rats remained undisturbed for the duration of recording using Ponemah 6.10 software (DSI). Digitized signal data were imported into NeuroScore 3.0 (DSI) and powerband frequencies (0 to 20 Hz) in 0.5 Hz increments were exported to CSV formatted flat files. \subsection{Data Processing and Annotation} Approximately 571 hours of continuously monitored electroencephalogram (EEG), electromyogram (EMG), and activity were recorded across the eight laboratory rodents. The collection of data was then partitioned into 10-second \textit{epochs}, or segments, and labeled by a domain expert. Approximately 427 hours of the recorded 571 hours have been manually labeled by a domain expert. In this study, our focus has been based on the manually annotated 427 hours of the data. The remaining 144 hours of unlabelled data will be used in the future for more rigorous testing of our automated classification method. Based on the polysomnogram (PSG), an expert labels each 10-second epoch as one of three discrete classes: Paradoxical, Slow-wave, or Wake. Paradoxical sleep is also known as rapid-eye-movement (REM) sleep, because of the paradox of the high-frequency brain waves mimicking wakefulness despite being asleep. Slow-Wave sleep, characterized by low frequency, high amplitude brain waves, is also known as non-rapid eye movement sleep (NREM), and it constitutes all sleep that is not REM sleep. Finally, the ``wake" classification is given to a PSG that elicits characteristics of wakefulness. These sleep stages constitute all three \textit{classes} and will be referred to as P, S, and W, which correspond to Paradoxical, Slow-wave, and Wake states, respectively. 42 discrete features were extracted from each 10-second epoch of continuous EEG, EMG, and activity signals. To obtain the first 40 features, the 10-second epoch is transformed from the time domain into the frequency domain using Discrete Fourier Transformation, then partitioned into 40 channels of equal width from 0 to 20 Hz. Thus, the first channel is the EEG from 0 to 0.5 Hz, the second channel is the EEG from 0.5 to 1 Hz, and so on. The 41st feature is that of the EMG, which is averaged over the 10-second epoch. The 42nd and final feature is the ``Activity" feature, which is a derived parameter from \href{https://support.datasci.com/hc/en-us/articles/115005030328}{Ponemah} (indicating the level of an animal's activity) which depends on the transmitter model, the speed with which the transmitter moves, outside radio interference, and variations from sensor to sensor. \subsection{Input Formalization} Many tactics in modern machine learning and artificial intelligence have been presented that aim to formalize the use of temporal data in the tasks of prediction and classification. Although the proper formulation of input can have a substantial impact on the trainability and the outcome of ML developments, in this investigation, we have implemented the most prevalent and natural approach. More specifically, the input to our ML activities consisted of a concatenation of five consecutive processed data (42 channels) that summarize a 10-second epoch from the raw continuous data. We postulate that a single epoch (summary of 10 seconds of data) is not the optimal temporal representation of time-series data for use in ML applications. Therefore, we choose to reformat the data such that each sample spans a longer period, theoretically providing each classifier with more temporal information and confidence. Five consecutive epochs encapsulate 50 seconds of the temporal signal, to which we will refer as the network input in the remainder of this report. Before this windowing, the data consisted of 154043 rows and 43 columns. Each row, which itself constitutes a 10-second epoch, consists of the 42 features and 1 output label describing the three stages of vigilance. This mechanism of input data creation results in the following class distribution: \begin{lstlisting}[style=Bash] Total: 154039 P: 10028 (6.5 S: 64539 (41.7 W: 79472 (51.7 \end{lstlisting} This data set was created by a simple moving window, where the first windowed sample will consist of samples 0-4 in the original data. The second windowed sample consisted of samples 1-5 in the original data, and the final windowed sample consisted of samples (n-5)-(n-1) in the original data. Since each input spans five individual vigilance states, various methods of arriving at a single output (given from five outputs) can be envisioned. In this work, we choose to label each windowed sample with the most frequent class in the window. If there is a tie, we label the sample with the label of the 10-second epoch in the center. The total number of samples after the simple moving windowing has 4 samples less than the original data, which is well known to be the case when windowing data. Thus, each row in the input data consists of 210 features (5 sets of 42 features), and 1 label. \subsection{Data Balancing} The class distribution in the raw windowed data is unequal. Ideally, there would be an equal representation of each class, where each class constitutes 33\% of the data, in this instance. However, class P is severely underrepresented at 6.51\% of the total data, or 10028 samples. Classes S and W are over-represented at 41.90\% and 51.59\%, or 64539 samples and 79472 samples, respectively. In balancing the representation between classes, we aim to replicate copies of classes to the data while minimizing total samples. Minimizing total samples is important to improve training speed. By concatenating complete copies of any given class to itself, we aim to ensure that the model adequately generalizes to the entire class sample. Therefore, we concatenate 7 additional copies of the entire P class to the data, which produced the following and improved class distribution: \begin{lstlisting}[style=Bash] Total: 224235 P: 80224 (35.7 S: 64539 (28.7 W: 79472 (35.4 \end{lstlisting} \subsection{Training, Validation, and Testing Split and Shuffle} To finalize data preparation before training a classifier, the data must be shuffled and partitioned into training, validation, and testing sets. To perform the shuffling and partitioning, we use a function from the popular machine learning module in python \href{https://scikit-learn.org/stable/}{scikit-learn}. This function randomly shuffles the data and partitions it into training and testing data. We split the data into 80\% training and 20\% testing data. The only machine learning classifier which uses a validation set is the Artificial Neural Network. For the Artificial Neural Network, we further split the training data into 80\% training, 20\% validation, which constitutes 64\% and 16\% of the entire data. This process was performed only once to keep the training, testing, and validation (when needed) sets constant across each ML technique. A consistent training/testing set will help to establish a more consistent comparison of performances across multiple techniques while also reducing the data preparation time. \subsection{Evaluation of Machine Learning Classifiers} We propose to evaluate various machine learning techniques to classify vigilance states. Following are brief descriptions of Decision Trees, Random Forests, Naive Bayes Classifiers, Logistic Regression Classifiers, and Artificial Neural Networks. We aim to find the simplest model that achieves the highest accuracy. \subsection{Decision Tree} A Decision Tree Classifier is a supervised machine learning algorithm that performs classification tasks. The algorithm behind a Decision Tree makes a sequence of decisions based on input features, one decision at each node along a path from the root to a leaf of the tree. The leaf node that the algorithm ends on for any given input determines the output class. Decision trees are self-interpretable, meaning the tree itself describes the underlying rules for classification. The advantages of the Decision Tree Classifier include its simplicity, interpretability, ability to model nonlinear data, ability to model high dimensional data, ability to work with large datasets to produce accurate results, and ability to handle outliers during training. \subsection{Random Forest} A Random Forest Classifier is a supervised predictive machine learning algorithm commonly used for classification tasks. A Random Forest consists of an ensemble of decision trees, each of which provides a ``vote", or a classification, predicting class based on a majority of votes from the decision trees. Random forests generally outperform decision trees in terms of accuracy; however, the random forest is a \textit{blackbox}, a model unable to describe its underlying rules for classification, sacrificing the interpretability of the decision tree. \subsection{Naive Bayes} A Naive Bayes Classifier is a supervised probabilistic machine learning algorithm commonly used for classification tasks. It relies on Bayes' Theorem, which is a theorem of conditional probabilities. Naive Bayes assumes strong independence between the input features. We use the Gaussian Naive Bayes Classifier based on the assumption that each input feature is normally distributed. The Naive Bayes Classifier is simple (and, therefore, computationally fast), scalable (requiring parameters linear in the number of features), and works well with high-dimensional data. \subsection{Logistic Regression} A Logistic Regression Classifier is a supervised predictive machine learning algorithm used for classification tasks. It is a type of generalized Linear Regression algorithm with a complex cost function. The cost function used here is the Sigmoid function, which continuously maps real-valued numbers between 0 and 1. We partition these continuously-mapped values from the cost function by various threshold values to determine output class. We include Logistic Regression in this work based on its speed, non-assumption of feature independence, and ubiquity in multi-class classification. \subsection{Artificial Neural Network} An artificial neural network is a supervised predictive machine learning technique that is successful in classification tasks in various applications \cite{b16,b17,b18}. A feed-forward neural network is a subset of neural networks in general where there are no cycles formed between neurons. We choose to use a specific type of feed-forward neural network, the multi-layer perceptron (MLP). An MLP consists of at least one hidden layer of neurons, as opposed to a single-layer perceptron, which does not have a hidden layer of neurons separate from the input and output layers. We propose to use a shallow neural network, as opposed to a deep neural network, which is a subset of the multi-layer perceptron. For a neural network to be \textit{shallow}, it means that the network has exactly one hidden layer with any number of neurons. \subsubsection{Architecture} For this investigation, we propose a fully connected artificial neural network with one hidden layer. The network has a single input layer where the number of neurons equals the number of input features and a single output layer where the number of neurons equals the number of classes. Thus, we use a neural network architecture similar to Figure.\ref{fig:arc} with 210 input neurons, 256 hidden layer neurons, and three output neurons. \begin{figure} \centerline{\begin{tikzpicture}[shorten >=1pt,->,draw=black!50, node distance=2.5cm] \tikzstyle{every pin edge}=[<-,shorten <=1pt] \tikzstyle{neuron}=[circle,fill=black!25,minimum size=17pt,inner sep=0pt] \tikzstyle{input neuron}=[neuron, fill=green!50]; \tikzstyle{output neuron}=[neuron, fill=red!50]; \tikzstyle{hidden neuron}=[neuron, fill=blue!50]; \tikzstyle{annot} = [text width=4em, text centered] \foreach \name / \y in {1,...,4} \node[input neuron] (I-\name) at (0,-\y) {}; \foreach \name / \y in {1,...,5} \path[yshift=0.5cm] node[hidden neuron] (H-\name) at (2.5cm,-\y cm) {}; \node[output neuron, right of=H-3] (O) {}; \foreach \source in {1,...,4} \foreach \dest in {1,...,5} \path (I-\source) edge (H-\dest); \foreach \source in {1,...,5} \path (H-\source) edge (O); \node[annot,above of=H-1, node distance=1cm] (hl) {Hidden layer}; \node[annot,left of=hl] {Input layer}; \node[annot,right of=hl] {Output layer}; \end{tikzpicture}} \caption{Fully-connected artificial neural network with shape (210,256,3), meaning the input layer has 210 neurons, the single hidden layer has 256 neurons, and the output layer has 3 neurons.} \label{fig:arc} \end{figure} Non-linear activation functions allow neural networks to learn complex patterns. We use the rectified linear unit activation function after the hidden layer to introduce this non-linearity into the model. We use the softmax activation function after the output layer. Softmax is commonly used in multi-class classification problems, more general than sigmoid, and maps output into the range between 0 and 1, making it a good function for determining class. We use the \textit{backpropagation} learning technique and the \textit{adam} optimizer \cite{adam}. \subsection{Evaluation of Model Performance} We evaluate the performance of each of the classifiers by comparing the predictions of each model to the manual scoring of domain experts. Testing accuracy is a ratio of the number of correctly classified samples by the model to the total number of samples. The primary measure of performance used in this investigation will be testing accuracy. However, testing accuracy does not always fully describe the performance of a machine learning model. Oftentimes it is important to maximize the true positive classifications or to minimize the false positive classifications. In order to measure these situations, we have the proportions called \textit{precision} and \textit{recall}. \textit{Precision} is the proportion of model classifications that correspond to the sample's true class. \textit{Recall} is the proportion of samples that are actually classified by the model correctly. In addition to these metrics, we also provide \textit{F1 Score}. The \textit{F1 Score} is the harmonic mean of precision and recall. Finally, \textit{AUC}, or Area Under the receiver operating characteristic Curve, represents the probability that the model ranks a random positive example higher than a random negative example. We choose to display testing classifications for each machine learning model in the form of a Confusion Matrix. In each confusion matrix, class 0 corresponds to class P, class 1 corresponds to class S, and class 2 corresponds to class W. Accuracy, precision, recall, F1 score, and AUC can all be derived from a confusion matrix. \section{Results} We evaluate the performance of the aforementioned methodologies primarily through testing accuracy. The testing accuracies for each methodology are described in Table.~\ref{table:acc}. F1 Score and AUC Score are provided for each machine learning technique; however, it will suffice to focus solely on accuracy.\begin{table}[!htbp] \caption{Performance of various machine learning models in sleep stage classification.} \centerline{\begin{tabular}{lllll} \multirow{2}{*}{\textit{\textbf{Classifier}}} & \multirow{2}{*}{\textit{\textbf{Accuracy}}} & \multirow{2}{*}{\textit{\textbf{F1 Score}}} & \multirow{2}{*}{\textit{\textbf{AUC Score}}}\\\\ \textit{Random Forest} & 95.78\% &96\% &.9954\\ \textit{ANN} & 93.31\% &93.9\% & .9867 \\ \textit{Decision Tree Classifier} & 92.77\% &93\% &.9427\\ \textit{Logistic Regression} & 77.33\% &77\% &.9242\\ \textit{Naive Bayes} & 74.37\% &74\% &.9011\\ \end{tabular}} \label{table:acc} \end{table} Notably, the highest performing classifier is the Random Forest model with a testing accuracy of 95.78\%. The confusion matrix for the testing classification of this model is shown in Fig.~\ref{fig:rf_cm}. Other metrics such as precision and recall may be derived from the confusion matrix. The model performs excellently on class 0, which corresponds to paradoxical sleep. The most frequently misclassified prediction-label pair occurred between slow-wave sleep and wakefulness. There were 1017 instances of predicting wakefulness where the true label was slow-wave and 606 samples where the model predicted slow-wave sleep where the true label was wake. \begin{figure}[!htbp] \centering \begin{minipage}{0.24\textwidth} \centerline{ \scalebox{.23}{ \includegraphics{figures/rf_cm.png}} } \caption{Confusion matrix for the Random Forest model with overall accuracy of 95.78\%.} \label{fig:rf_cm} \end{minipage} \begin{minipage}{0.24\textwidth} \centerline{ \scalebox{.21}{ \includegraphics{figures/dt_cm.png}} } \caption{Confusion matrix for the Decision Tree model with overall accuracy of 92.77\%.} \label{fig:dt_cm} \end{minipage} \begin{minipage}{0.24\textwidth} \centerline{ \scalebox{.32}{ \includegraphics{figures/lr_cm.png}} } \caption{Confusion matrix for the Logistic Regression model with overall accuracy of 77.33\%.} \label{fig:lr_cm} \end{minipage} \begin{minipage}{0.24\textwidth} \centerline{ \scalebox{.32}{ \includegraphics{figures/nb_cm.png}} } \caption{Confusion matrix for the Naive Bayes model with overall accuracy of 74.37\%.} \label{fig:nb_cm} \end{minipage}\hfill \end{figure} The second-highest performing classifier is the Artificial Neural Network with a testing accuracy of 93.31\%. Across the entire testing partition, the model achieves over 93\% categorical accuracy, which is comparable or higher than many other methodologies in the literature \cite{b5,b19,b20}. The confusion matrix for the testing classification of this model is shown in Fig.~\ref{fig:ann_cm}. The prediction-label pair that was most frequently misclassified by the ANN occurred when the model predicted slow-wave and the true label was wake. Interestingly, this is the same confusion pair that occurred most frequently in the Random Forest model. Theoretically, there is a dimension that would reliably distinguish between slow-wave and wake. Future research will investigate this relationship and attempt to distinguish more reliably and accurately between these two classes. The ANN achieved a high F1 Score and AUC Score of 93.9\% and .9867, respectively. After training for only 50 epochs, the model achieves a testing categorical accuracy of 94.01\%, testing precision of 94.54\%, testing recall of 93.43\%, and a testing AUC of 99\%. The value of these metrics over the period of training are shown in Fig.~\ref{fig:loss}, Fig.~\ref{fig:precision}, and Fig.~\ref{fig:recall}. \pgf[.5]{cm.pgf}{Confusion matrix for the Artificial Neural Network classifier with overall accuracy of 93.31\%.}{fig:ann_cm} \begin{figure}[!htbp] \centering \begin{minipage}{0.24\textwidth} \centerline{\scalebox{.25}{ \import{figures}{loss.pgf} }}\caption{Loss curve for training and validation data over 50 epochs.}\label{fig:loss} \end{minipage}\hfill \begin{minipage}{0.24\textwidth} \centerline{\scalebox{.25}{ \import{figures}{categorical_accuracy.pgf} }} \caption{Accuracy curve for training and validation data over 50 epochs.} \label{fig:acc} \end{minipage} \begin{minipage}{0.24\textwidth} \centerline{\scalebox{.25}{ \import{figures}{precision.pgf} }} \caption{Precision curve for training and validation data over 50 epochs.} \label{fig:precision} \end{minipage} \begin{minipage}{0.24\textwidth} \centerline{\scalebox{.25}{ \import{figures}{recall.pgf} }} \caption{Recall curve for training and validation data over 50 epochs.} \label{fig:recall} \end{minipage} \end{figure} Not only did this model achieve a high degree of categorical accuracy, precision, and recall, but it did this with very little training and computation. All training instances consisted of only 50 epochs, each of which took approximately 220.66~seconds when run on a 2.4 GHz 7th Generation Intel(R) Core(T M) i7-7700HQ Quad-Core Processor with 16GB (2x8GB) DDR4 at 2400Mhz. The Decision Tree model performed well with an accuracy of 92.77\%; however, we do not discuss this model any further because it is a special case of the Random Forest. Logistic Regression and Naive Bayes had testing accuracies of 77.33\% and 74.37\%, respectively. These low accuracies suggest that this vigilance state classification problem is not trivial and that the accuracies reached by the Random Forest and the Artifical Neural Network are remarkable achievements.
{'timestamp': '2021-11-08T02:00:37', 'yymm': '2111', 'arxiv_id': '2111.03085', 'language': 'en', 'url': 'https://arxiv.org/abs/2111.03085'}
arxiv